繁体   English   中英

ASP Net Core授权

[英]Asp Net Core Authorization

问题:每当普通用户尝试访问只能由管理员访问的页面时,总是将用户重定向到登录名,而不是拒绝访问的页面。

问题:每当普通用户访问受限页面时,如何才能看到该页面?

控制器:

[Authorize(Roles = "Administrator")]
public class AdminOnlyController: Controller{

}

Startup.cs

app.UseIdentity();

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
            AuthenticationScheme = "FirstCookieAuthentication",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AccessDeniedPath = new PathString("/Forbidden/"),
            LoginPath = new PathString("/Conotroller/Login"),
});

拒绝访问只是一个状态代码,如未找到,内部错误等。要管理状态代码,您可以使用中间件“ app.UseStatusCodePages”。

码:

if (env.IsDevelopment())
{
//       see something more here
}
else
{
        app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");
}

然后在StatusCodeController中,构建与您提供的路线匹配的操作结果,例如:

    [HttpGet("/StatusCode/{statusCode}")]
    public IActionResult Index(int statusCode)
    {
        string statusmessage = "";
        switch (statusCode)
        {
            case 400:
                statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax";
                break;
            case 403:
                statusmessage = "Forbidden";
                break;
//all codes here...
            default:
                statusmessage = "That’s odd... Something we didn't expect happened";
                break;
        }

        // return appropriate view 
        // or same view with different message, eg from ViewBag
    }

我所做的是创建一个自定义属性,该属性实现IActionFilter接口并继承Attribute类。 所以基本上我将代码放在On Action Executing Method中。 但是我也看到了这个线程关于不创建自定义属性。 但是我没有在评论部分中阅读整个讨论。 无论如何,这适用于我的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM