asp.net-core - 带有 ASP.NET Identity 3 的 JWT 不记名 token

标签 asp.net-core openid-connect bearer-token asp.net-identity-3 aspnet-contrib

基于 Shaun Luttin 在 https://stackoverflow.com/a/30857524 上的出色示例我能够使用该代码生成和使用不记名 token 。较小的更改是获取最新的软件包:

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

尽管代码是一个很好的开始,但它并不是一个完全集成了 ASP.NET Identity 的完整解决方案。我修改 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。有没有更好的方法来集成 ASP.NET Identity?

最佳答案

您的实现看起来不错,有 3 条小注释:

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

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

    关于asp.net-core - 带有 ASP.NET Identity 3 的 JWT 不记名 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031776/

    相关文章:

    c# - 转发到 Controller 的动态 DateTime 控件数量

    azure - azure 用户 session 生命周期

    python - Angular.js 中基于 OpenID 连接的身份验证与 (drf oidc) Django 休息框架后端

    jquery - 在HTTP拦截器中添加 header

    asp.net - C#/OWIN/ASP.NET : can I *manually* generate and get a valid bearer token string in my API code?

    c# - HttpContext.SignOutAsync() 既不注销用户也不删除本地 cookie

    c# - Azure AD 图 : Secure binary serialization is not supported on this platform

    vue.js - 在 Vue 应用程序中导入 @aspnet/signalr

    asp.net - 客户端和服务 Web 应用程序可以共享同一个 Azure Active Directory 应用程序吗?

    c# - 没有 Exp 和默认 Prop 的 dotnet 中的 Jwt token