首页 > 后端开发 > C++ > 如何使用 AngularJS 和 ASP.NET Core 实现基于令牌的身份验证?

如何使用 AngularJS 和 ASP.NET Core 实现基于令牌的身份验证?

Susan Sarandon
发布: 2024-12-26 09:12:10
原创
581 人浏览过

How to Implement Token-Based Authentication with AngularJS and ASP.NET Core?

ASP.NET Core 中基于令牌的身份验证

场景:

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板