两个独立的项目,DotNet核心3: API和Web。
MVC和Mobile应用程序都只与API对话。
mvc需要对用户进行API身份验证(并且还能够进行google身份验证,并传递给API),这是通过向MVC上的/account/ login /提交的登录页面完成的,后者然后向返回JWT令牌的API打开一个httpclient请求。API将使用JWT来执行来自web应用程序的所有进一步操作。
不幸的是,很多文档只处理API返回令牌,或者使用SPA框架进行身份验证。我正在考虑使用MVC作为客户端。
有一些问题访问返回的JWT声明,并研究如何将其存储在MVC应用程序使用的身份验证cookie中。
API接口控制器 / Auth /
public IActionResult Post()
{
//Do auth check here
if (Request.Form["username"] == "test@test.com" && Request.Form["password"] == "test")
{
var authClaims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "testUsername"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, "ID"),
new Claim("Name", "testName"),
new Claim("Email", "testEmail"),
};
var authSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("qwertyuiopasdfghjklzxcvbnm123456"));
var token = new JwtSecurityToken(
issuer: "https://localhost",
audience: "https://localhost",
expires: DateTime.Now.AddHours(3),
claims: authClaims,
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
MVC上的/account/登录Post操作
var httpClient = _httpClientFactory.CreateClient("API");
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
var response = await httpClient.PostAsync("https://localhost:{port}/auth", formContent);
if (response.IsSuccessStatusCode)
{
var tokenResponse = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(tokenResponse);
var token = json.RootElement.GetProperty("token").GetRawText();
var expires = json.RootElement.GetProperty("expiration").GetRawText();
var jwt = new JwtSecurityToken(token);
//Access claims from jwt here, set the identity claims
//Set cookie authentication for MVC
var iden = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(iden);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
//Redirect to account page
}
标记从API中正确返回,但将给出
有三个段,但没有采用适当的JWS格式。
在var jwt = new JwtSecurityToken(token);
步骤中出错。
我是不是做错了?我是否应该使用javascript和登录表单提交直接将JWT发送到API,将JWT添加到标头中并将MVC切换到JwtBearer身份验证?
发布于 2020-08-19 10:56:23
我也遇到了同样的问题,我使用以下代码读取令牌:
jwt = jwt.Replace("Bearer ", string.Empty);
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(jwt);
然后可以使用jwtToken.Claims
集合查看声明。
https://stackoverflow.com/questions/58212217
复制相似问题