我想测试非常简单的身份验证层
public class CustomAuth : AuthorizeAttribute, IAuthorizationFilter
{
public CustomAuth()
{
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var cookies = context.HttpContext.Request.Cookies;
var ok = cookies["Auth0"] == "asdf";
if (!ok)
{
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
return;
}
}
}
[CustomAuth]
public IActionResult Index()
{
return View();
}
当没有名为Auth0
且值为asdf
的cookie时,一切正常,但是当我添加它时,No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
我尝试将context.Result = ...;
设置为new OkResult()
或RedirectToActionResult
并起作用,但是我只想让他直接进入Index
,而不是从中移走所有内容该OnAuthorization
方法的操作
我该如何实现?
答案 0 :(得分:0)
对于CustomAuth
,它是从AuthorizeAttribute
继承的。身份验证中间件将通过默认身份验证方案检查身份。
如果您更喜欢在不配置任何身份验证的情况下转到Index
,则可以尝试将
AuthorizeAttribute
更改为Attribute
public class CustomAuth : Attribute, IAuthorizationFilter
{
public CustomAuth()
{
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var cookies = context.HttpContext.Request.Cookies;
var ok = cookies["Auth0"] == "asdf";
if (!ok)
{
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
return;
}
}
}