Implementing token-based authentication in ASP.NET Core can be a challenge, especially when transitioning from previous versions of the framework. This article provides detailed instructions on how to configure your WebApi application for token-based authentication, addressing common issues and updates for .NET Core versions.
Startup Configuration
In Startup.cs, configure your services and add the following code within the ConfigureServices method:
const string TokenAudience = "Myself"; const string TokenIssuer = "MyProject"; var claimsPrincipal = new System.Security.Claims.ClaimsPrincipal(new[] { new System.Security.Claims.ClaimsIdentity(new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User") }) }); public string BuildJwt() { var keySecret = authenticationConfiguration["JwtSigningKey"]; var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret)); var creds = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: TokenIssuer, audience: TokenAudience, claims: claimsPrincipal.Claims, expires: DateTime.Now.AddMinutes(20), signingCredentials: creds ); return new JwtSecurityTokenHandler().WriteToken(token); }
Next, configure the authentication pipeline within the Configure method:
app.UseAuthentication(); app.UseAuthorization();
Use Authentication Middleware
Ensure the app.UseAuthentication() middleware is placed before any middleware that requires user information, such as app.UseMvc(). This will check for a Bearer token in the Authorization header.
Authorization Policy (Optional)
If desired, specify an authorization policy to restrict access to certain controllers or actions only for Bearer tokens:
services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType) .RequireAuthenticatedUser().Build()); });
Generating the Token
To generate the token for authentication, use the BuildJwt method defined earlier. For example, in a controller action:
[HttpPost] public string AnonymousSignIn() { return BuildJwt(); }
Testing and Validation
Obtain the token and validate its signature using a tool like jwt.io, using the secret key specified in authenticationConfiguration.
By following these instructions carefully, you can successfully implement token-based authentication in your ASP.NET Core WebApi application and secure your API endpoints effectively.
The above is the detailed content of How to Implement Token-Based Authentication in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!