【发布时间】:2019-07-31 23:14:15
【问题描述】:
我正在尝试为我的服务器设置自己的自定义身份验证。但它会为每个端点调用,即使它在方法上有 [AllowAnonymous] 属性。使用我当前的代码,我可以每次都在 HandleAuthenticateAsync 方法中命中断点,即使在允许匿名函数上也是如此。
AddCustomAuthentication 正确添加了 authenticationhandler
public void ConfigureServices(IServiceCollection services)
{
//services.AddAuthorization();
services.AddAuthentication(options =>
{
// the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
options.DefaultAuthenticateScheme = "scheme";
options.DefaultChallengeScheme = "scheme";
})
.AddCustomAuthentication(o => { });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
...
public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>
{
public RvxAuthenticationHandler(
IOptionsMonitor<RvxAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var token = Request.Headers["token"].ToString();
if (string.IsNullOrWhiteSpace(token))
{
return AuthenticateResult.Fail("Invalid Credentials");
}
return AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "Hi"));
}
【问题讨论】:
标签: c# asp.net-mvc