【问题标题】:Jwt authentication, authorization any requestJwt认证,授权任何请求
【发布时间】:2022-01-31 00:53:53
【问题描述】:

我克隆了这个 github 项目:https://github.com/cornflourblue/dotnet-5-jwt-authentication-api

所以我遵循函数来验证 jtw 令牌,并在成功的 jwt 验证后将用户附加到上下文:

private void attachUserToContext(HttpContext context, string token)
{
   try
   {
      //...
      var jwtToken = (JwtSecurityToken)validatedToken;
      var userId = jwtToken.Claims.First(x => x.Type == "username").Value;

      // attach user to context on successful jwt validation
      context.Items["User"] = userId;
   }
   catch
   {
      // do nothing if jwt validation fails
      // user is not attached to context so request won't have access to secure routes
   }
}

所以AuthorizeAttribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var username = context.HttpContext.Items["User"];
        if (username == null)
        {
            // not logged in
            context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
        }
    }
}

但由于某种原因,它允许所有请求,甚至是没有标头信息的请求。如果您需要更多信息,请询问!

【问题讨论】:

  • 不要滚动你自己的Authorize trait。使用内置机制
  • @DanielA.White 能否分享一个链接,我可以在其中找到有关“内置机制”的更多信息?

标签: c# asp.net-mvc jwt authorization


【解决方案1】:

我不知道为什么自定义 AuthorizeAttribute 不起作用但我设置相同 查询以测试 HttpContext.Items["User"] 不为空,现在它可以工作了...:

[Authorize]
[HttpGet("Select")]
public IActionResult Select()
{
   try
   {
      if (HttpContext.Items["User"] == null)
      {
         return Conflict(new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized });
      }
      return Ok(TestService.Select());
   }
   catch (Exception ex)
   {
      return Conflict(ex);
   }
}

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2017-09-11
    • 2020-09-06
    • 2018-10-01
    • 2020-02-11
    • 2019-04-18
    • 2021-09-29
    • 2020-11-29
    • 2017-01-14
    相关资源
    最近更新 更多