Tags
ASP.NET Core provides several options for authentication, including cookie-based authentication, token-based authentication (using JWT), and external authentication providers such as Google, Facebook, and Twitter. Here's a brief overview of how to set up JWT-based authentication in ASP.NET Core:
Add authentication middleware to the application's
Startup.cs
file. This middleware can be added by calling theAddAuthentication()
method and specifying the authentication scheme you want to use (in this case, JWT-based authentication).public void ConfigureServices(IServiceCollection services)
{
// Add authentication services
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
}Configure the authentication middleware to use the JWT-based authentication scheme. This is done in the
Configure()
method ofStartup.cs
.public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Add authentication middleware
app.UseAuthentication();
}Protect the desired routes or controllers with the
[Authorize]
attribute. This attribute can be placed at the controller or action level to restrict access to authorized users only.[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}Create a JWT token when the user successfully authenticates. This token will contain the user's claims, which can be used to authorize subsequent requests.
[HttpPost("login")]
public async Task<IActionResult> Login(LoginViewModel model)
{
// Validate user credentials
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
{
return Unauthorized();
}
// Create token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { token = tokenString });
}Add the JWT token to the Authorization header of subsequent requests. This can be done using a bearer token, like so:
Authorization: Bearer <Token>
About Sean Nelson
I like codes and stuff.
|
1 comments