栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

.Net Core 3.1更新:

David Fowler(ASP .NET
Core团队的架构师)汇集了一组非常简单的任务应用程序,其中包括演示JWT的简单应用程序。我很快将把他的更新和简单化的风格纳入本文。

为.Net Core 2更新:

此答案的先前版本使用RSA;如果生成令牌的相同代码也正在验证令牌,则实际上是没有必要的。但是,如果您要分配职责,则可能仍想使用的实例来执行此操作

Microsoft.IdentityModel.Tokens.RsaSecurityKey

  1. 创建一些常量,稍后我们将使用它;这是我所做的:

    const string TokenAudience = "Myself";

    const string TokenIssuer = “MyProject”;

  2. 将此添加到您的Startup.cs的中

    ConfigureServices
    。稍后我们将使用依赖项注入来访问这些设置。我假设您
    authenticationConfiguration
    是一个
    ConfigurationSection
    Configuration
    对象,以便可以为调试和生产使用不同的配置。确保您安全地存储密钥!它可以是任何字符串。

    var keySecret = authenticationConfiguration["JwtSigningKey"];

    var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));

    services.AddTransient(_ => new JwtSignInHandler(symmetricKey));

    services.AddAuthentication(options =>
    {
    // This causes the default authentication scheme to be JWT.
    // Without this, the Authorization header is not checked and
    // you’ll get no results. However, this also means that if
    // you’re already using cookies in your app, they won’t be
    // checked by default.
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
    options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
    options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
    options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
    });

我已经看到其他答案会更改其他设置,例如

ClockSkew
;设置了默认值,使其可以在时钟不完全同步的分布式环境中工作。这些是您唯一需要更改的设置。

  1. 设置身份验证。在需要您的
    User
    信息的任何中间件之前,您应该有此行
    app.UseMvc()
    app.UseAuthentication();

请注意,这不会导致您的令牌与

SignInManager
或其他任何东西一起发出。您将需要提供自己的输出JWT的机制-参见下文。

  1. 您可能需要指定一个

    AuthorizationPolicy
    。这将允许您使用来指定仅允许Bearer令牌作为身份验证的控制器和操作
    [Authorize("Bearer")]

    services.AddAuthorization(auth =>

    {
    auth.AddPolicy(“Bearer”, new AuthorizationPolicyBuilder()
    .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
    .RequireAuthenticatedUser().Build());
    });

  2. 这是棘手的部分:构建令牌。

    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);}

    }

然后,在需要令牌的控制器中,如下所示:

    [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);}

在这里,我假设您已经有一个校长。如果您使用的是Identity,则可以使用

IUserClaimsPrincipalFactory<>
将转换
User
ClaimsPrincipal

  1. 要测试它 :获得令牌,将其放入jwt.io的表单中。我上面提供的说明还允许您使用配置中的密码来验证签名!

  2. 如果要在HTML页面的部分视图中呈现此视图,并与.Net 4.5中的仅承载身份验证结合使用,则现在可以使用进行

    ViewComponent
    相同的操作。它与上面的“控制器操作”代码基本相同。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465529.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号