.NET Core 2.0身份和jwt? [英] .NET Core 2.0 Identity AND jwt?

查看:120
本文介绍了.NET Core 2.0身份和jwt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找并尝试对.NET Core身份进行更多研究(

I've been looking around and trying to do more research on .NET Core Identity (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.1&tabs=visual-studio%2Caspnetcore2x) and Jwt (json web tokens). I've been rolling with the default Identity as authentication/authorization in my .NET Core 2.0 app and it has been working well so far.

我遇到了一个障碍,我认为这是我对.NET Core身份和jwt的理解的方式.我的应用程序具有MVC和Web API.我想理想地要保护Web api,但是我听说现在做到这一点的最佳方法是通过jwt.很好-很酷.

I'm running into a roadblock and I think it's the way of my understanding of .NET Core identity and jwt. My application has MVC and an web api. I would ideally like to secure the web api, but I hear the best way to do that now is through jwt. Good - cool.

我可以继续配置jwt,然后将其用作我的身份验证/授权(

I can go ahead and configure jwt and then use it as my authentication/authorization (https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/), but - do I need to go ahead and spin up a new server to serve as the authorization server for jwt? If so, I'm not going to do that (too expensive).

如果我与jwt一起使用,那么.NET Core身份代码又如何呢?那那一定要消失吗?如果可以共存,我该如何使用Identity来授权我的MVC页面以及使用jwt来授权我的api端点?

What about my .NET Core identity code if I do go with jwt? Does that have to go away then? If it can co-exist, how might I authorize my MVC pages with Identity and my api endpoints with jwt?

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

I realize this is an open-ended question, but the core of it is:

.NET核心标识和JWT是否可以共存?还是我必须选择其中一个?我有MVC和网络api,并希望同时保护两者.

推荐答案

是的,可以. 逻辑过程就是这种方法:

Yes, you can. The logic process is in this method:

第1步:GetUserClaims

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

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

  • 您将进入GetClaimsIdentity

  • Into GetClaimsIdentity you will

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:将需要添加到令牌中的所有用户声明分组-使用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令牌

jwt = await jwtFactory.GenerateEncodedToken(userName, identity);
return new OkObjectResult(jwt);

  • 要生成令牌,请执行以下操作:

    • To generate token do something like this:

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

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

      There are many ways to do this. The most common is: Validate Identity User --> Get User identifiers --> Generate and Return Token Based on Identifiers --> Use Authorization for endpoints

      希望获得帮助

      这篇关于.NET Core 2.0身份和jwt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆