[英].NET Core 2.0 Identity AND jwt?
我一直在四處尋找並嘗試對.NET核心身份進行更多研究( 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應用程序中使用默認身份作為身份驗證/授權進行滾動,到目前為止它一直運行良好。
我遇到了障礙,我認為這是我理解.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端點?
我意識到這是一個開放式的問題,但它的核心是:
.NET Core Identity和JWT可以共存嗎? 或者我必須選擇其中一個? 我有MVC和web api,並希望兩者兼顧。
您可以驗證用戶名和密碼並生成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步: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); }
步驟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);
要生成令牌,請執行以下操作:
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; }
有很多方法可以做到這一點。 最常見的是:驗證身份用戶 - >獲取用戶標識符 - >基於標識符生成和返回令牌 - >使用端點的授權
希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.