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

How to Implement Token-Based Authentication in ASP.NET Core for an AngularJS Application?

DDD
Release: 2024-12-27 18:53:12
Original
215 people have browsed it

How to Implement Token-Based Authentication in ASP.NET Core for an AngularJS Application?

Token-Based Authentication in ASP.NET Core


Scenario

Suppose you have an ASP.NET Core application where you want to implement token-based authentication for an AngularJS application. The AngularJS application will make a request to a specific URL passing a username and password. The Web API will authorize the user and return an access token, which the AngularJS app will use in subsequent requests.

How to Configure Token-Based Authentication in ASP.NET Core

To configure your ASP.NET Core Web API application for token-based authentication:

1. Define Constants

Create constants for the token audience and issuer:

const string TokenAudience = "Myself";
const string TokenIssuer = "MyProject";
Copy after login

2. Configure Services

In your Startup.cs file, add the following to the ConfigureServices method:

var keySecret = authenticationConfiguration["JwtSigningKey"];
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));

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

3. Set Up Authentication

Add the following line in your Startup.cs file, before any middleware that requires user information:

app.UseAuthentication();
Copy after login

4. Build the Token

Create a class to handle JWT token generation:

class JwtSignInHandler
{
    public const string TokenAudience = "Myself";
    public const string TokenIssuer = "MyProject";
    private readonly SymmetricSecurityKey key;

    public JwtSignInHandler(SymmetricSecurityKey symmetricKey)
    {
        this.key = symmetricKey;
    }

    public string BuildJwt(ClaimsPrincipal principal)
    {
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: TokenIssuer,
            audience: TokenAudience,
            claims: principal.Claims,
            expires: DateTime.Now.AddMinutes(20),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
Copy after login

5. Return the Token

In the controller action where you want to return the token, call the BuildJwt method:

[HttpPost]
public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
{
    var principal = new System.Security.Claims.ClaimsPrincipal(new[]
    {
        new System.Security.Claims.ClaimsIdentity(new[]
        {
            new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User")
        })
    });
    return tokenFactory.BuildJwt(principal);
}
Copy after login

With these steps, your ASP.NET Core Web API application will be configured to use token-based authentication, enabling your AngularJS application to securely access protected resources.

The above is the detailed content of How to Implement Token-Based Authentication in ASP.NET Core for an AngularJS Application?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template