首页 文章

.NET Core 2.0身份和jwt?

提问于
浏览
3

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

我'm running into a roadblock and I think it'是我理解.NET核心身份和jwt的方式 . 我的应用程序有MVC和web api . 理想情况下我想保护网络API,但我听说现在最好的办法就是通过jwt . 好 - 很酷 .

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

如果我使用jwt,我的.NET核心身份代码怎么样?那必须消失吗?如果它可以共存,我如何使用Identity授权我的MVC页面和使用jwt授权我的api endpoints ?

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

Can .NET Core Identity and JWT co-exist? Or do I have to choose one or the other? I have MVC and an web api and would like to secure both.

2 回答

  • 3

    您可以验证用户名和密码并生成Jwt .

    首先,确保您的API在startup.cs中设置了以下默认标识:

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    其次,您可以使用以下内容验证登录:

    您可以设置这样的API控制器:

    [ApiController, Route("check")]
    public class TokenController : ControllerBase
    {
        private readonly SignInManager<IdentityUser> signin;
    
        public TokenController(SignInManager<IdentityUser> signin)
        {
            this.signin = signin;
        }
    
        [HttpGet]
        public async Task<string> Get(string user, string pass)
        {
            var result = await signin.PasswordSignInAsync(user, pass, true, false);
            if (result.Succeeded)
            {
                string token = "";
                return token;
            }
            return null;
        }
    }
    

    在你的get函数中,你现在可以生成你的Jwt .

  • 1

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

    Step 1: GetUserClaims

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

    Step 2: Group all user claims you need add to the token - Use 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);
        }
    

    Step 3: Then back on your method you have to generate and return the JWT Token

    jwt = await jwtFactory.GenerateEncodedToken(userName, identity);
    return new OkObjectResult(jwt);
    
    • 要生成令牌,请执行以下操作:
    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;
    }
    

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

    希望这有帮助

相关问题