首先生成访问令牌、刷新令牌等都应该在
真实授权服务器
有关详细信息
http://authguidance.com
但通过说,即使我在我的应用程序中也生成了JWT令牌。。。
我就是这样进来的。net core 2.0
正在启动中。反恐精英
配置服务
var securityKey = "asdasdasdasdasdasddsda123123132123123";// your own key
var key = Encoding.UTF8.GetBytes(securityKey);
var signingKey = new SymmetricSecurityKey(key);
var tokenValidationParameters = new TokenValidationParameters()
{
ValidAudiences = new string[]
{
tokenSetting.Audience
},
ValidIssuers = new string[]
{
tokenSetting.Issuer
},
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ClockSkew= TimeSpan.Zero
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.Response.Headers.Add("x-tokenstatus-header", "fail");// may be not necessary for you
return Task.CompletedTask;
}
};
options.Audience = tokenSetting.Audience;
options.RequireHttpsMetadata = tokenSetting.RequireHttpsMetadata;
options.TokenValidationParameters = tokenValidationParameters;
});
并且在
配置
app.UseTokenProvider(); // This is my own middleware
app.UseAuthentication();
app.UseMvc();
公共类TokenProviderMiddleware{..}
public Task Invoke(HttpContext context, IUserService userService)
{
if (!IsAuthenticationRequest(context.Request.Path, context.Request.Method)) {
return this._next(context);
}
var securityKey = "asdasdasdasdasdasddsda123123132123123";// your own key
var key = Encoding.UTF8.GetBytes(securityKey);
var signingKey = new SymmetricSecurityKey(key);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var claimsIdentity = new ClaimsIdentity(listClaims, "Custom");
var securityTokenDescriptor = new SecurityTokenDescriptor()
{
Audience = this._tokenSettings.Audience,
Issuer = this._tokenSettings.Issuer,
Subject = claimsIdentity,
SigningCredentials = signingCredentials,
Expires = DateTime.UtcNow.AddMinutes(20),
};
var tokenHandler = new JwtSecurityTokenHandler();
var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);
var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);
// signedAndEncodedToken => contains your token you can do send it as response or anything you want
}
private bool IsAuthenticationRequest(string path, string method) {
if (HttpMethods.IsPost(method) && path?.IndexOf("/api/login", StringComparison.OrdinalIgnoreCase) >= 0) {
return true;
}
return false;
}
如果您需要对代码进行澄清,请务必告诉我。。