简体   繁体   English

ASP.NET 5用于Windows身份验证的自定义角色

[英]ASP.NET 5 Custom roles for Windows Authentication

I'm building an intranet type site with ASP.NET 5 that uses Windows Authentication. 我正在使用ASP.NET 5构建一个使用Windows身份验证的Intranet类型站点。 I have the authentication working, but I don't want everyone on the domain to have access to the intranet site. 我有身份验证工作,但我不希望域中的每个人都可以访问Intranet站点。 I can't use domain roles so I've set up my own custom roles in my SQL Server. 我无法使用域角色,因此我在SQL Server中设置了自己的自定义角色。 I have a table that maps the domain username to roles. 我有一个表将域用户名映射到角色。 I want to restrict access to the intranet site to only users that have a role defined in my SQL Server role table. 我想将对Intranet站点的访问权限仅限于在我的SQL Server角色表中定义了角色的用户。 How would I set up custom roles for Windows Authentication in ASP.NET 5? 如何在ASP.NET 5中为Windows身份验证设置自定义角色? Thanks! 谢谢!

You don't set up custom roles. 您没有设置自定义角色。 You need to create a custom authorization attribute, as described here . 您需要创建一个自定义的授权属性,如所描述这里

UPDATE: 更新:

Yes, you can use your custom authorize attribute globally. 是的,您可以全局使用自定义授权属性。 Let's say here's your custom authorize attribute: 让我们说这是您的自定义授权属性:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var username = httpContext.User.Identity.Name;

        // Check to see if user has a role in the database
        var isAuthorized = db.User.Find(username).Any();

        return isAuthorized;
    }
}

Then, you can either use it at the Action level or Controller level like this: 然后,您可以在Action级别或Controller级别使用它,如下所示:

[MyAuthorize]
public ActionResult Index()
{
}

Or, you can register it as a global filter in your FilterConfig class under the App_Start folder, like this: 或者,您可以在App_Start文件夹下的FilterConfig类中将其注册为全局过滤器,如下所示:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new MyAuthorizeAttribute());
    }
}

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

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