基本用法请参考官方文档:https://identityserver4.readthedocs.io/en/latest/index.html
这里不对具体用法进行说明,一般情况下,Startup添加验证,就可以了,代码如下
services.AddAuthorization(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "这里写验证服务器链接"; options.RequireHttpsMetadata = false; options.ApiName = "test"; });
这里默认的验证token是取的header里面的Authorization参数
以下讨论的目的是:需要既可以从query里面获取token,也可以从header里面获取token
1. IdentityServerAuthentication
修改TokenRetriever来达到我们的要求
services.AddAuthorization(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = Configuration["CQMSERVICE_AUTHENDPOINT"]; options.RequireHttpsMetadata = false; options.ApiName = "vte-api"; options.TokenRetriever = request => { var authorization = TokenRetrieval.FromAuthorizationHeader()(request); if (string.IsNullOrEmpty(authorization)) { authorization = TokenRetrieval.FromQueryString("token")(request); if (!string.IsNullOrEmpty(authorization)) { authorization = authorization.Replace("Bearer ", ""); } } return authorization; }; });
TokenRetriever 的默认值是TokenRetrieval.FromAuthorizationHeader(),当然如果你只需要通过query参数验证的话,可以直接赋值为TokenRetrieval.FromQueryString("token")
/// <summary> /// Callback to retrieve token from incoming request /// </summary> public Func<HttpRequest, string> TokenRetriever { get; set; } = TokenRetrieval.FromAuthorizationHeader();
2.JwtBearer
如果是JWT验证的话,就没TokenRetrieval这个属性设置了,但是可以通过设置OnMessageReceived事件来达到目的
官方源代码如下
jwtOptions.Events = new JwtBearerEvents { OnMessageReceived = e => { e.Token = InternalTokenRetriever(e.Request); return JwtBearerEvents.MessageReceived(e); }, OnTokenValidated = e => JwtBearerEvents.TokenValidated(e), OnAuthenticationFailed = e => JwtBearerEvents.AuthenticationFailed(e), OnChallenge = e => JwtBearerEvents.Challenge(e) };
所以可以这么定义一下事件
services.AddAuthorization(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SECURITYKEY IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ABCDEFG"))//SECURITYKEY }; options.Events = new JwtBearerEvents { OnMessageReceived = context => { context.Token = context.Request.Query["token"]; return Task.CompletedTask; } }; });
以上我个人测试是没什么问题的,如果有其他问题,欢迎留言。