Home > Backend Development > C++ > How to Configure Token-Based Authentication in ASP.NET Core Web API for AngularJS Applications?

How to Configure Token-Based Authentication in ASP.NET Core Web API for AngularJS Applications?

Linda Hamilton
Release: 2024-12-30 14:23:13
Original
441 people have browsed it

How to Configure Token-Based Authentication in ASP.NET Core Web API for AngularJS Applications?

Configuring Token-Based Authentication in ASP.NET Core WebApi

Challenge

In ASP.NET Core applications, implementing token-based authentication can be a challenge. Conventional examples typically revolve around cookie authentication or external authentication providers. However, when working with a scenario where an AngularJS application requests a token from a /token endpoint, passing username and password, it's crucial to understand how to configure the WebApi application accordingly.

Authentication Setup

To configure token-based authentication in ASP.NET Core WebApi, follow these steps:

  1. Define Token Properties: Start by creating constants for token parameters, including the token audience and issuer.
const string TokenAudience = "Myself";
const string TokenIssuer = "MyProject";
Copy after login
  1. Configure DI Services:

    • In your Startup.cs ConfigureServices method, add dependency injection for the JwtSignInHandler class.
    • Configure authentication to default to JWT and set token validation parameters.
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
  1. Enable Authentication Middleware: Add the UseAuthentication middleware in the request pipeline before any middleware requiring user information.
app.UseAuthentication();
Copy after login
  1. Define Authorization Policy (Optional): Optionally, you can define an AuthorizationPolicy to restrict access to controllers and actions based on bearer tokens.
services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
        .RequireAuthenticatedUser().Build());
});
Copy after login
  1. Build the JWT: Create a JwtSignInHandler class for 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
  1. Implement Token Generation in Controller: Within a controller action, use the JwtSignInHandler to generate a token.
[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
  1. Jwt Testing: Acquire a token and validate its signature using the secret from your configuration file.

The above is the detailed content of How to Configure Token-Based Authentication in ASP.NET Core Web API for AngularJS Applications?. 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