C# 如何手动检查json web令牌是否有效?
我想确定JWT令牌在C# 如何手动检查json web令牌是否有效?,c#,asp.net-core,.net-core,asp.net-core-mvc,C#,Asp.net Core,.net Core,Asp.net Core Mvc,我想确定JWT令牌在[AllowAnonymouse]]端点中是否有效 编辑 我有一个可以被任何人(授权和未授权的人)访问的端点,然后:如果该用户有http授权头,或者他在cookie中有令牌,并且他的令牌有效,那么将他重定向到X,否则重定向到Y 我的想法的伪代码: [Route("Passport/")] public IActionResult Passport() { if (this.User.Identity.IsAuthenticated) or
[AllowAnonymouse]]
端点中是否有效
编辑
我有一个可以被任何人(授权和未授权的人)访问的端点,然后:如果该用户有http授权头,或者他在cookie中有令牌,并且他的令牌有效,那么将他重定向到X,否则重定向到Y 我的想法的伪代码:
[Route("Passport/")]
public IActionResult Passport()
{
if (this.User.Identity.IsAuthenticated)
or pseudocode:
if (tokenIsValid(getJWTTokenFromHeader()));
{
return RedirectToAction("Resources");
}
else
{
return RedirectToAction("Login");
}
}
我想到了这样的事情:
[Route("Passport/")]
public IActionResult Passport()
{
var token = ExtractTokenFromHeader();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue
("application/json"));
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var get = client.GetAsync($"http://localhost/verifyToken").Result;
var responseBody = await get.Content.ReadAsStringAsync().ConfigureAwait(false);
switch (get.StatusCode)
{
case HttpStatusCode.Unauthorized:
return RedirectToAction("Login");
case HttpStatusCode.OK:
return RedirectToAction("Resources");
default:
return RedirectToAction(...);
}
}
如果endpoint verifyToken具有[Authorize]
属性,并且只返回Unauthorized(默认)或OK(来自代码)您可以在下面的代码中尝试
private static bool ValidateJWTToken(string token, out string username) {
username = null;
var simplePrinciple = JwtManager.GetPrincipal(token);
var identity = simplePrinciple.Identity as ClaimsIdentity;
if (identity == null) return false;
if (!identity.IsAuthenticated) return false;
}
请详细说明,您的问题不清楚我有一个端点,任何人(授权和未授权的人)都可以访问该端点然后:如果该用户有http授权头,或者他在Cookie中有令牌,并且他的令牌有效,则将他重定向到X,否则将使用策略,而不是在控制器方法中检查令牌:@aguafrommars听起来不错,但是我仍然需要确定令牌在
HandleRequirement
中是否有效?那么如果(this.User.Identity.IsAuthenticated)仅使用有什么错呢?