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.
To configure your ASP.NET Core Web API application for token-based authentication:
Create constants for the token audience and issuer:
const string TokenAudience = "Myself"; const string TokenIssuer = "MyProject";
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; });
Add the following line in your Startup.cs file, before any middleware that requires user information:
app.UseAuthentication();
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); } }
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); }
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!