加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 带有ASP.NET身份3的JWT承载令牌

发布时间:2020-12-16 03:24:12 所属栏目:asp.Net 来源:网络整理
导读:基于Shaun Luttin在 https://stackoverflow.com/a/30857524的优秀示例,我能够使用该代码生成和使用承载令牌.微小的变化是获得最新的包: "dependencies": { "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final","AspNet.Security.OpenIdConnect
基于Shaun Luttin在 https://stackoverflow.com/a/30857524的优秀示例,我能够使用该代码生成和使用承载令牌.微小的变化是获得最新的包:

"dependencies": {
  "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final","AspNet.Security.OpenIdConnect.Server": "1.0.0-beta4"
}

虽然代码是一个很好的开始,但它并不是一个完全集成w / ASP.NET身份的完整解决方案.我修改了AuthorizationProvider类,如下所示:

public override Task GrantResourceOwnerCredentials(
    GrantResourceOwnerCredentialsContext context)
{
    var user = _userManager.FindByNameAsync(context.UserName).Result;
    if (user == null)
    {
        context.Rejected("The user name or password is incorrect.");
    }
    else
    {
        var signInManager = context.HttpContext.RequestServices
            .GetRequiredService<SignInManager<ApplicationUser>>();

        if (signInManager.CanSignInAsync(user).Result &&
            _userManager.CheckPasswordAsync(user,context.Password).Result)
        {
            var principal = signInManager.CreateUserPrincipalAsync(user).Result;

            //To avoid leaking confidential data,AspNet.Security.OpenIdConnect.Server
            //refuses to serialize the claims that don't explicitly specify a destination.
            foreach (var claim in principal.Claims)
                claim.WithDestination("token id_token");

            context.Validated(principal);
        }
        else
            context.Rejected("The user name or password is incorrect.");
    }

    return Task.FromResult(0);
}

我正在使用CreateUserPrincipalAsync为Validated方法创建ClaimsPrincipal.是否有更好的方法来集成w / ASP.NET身份?

解决方法

你的实现看起来很好,次要的3条评论:

>您应该使用async / await来避免.Result阻塞调用.
>您应该考虑按照OAuth2规范的要求实施强力对策:https://tools.ietf.org/html/rfc6749#section-4.3.2.您可以轻松地使用Identity 3,因为它为“锁定”提供本机支持.
>您必须记住,此实现将导致序列化与用户关联的所有声明(甚至是自定义声明),其中可能包括机密数据.

最后两点在OpenIddict(一个内部使用AspNet.Security.OpenIdConnect.Server的全新实验性OIDC服务器)中得到缓解,因此请不要犹豫,看看它的默认实现:https://github.com/openiddict/core/blob/dev/src/OpenIddict.Core/OpenIddictProvider.cs#L353.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读