c# – 如何为ActiveAuthenticationSchemes设置默认值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 如何为ActiveAuthenticationSchemes设置默认值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2434字,纯文字阅读大概需要4分钟。
内容图文
![c# – 如何为ActiveAuthenticationSchemes设置默认值?](/upload/InfoBanner/zyjiaocheng/806/451c1a053cd24d9189816e764332f92c.jpg)
在我的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));
}
}
在我的创业公司中,我有以下内容:
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);
});
});
}
最后我的视图控制器:
[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";
}
}
当我将ActiveAuthenticationSchemes指定给我的方案名称时,将调用我的身份验证器HandleAuthenticateAsync,否则它将不会.我有一个演示应用程序显示此处的行为:https://github.com/JohnPAguirre/AuthenticationSchemaProblem
我希望我的BasicAuthenticationMiddleware使用我的演示逻辑记录每个人.如何为所有请求将ActiveAuthenticationSchemes默认为“BasicAuth”?
任何人对我可能缺少的东西都有任何想法?
解决方法:
我不认为你可以设置默认值,但你有其他选择.
>创建自己的自定义授权属性:
public class BasicAuthAuthorizeAttribute : AuthorizeAttribute
{
public BasicAuthAuthorizeAttribute()
{
ActiveAuthenticationSchemes = "BasicAuth";
}
}
并像以前一样在你的行动中使用它:
[BasicAuthAuthorize]
public string SomeAction()
{
//snip
}
>将Authorize属性添加到您的所有操作,并仅在需要时覆盖它.要做到这一点,在你的“方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new AuthorizeAttribute
{
ActiveAuthenticationSchemes = "BasicAuth"
});
});
//snip
}
并覆盖它:
[AllowAnonymous]
public string UnsecureAction()
{
//snip
}
内容总结
以上是互联网集市为您收集整理的c# – 如何为ActiveAuthenticationSchemes设置默认值?全部内容,希望文章能够帮你解决c# – 如何为ActiveAuthenticationSchemes设置默认值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。