c# - .NET Core 2.0 身份和 jwt?

标签 c# asp.net asp.net-mvc asp.net-core jwt

我一直在四处寻找并尝试对 .NET Core Identity ( https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&tabs=visual-studio%2Caspnetcore2x) 和 Jwt(json 网络 token )进行更多研究。我一直在使用默认身份作为我的 .NET Core 2.0 应用程序中的身份验证/授权,到目前为止它运行良好。

我遇到了障碍,我认为这是我理解 .NET Core 身份和 jwt 的方式。我的应用程序有 MVC 和 web api。我理想情况下希望保护 web api,但我听说现在最好的方法是通过 jwt。很好 - 很酷。

我可以继续配置 jwt,然后将其用作我的身份验证/授权(https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/),但是 - 我是否需要继续并启动一个新服务器作为 jwt 的授权服务器?如果是这样,我不会那样做(太贵了)。

如果我使用 jwt,我的 .NET Core 身份代码怎么办?那必须消失吗?如果它可以共存,我如何使用 Identity 授权我的 MVC 页面以及使用 jwt 授权我的 api 端点?

我意识到这是一个开放式问题,但它的核心是:

.NET Core Identity 和 JWT 可以共存吗?或者我必须选择其中之一吗?我有 MVC 和一个网络 API,并希望保护两者。

最佳答案

是的,你可以。 逻辑过程在这个方法中:

第 1 步:获取用户声明

var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);

  • 您将进入 GetClaimsIdentity

    private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            return await Task.FromResult<ClaimsIdentity>(null);
    
        var userToVerify = await _userManager.FindByNameAsync(userName);                
    
        if (userToVerify == null) {
            userToVerify = await _userManager.FindByEmailAsync(userName);
            if (userToVerify == null)  {
                return await Task.FromResult<ClaimsIdentity>(null);
            }
        }
        // check the credentials
        if (await _userManager.CheckPasswordAsync(userToVerify, password))
        {
            _claims = await _userManager.GetClaimsAsync(userToVerify);
    
            return await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userToVerify.UserName, userToVerify.Id, _claims));
        }
        // Credentials are invalid, or account doesn't exist
        return await Task.FromResult<ClaimsIdentity>(null);
    }
    

第 2 步:将您需要添加到 token 的所有用户声明分组 - 使用 System.Security.Claims

 public ClaimsIdentity GenerateClaimsIdentity(string userName, string id, IList<Claim> claims)
    {
        claims.Add(new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id));

        // If your security is role based you can get then with the RoleManager and add then here as claims

        // Ask here for all claims your app need to validate later 

        return new ClaimsIdentity(new GenericIdentity(userName, "Token"), claims);
    }

第 3 步:然后回到您的方法,您必须生成并返回 JWT token

jwt = await jwtFactory.GenerateEncodedToken(userName, identity);
return new OkObjectResult(jwt);
  • 要生成 token ,请执行以下操作:

    public async Task<string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
    {
        List<Claim> claims = new List<Claim>();
        //Config claims
        claims.Add(new Claim(JwtRegisteredClaimNames.Sub, userName));
        claims.Add(new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()));
        claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));
        //End Config claims
        claims.AddRange(identity.FindAll(Helpers.Constants.Strings.JwtClaimIdentifiers.Roles));
        claims.AddRange(identity.FindAll("EspecificClaimName"));
    
    
        // Create the JWT security token and encode it.
        var jwt = new JwtSecurityToken(
            issuer: _jwtOptions.Issuer,
            audience: _jwtOptions.Audience,
            claims: claims,
            notBefore: _jwtOptions.NotBefore,
            expires: _jwtOptions.Expiration,
            signingCredentials: _jwtOptions.SigningCredentials);
    
        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
    
        return encodedJwt;
    }
    

有很多方法可以做到这一点。 最常见的是: 验证身份用户 --> 获取用户标识符 --> 根据标识符生成并返回 token --> 对端点使用授权

希望对你有帮助

关于c# - .NET Core 2.0 身份和 jwt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316985/

相关文章:

c# - C# 6.0 中的 Monadic 空值检查

c# - 在 getter 中返回子控件的属性是无限递归的吗?

c# - html.dropdownlist 的 onchange 事件

c# - 为什么 ASP.NET 会终止异步请求?

c# - 如何根据条件更改模型的可编辑属性

c# - 如何在 C# 中声明字符串引用变量?

c# - 将标志拆分为规范化表

c# - GridView 中的下拉列表

c# - 在编辑器 onload 中显示 Datepicker 而不是需要用户选择

asp.net-mvc - 优化和 CDN 时,Font Awesome 在 Firefox 中不起作用