Cookies Authentication:
.NET Core provides a versatile and robust authentication system, making it easy to implement secure user access in applications. Let's take a look at a simple code example using .NET Core's built-in authentication middleware to protect a web application with cookie authentication.
// In Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add authentication middleware
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "YourAuthCookie"; // Customize cookie name
options.ExpireTimeSpan = TimeSpan.FromMinutes(30); // Set cookie expiration time
options.LoginPath = "/Account/Login"; // Redirect to login page for unauthorized users
options.LogoutPath = "/Account/Logout"; // Redirect to logout page after logout
});
// Other service configurations...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other app configurations...
// Use authentication middleware
app.UseAuthentication();
// Other middleware and routes...
}
}
In this example, we configure the authentication middleware to use cookie authentication as the default scheme. We customize the cookie's name, expiration time, and specify the login and logout paths. The middleware will automatically handle authentication, and if a user is not authenticated, they will be redirected to the login page.
Note that this is a basic example, and .NET Core authentication supports various methods like JWT, OAuth, and OpenID Connect for more complex scenarios.