首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用身份验证创建不同的访问级别

问使用身份验证创建不同的访问级别
EN

Stack Overflow用户
提问于 2015-09-10 10:34:23
回答 1查看 217关注 0票数 0

我创建了一个具有安全访问级别的枚举,例如:

代码语言:javascript
复制
public enum AccessLevel
{
    Total,
    DeletionPrivileges,
    MaintainUsers,
    MaintainInventory,
    QueriesOnly,
    None
}

我可以管理的网站,所以某些功能如删除,不呈现给没有删除特权的人。但我也想在代码中使用某种授权。

在默认框架中,有防止使用[Authorize]访问项目某些区域的工具,我如何创建不同级别的权限来标记每个方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-10 12:29:43

您可以使用基于身份的基于请求的身份验证功能来实现此目的。首先,您需要在登录操作方法中为每个用户添加适当的声明,这样做可以更改您的日志操作方法,如下所示:

代码语言:javascript
复制
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var userManager=HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = userManager.Find(model.UserName, model.Password);
        if (user != null)
        {
            var ident = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            // imaging you have a custom class which return user access levels 
            var userAccessLevels=_accessLevelManager.GetAccessLevels(user.Id);
            // now we are going to add our custom claims 
            ident.AddClaims(new[]
            {
                // add each access level as a separate claim 
                new Claim("AccessLevel",userAccessLevels[0].ToString()),
                new Claim("AccessLevel",userAccessLevels[1].ToString()),
                // and so on
            });
            HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);
            // authentication succeed do what you want 
            return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
        }
    }
    ModelState.AddModelError("", "Invalid username or password");
    return View(login);
}

现在,我们已经成功地将我们的主张注入身份。但是您需要一个定制的授权属性来检查您的声明,如下所示:

代码语言:javascript
复制
public class ClaimsAccessAttribute : AuthorizeAttribute 
{
    public string ClaimType { get; set; }
    public string Value { get; set; }

    protected override bool AuthorizeCore(HttpContextBase context) 
    {
         return context.User.Identity.IsAuthenticated
             && context.User.Identity is ClaimsIdentity
             && ((ClaimsIdentity)context.User.Identity).HasClaim(x =>
                 x.Type == ClaimType && x.Value == Value);
    }
}  

现在,您可以在操作方法中轻松地使用属性:

代码语言:javascript
复制
[ClaimsAccess(CliamType="AccessLevel",Value="DeletionPrivileges")]
public ActionResult MyAction()
{
    // also you have access the authenticated user's claims 
    // simply by casting User.Identity to ClaimsIdentity
    // ((ClaimsIdentity)User.Identity).Claims
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32499496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档