Jwt Bearer Authentication 中间件始终将 User.Identity.IsAuthenticated 设置为 false

Posted

技术标签:

【中文标题】Jwt Bearer Authentication 中间件始终将 User.Identity.IsAuthenticated 设置为 false【英文标题】:Jwt Bearer Authentication middleware always sets User.Identity.IsAuthenticated to false 【发布时间】:2021-09-03 20:50:11 【问题描述】:

我已将 UseJwtBearerAuthentication 中间件添加到我的应用程序中以验证所有传入请求:

public void Configuration(IAppBuilder app)


    var config = new HttpConfiguration();
    WebApiConfig.Register(config);
    #region Autofac config

    var container =AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    #endregion
    #region RoutConfig

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    #endregion

    //Register middlewares
    app.UseJwtBearerAuthentication(new MyJwtAuthenticationOptions());
    app.UseAutofacMiddleware(container);
    app.Use<ReadBodyMiddleware>();
    app.UseWebApi(config);


这是我的 MyJwtAuthenticationOptions 类:

public class MyJwtAuthenticationOptions: JwtBearerAuthenticationOptions

    public MyJwtAuthenticationOptions()
    
        var secretkey = ConfigurationManager.AppSettings["SecretKey"].ToString();

        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active;
        AuthenticationType = "Basic";
        TokenValidationParameters = new TokenValidationParameters()
        
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretkey)),
            ValidAlgorithms = new string[]  SecurityAlgorithms.HmacSha256Signature 
        ;
    

现在让我们看看令牌是如何生成的:

public static string GenerateToken(string userid)

    var expireMin = ConfigurationManager.AppSettings["TokenExpirationMinutes"].ToString();
    var secretKey = ConfigurationManager.AppSettings["SecretKey"].ToString();

    byte[] key = Convert.FromBase64String(secretKey);
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);
    var descriptor = new SecurityTokenDescriptor
    
        Subject = new ClaimsIdentity(new[] 
              new Claim("UserId", userid), "Basic"),
        Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireMin)),
        SigningCredentials = new SigningCredentials(securityKey,
        SecurityAlgorithms.HmacSha256Signature)
    ;

    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
    JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
    return handler.WriteToken(token);

但是当我将生成的令牌放入 Authorization 标头并通过 Postman 发送到服务器时

HttpContext.Current.User.Identity.IsAuthenticated is always false

授权标头正确采用Bearer 格式

【问题讨论】:

你的控制器或方法有[Authorize]属性吗? 不...它没有...如果身份验证中间件是有效令牌,则应将 IsAuthenticated 设置为 true。 你有这方面的文件吗? 那么使用'UseJwtBearerAuthentication'中间件有什么意义呢? 它负责认证,授权目前不是我的情况。 【参考方案1】:

我的问题源于两点:

point1

public static void Register(HttpConfiguration config)

    // Owin auth
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
    config.MapHttpAttributeRoutes();
    config.Services.Insert(typeof(ModelBinderProvider), 0,
     new SimpleModelBinderProvider(typeof(DocumentModel), new FromFormDataBinding()));
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "controller/action/id",
        defaults: new  id = RouteParameter.Optional 
    );

此行与我使用的 api 的其他点不同 Signature

config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

改成这样:

config.Filters.Add(new HostAuthenticationFilter("Signature"));

第 2 点:

GenerateTokebn 类中我是这样读取密钥的:

byte[] key = Convert.FromBase64String(secretKey);

改成与MyJwtAuthenticationOptions类相同的这一行:

byte[] key = Encoding.UTF8.GetBytes(secretKey);

【讨论】:

以上是关于Jwt Bearer Authentication 中间件始终将 User.Identity.IsAuthenticated 设置为 false的主要内容,如果未能解决你的问题,请参考以下文章

Jwt Bearer Authentication 中间件始终将 User.Identity.IsAuthenticated 设置为 false

将 JWT Bearer Authentication Web API 与 Asp.Net Core 2.0 结合使用的问题

JWT Bearer ASP.Net Core 3.1 用户在服务器上为空白

AspNetCore 2.1 Bearer Token Authentication - 当前用户为空

JWT 为啥我们需要 Bearer word?

在 React 项目中,我应该在哪里传递 Bearer Authentication Token?