ASP.NET Core中的自定义授权属性 [英] Custom authorization attributes in ASP.NET Core

查看:597
本文介绍了ASP.NET Core中的自定义授权属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net核心,但我不了解某些内容。例如,在mvc.net 5中,
可以使用AuthorizeAttribute中的create类过滤和授权操作,并将属性设置为以下操作:

i'm working on asp.net core and i don't understand some things. for example in mvc.net 5 we can filter and authorize action with create class from AuthorizeAttribute and set attribute to actions like this:

public class AdminAuthorize : AuthorizeAttribute {
        public override void OnAuthorization(AuthorizationContext filterContext) {
            base.OnAuthorization(filterContext);
            if (filterContext.Result is HttpUnauthorizedResult)
                filterContext.Result = new RedirectResult("/Admin/Account/Login");
        }
    }

但是在asp.net核心中我们没有AuthorizeAttribute ...
如何在asp.net核心中为自定义操作设置此类过滤器?

but in asp.net core we don't have AuthorizeAttribute ... how can i set filter like this in asp.net core for custom actions ?

推荐答案

您可以使用身份验证中间件和 Authorize 服装来重定向登录页面。对于您的情况,也使用 AuthenticationScheme 似乎是合理的。

You can use authentication middleware and Authorize attirbute to redirect login page. For your case also using AuthenticationScheme seems reasonable.

首次使用(我假设您要使用cookie中间件)cookie身份验证中间件:

First use(i assume you want use cookie middleware) cookie authentication middleware:

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "AdminCookieScheme",
            LoginPath = new PathString("/Admin/Account/Login/"),
            AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            CookieName="AdminCookies"
        });

,然后在此方案中使用 Authorize 属性:

and then use Authorizeattribute with this scheme:

[Authorize(ActiveAuthenticationSchemes = "AdminCookieScheme")]

另一个选项是使用 UseWhen 分隔管理员和默认身份验证:

Another option is using UseWhen to seperate admin and default authentication:

      app.UseWhen(x => x.Request.Path.Value.StartsWith("/Admin"), builder =>
      {
          builder.UseCookieAuthentication(new CookieAuthenticationOptions()
          {
              LoginPath = new PathString("/Admin/Account/Login/"),
              AccessDeniedPath = new PathString("/Admin/Account/Forbidden/"),
              AutomaticAuthenticate = true,
              AutomaticChallenge = true
          });
      });

然后只需使用 Authorize 属性。

这篇关于ASP.NET Core中的自定义授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆