.NET Core 2.0身份和jwt?

编程入门 行业动态 更新时间:2024-10-23 14:24:02
本文介绍了.NET Core 2.0身份和jwt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I've been looking around and trying to do more research on .NET Core Identity (docs.microsoft/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,然后将其用作我的身份验证/授权( blogs.msdn.microsoft/webdev/2017/04/06/jwt-validation-and-authorization-in-asp- net-core/),但是-我是否需要继续并启动一个新服务器来充当jwt的授权服务器?如果是这样,我就不会这样做(太贵了).

I can go ahead and configure jwt and then use it as my authentication/authorization (blogs.msdn.microsoft/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?

本文发布于:2023-11-14 00:46:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585760.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份   Core   NET   jwt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!