我目前正在关注本教程https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/ 实现Jwt刷新令牌。当前,当我在响应API请求时遇到特定的异常时,我正在尝试添加一个名为Token-Expired的标头:“ true”。
在本教程中,本节说明如何在Startup.cs中进行操作
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "bearer";
options.DefaultChallengeScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("the server key used to sign the JWT token is here, use more than 16 chars")),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero //the default for this setting is 5 minutes
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
}
问题是我正在使用ASP.NET Web Api 2而不是.net core 2.1。如何将此代码添加到我的代码中?我认为可能可行的一种方法是,可以将其添加到TokenValidation类中,但是我不知道该怎么做:
public class TokenValidationHandler : DelegatingHandler
{
private static bool RetrieveToken(HttpRequestMessage request, out string token)
{
token = null;
IEnumerable<string> authHeaders;
if (!request.Headers.TryGetValues("Authorization", out authHeaders) || authHeaders.Count() > 1)
{
return false;
}
var bearerToken = authHeaders.ElementAt(0);
token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
return true;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpStatusCode statusCode;
string token;
//determine whether a jwt exists or not
if (!RetrieveToken(request, out token))
{
statusCode = HttpStatusCode.Unauthorized;
//allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
return base.SendAsync(request, cancellationToken);
}
try
{
const string sec = HostConfig.SecurityKey;
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
SecurityToken securityToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters()
{
ValidAudience = HostConfig.Audience,
ValidIssuer = HostConfig.Issuer,
//Set false to ignore expiration date
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
LifetimeValidator = this.LifetimeValidator,
IssuerSigningKey = securityKey
};
//extract and assign the user of the jwt
Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);
return base.SendAsync(request, cancellationToken);
}
catch (SecurityTokenValidationException e)
{
statusCode = HttpStatusCode.Unauthorized;
}
catch (Exception ex)
{
statusCode = HttpStatusCode.InternalServerError;
}
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });
}
public bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
{
if (expires != null)
{
if (DateTime.UtcNow < expires) return true;
}
return false;
}
}
答案 0 :(得分:0)
首先还需要安装Microsoft.Owin.Host.SystemWeb软件包。然后创建一个名称为Startup.cs的类。
这将为您提供帮助。
public class Startup
{
public void Configuration(IAppBuilder app)
{
//
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "bearer";
options.DefaultChallengeScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("the server key used to sign the JWT token is here, use more than 16 chars")),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero //the default for this setting is 5 minutes
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
}
}
此外,如果您的启动类不在默认名称空间中,则将Web配置行添加到<appSettings>
区域,例如:<add key="owin:AppStartup" value="[NameSpace].Startup" />
要使用ConfigureServices
方法,您需要具有内置依赖项注入功能,仅在ASP.NET Core中可用。您将需要使用第三方IoC容器,例如-
Autofac for Web API
或
注入
为此,请访问以下库。
Microsoft.Extensions.DependencyInjection
答案 1 :(得分:0)
请再添加一个SecurityTokenExpiredException catch块以捕获令牌到期错误,并在catch块内添加响应标头,如下所示。
public class TokenValidationHandler : DelegatingHandler
{
private static bool RetrieveToken(HttpRequestMessage request, out string token)
{
token = null;
IEnumerable<string> authHeaders;
if (!request.Headers.TryGetValues("Authorization", out authHeaders) || authHeaders.Count() > 1)
{
return false;
}
var bearerToken = authHeaders.ElementAt(0);
token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
return true;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage();
string token;
//determine whether a jwt exists or not
if (!RetrieveToken(request, out token))
{
response.StatusCode = HttpStatusCode.Unauthorized;
//allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
return base.SendAsync(request, cancellationToken);
}
try
{
const string sec = HostConfig.SecurityKey;
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
SecurityToken securityToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters()
{
ValidAudience = HostConfig.Audience,
ValidIssuer = HostConfig.Issuer,
//Set false to ignore expiration date
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
LifetimeValidator = this.LifetimeValidator,
IssuerSigningKey = securityKey
};
//extract and assign the user of the jwt
Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);
return base.SendAsync(request, cancellationToken);
}
catch (SecurityTokenExpiredException e)
{
var expireResponse = base.SendAsync(request, cancellationToken).Result;
response.Headers.Add("Token-Expired", "true");
response.StatusCode = HttpStatusCode.Unauthorized;
}
catch (SecurityTokenValidationException e)
{
response.StatusCode = HttpStatusCode.Unauthorized;
}
catch (Exception ex)
{
response.StatusCode = HttpStatusCode.InternalServerError;
}
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
}
public bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
{
if (expires != null)
{
if (DateTime.UtcNow < expires) return true;
}
return false;
}
}