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

How to Implement Token-Based Authentication with AngularJS and ASP.NET Core?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 09:12:10528browse

How to Implement Token-Based Authentication with AngularJS and ASP.NET Core?

Token Based Authentication in ASP.NET Core

Scenario:

An AngularJS application requests a token from a WebApi by providing username and password. Upon successful authorization, the WebApi returns an access token for use by the AngularJS app in subsequent requests.

Configuration:

Startup.cs:

Configure authentication services:

services.AddTransient(_ => new JwtSignInHandler(symmetricKey));

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
    options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
    options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
    options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
});

Middleware:

app.UseAuthentication();

Authorization Policy (optional):

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
        .RequireAuthenticatedUser().Build());
});

Token Generation:

public class JwtSignInHandler
{
    public string BuildJwt(ClaimsPrincipal principal)
    {
        // Create credentials and token
        var token = new JwtSecurityToken(
            issuer: TokenIssuer,
            audience: TokenAudience,
            claims: principal.Claims,
            expires: DateTime.Now.AddMinutes(20),
            signingCredentials: creds
        );
        
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

[HttpPost]
public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
{
    // Create claims principal
    var principal = new ClaimsPrincipal(new[]
    {
        new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, "Demo User")
        })
    });
    return tokenFactory.BuildJwt(principal);
}

The above is the detailed content of How to Implement Token-Based Authentication with AngularJS and ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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