我正在尝试使用IdentityServer4和JWT进行身份验证。我从我的客户端获取一个令牌,并试图向我的一个控制器发送一个简单的请求。
我有这样的要求
获取api /用户
授权:持票人{{my-token}}
在我的启动课程中,我注册了
var authorizationPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
services.AddMvc(config => {
config.Filters.Add(new AuthorizeFilter(authorizationPolicy)});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(o =>
{
o.Authority = "https://localhost:44333";
o.RequireHttpsMetadata = false;
o.ApiName = "MyApi";
o.JwtBearerEvents = new JwtBearerEvents
{
OnAuthenticationFailed = async context => {
Console.WriteLine("Debugger");
},
OnMessageReceived = async context => {
Console.WriteLine("Debugger");
},
OnTokenValidated = async tokenValidationContext =>
{
Console.WriteLine("Debugger");
}
});
我在每个Console.WriteLine("Debugger")
陈述中都给出了破发点,但没有一个破发点被击中。我仍然未经授权返回。
标题是否适合我的授权?我想在失败时查看请求,但即使启用了所有例外,我也无法达到突破点,是否有人有任何建议?
编辑我的客户端配置:
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("MyApi", "My Api"),
new ApiResource
{
Name = "customAPI",
DisplayName = "Custom API",
Description = "Custom API Access",
UserClaims = new List<string> {"role"},
ApiSecrets = new List<Secret> {new Secret("secretPassword".Sha256())},
Scopes = new List<Scope>
{
new Scope("customAPI.read"),
new Scope("customAPI.write")
}
}
};
}
控制器控制器基础:
[Route("api/[controller]")]
public class AsyncCRUDSingleKeyServiceController<TDTO, TKey> : Controller
where TKey : struct
{
protected IAsyncCRUDService<TDTO> _service;
public AsyncCRUDSingleKeyServiceController(IAsyncCRUDService<TDTO> service)
{
this._service = service;
}
[HttpGet("{id}")]
public virtual async Task<TDTO> Get(TKey id)
{
return await this._service.Get(new object[] { id });
}
//...
}
在Startup.Configure中,您是否包含以下行(在app.UseMvc之前)?
app.UseAuthentication();