Jwt Bearer Authentication 中间件总是将 User.Identity.IsAuthenticated 设置为 false
Jwt Bearer Authentication middleware always sets User.Identity.IsAuthenticated to false
我已将 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 class:
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 }
};
}
}
现在让我们看看token是如何生成的:
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
header 并通过 Postman
将其发送到服务器时
HttpContext.Current.User.Identity.IsAuthenticated is always false
授权 header 格式正确 Bearer
我的问题源于两点:
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"));
point2:
在 GenerateTokebn
class 里面,我是这样读密钥的:
byte[] key = Convert.FromBase64String(secretKey);
更改为与 MyJwtAuthenticationOptions
相同的这一行 class:
byte[] key = Encoding.UTF8.GetBytes(secretKey);
我已将 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 class:
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 }
};
}
}
现在让我们看看token是如何生成的:
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
header 并通过 Postman
HttpContext.Current.User.Identity.IsAuthenticated is always false
授权 header 格式正确 Bearer
我的问题源于两点:
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"));
point2:
在 GenerateTokebn
class 里面,我是这样读密钥的:
byte[] key = Convert.FromBase64String(secretKey);
更改为与 MyJwtAuthenticationOptions
相同的这一行 class:
byte[] key = Encoding.UTF8.GetBytes(secretKey);