場景:
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中文網其他相關文章!