Joh*_*rre 5 c# .net-core asp.net-core-2.0
在我的 ASP.Net Core 2 项目中,我有一个AuthenticationHandler想要插入的自定义中间件。
public class BasicAuthenticationMiddleware : AuthenticationHandler<AuthenticationSchemeOptions>
{
public BasicAuthenticationMiddleware(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var principal = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), "BasicAuth");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
Run Code Online (Sandbox Code Playgroud)
在我的启动中,我有以下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "BasicAuth";
options.DefaultChallengeScheme = "BasicAuth";
options.AddScheme("BasicAuth", x => {
x.DisplayName = "BasicAuthenticationMiddleware";
x.HandlerType = typeof(BasicAuthenticationMiddleware);
});
});
}
Run Code Online (Sandbox Code Playgroud)
最后我的视图控制器:
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values/Works
[HttpGet]
[Route("Works")]
[Authorize(ActiveAuthenticationSchemes = "BasicAuth")]
public string Works()
{
return "works";
}
// GET api/values/DoesNotWork
[HttpGet]
[Route("DoesNotWork")]
[Authorize]
public string DoesNotWork()
{
return "does not work";
}
}
Run Code Online (Sandbox Code Playgroud)
HandleAuthenticateAsync当我指定ActiveAuthenticationSchemes我的方案名称时,我的身份验证器将被调用,否则不会。我有一个演示应用程序显示这里的行为:https : //github.com/JohnPAguirre/AuthenticationSchemaProblem
我希望我的BasicAuthenticationMiddleware每个人都使用我的演示逻辑登录。如何将ActiveAuthenticationSchemes所有请求的默认设置设为“BasicAuth”?
任何人都对我可能缺少的东西有任何想法?
我确实设法设置了默认身份验证方案 通过将我想要的方案设置为 DefaultPolicy 的唯一身份验证方案进行授权。在您的配置中使用以下内容。我在两者之间使用过它AddMvc,AddAuthentication并且效果很好。
services.AddAuthorization(config => {
var def = config.DefaultPolicy;
config.DefaultPolicy = new AuthorizationPolicy(def.Requirements,
new List<string>(){ "BasicAuth" });
});
Run Code Online (Sandbox Code Playgroud)
我不认为你可以设置默认值,但你还有其他一些选择。
创建您自己的自定义授权属性:
public class BasicAuthAuthorizeAttribute : AuthorizeAttribute
{
public BasicAuthAuthorizeAttribute()
{
ActiveAuthenticationSchemes = "BasicAuth";
}
}
Run Code Online (Sandbox Code Playgroud)
并像以前一样在您的操作中使用它:
[BasicAuthAuthorize]
public string SomeAction()
{
//snip
}
Run Code Online (Sandbox Code Playgroud)将该Authorize属性添加到您的所有操作中,并仅在需要时覆盖它。为此,在您的 `` 方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new AuthorizeAttribute
{
ActiveAuthenticationSchemes = "BasicAuth"
});
});
//snip
}
Run Code Online (Sandbox Code Playgroud)
并覆盖它:
[AllowAnonymous]
public string UnsecureAction()
{
//snip
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |