场景:
AngularJS 应用程序通过以下方式从 WebApi 请求令牌提供用户名和密码。成功授权后,WebApi 将返回一个访问令牌,供 AngularJS 应用程序在后续请求中使用。
配置:
Startup.cs:
配置身份验证服务:
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; });
中间件:
app.UseAuthentication();
授权策略(可选):
services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType) .RequireAuthenticatedUser().Build()); });
代币世代:
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); }
以上是如何使用 AngularJS 和 ASP.NET Core 实现基于令牌的身份验证?的详细内容。更多信息请关注PHP中文网其他相关文章!