如何手动检查json网络令牌是否有效?

时间:2018-09-06 09:16:44

标签: 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 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(...);
    }
}

其中端点verifyToken具有[Authorize]属性,并且仅返回未经授权(默认)或确定(来自代码)

1 个答案:

答案 0 :(得分:-1)

您可以尝试以下代码

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; 
}