CustomAuth属性尽可能简单

时间:2019-05-04 15:53:27

标签: c# asp.net-core asp.net-core-mvc

我想测试非常简单的身份验证层

 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方法的操作

我该如何实现?

1 个答案:

答案 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;
        }
    }
}