ASP.NET Security Roles AND Permissions

前端 未结 5 1331
[愿得一人]
[愿得一人] 2021-01-03 00:35

I\'m comfortable with the ASP.NET security model whereby one can allow/deny access to users in the web.config based on what roles they are in e.g.



        
5条回答
  •  醉酒成梦
    2021-01-03 01:04

    i found this article that gives a nice example

    [Flags]
    public enum Permissions
    {
    View                 = (1 << 0),
    Add                  = (1 << 1),
    Edit                 = (1 << 2),
    Delete               = (1 << 3),
    Admin                = (View | Add | Edit | Delete)
    }
    
    public ActionResult Authenticate(string username, string password)
    {
    var user = authenticationService.Authenticate(username, password);
    Session["User"] = user;
    
    return RedirectToAction("Somewhere", "Else");  
    }
    
    public class PermissionsAttribute : ActionFilterAttribute
    {
    private readonly Permissions required;
    
    public PermissionsAttribute(Permissions required)
    {
        this.required = required;
    }
    
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var user = filterContext.HttpContext.Session.GetUser();
        if (user == null)
        {
            //send them off to the login page
            var url = new UrlHelper(filterContext.RequestContext);
            var loginUrl = url.Content("~/Home/Login");
            filterContext.HttpContext.Response.Redirect(loginUrl, true);   
        }
        else
        {
            if (!user.HasPermissions(required))
            {
                throw new AuthenticationException("You do not have the necessary permission to perform this action");
            }
        }
    }
    }
    
    [Permissions(Permissions.View)]
    public ActionResult Index()
    {
    
    // ...
    
    }
    

提交回复
热议问题