Home > Backend Development > C++ > How to Implement Token-Based Authentication in ASP.NET Core?

How to Implement Token-Based Authentication in ASP.NET Core?

Linda Hamilton
Release: 2024-12-30 04:39:57
Original
620 people have browsed it

How to Implement Token-Based Authentication in ASP.NET Core?

Token-Based Authentication in ASP.NET Core

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);
}
Copy after login

Next, configure the authentication pipeline within the Configure method:

app.UseAuthentication();
app.UseAuthorization();
Copy after login

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());
});
Copy after login

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template