我一直在四处寻找并尝试对.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 回答
您可以验证用户名和密码并生成Jwt .
首先,确保您的API在startup.cs中设置了以下默认标识:
其次,您可以使用以下内容验证登录:
您可以设置这样的API控制器:
在你的get函数中,你现在可以生成你的Jwt .
是的你可以 . 逻辑过程在这个方法中:
Step 1: GetUserClaims
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
Step 2: Group all user claims you need add to the token - Use System.Security.Claims
Step 3: Then back on your method you have to generate and return the JWT Token
有很多方法可以做到这一点 . 最常见的:验证身份用户 - >获取用户标识符 - >基于标识符生成和返回令牌 - >使用 endpoints 授权
希望这有帮助