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
Release: 2024-12-26 09:12:10
Original
606 people have browsed it

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

Middleware:

app.UseAuthentication();
Copy after login

Authorization Policy (optional):

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

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

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