简体   繁体   中英

WEB API Forms Authentication - Where can i set Roles for a User

I use this Login Action:

    // POST api/login
    public bool Post(LoginModel model)
    {
        if (model.Username == "user" && model.Password == "password")
        {
            var princ = new GenericPrincipal(new GenericIdentity(model.Username), null);

            FormsAuthentication.SetAuthCookie(model.Username,false);
            return true;
        }
        else
        {
            return false;
        }
    }

and i have set authentication to forms. Everything works fine so far, except i have no idea how i would set the roles for the currently authenticated user, so i can use this Attribute:

[Authorize (Roles = "Admin")]

From Visual Studio click the Project menu and select ASP.NET Configuration . This will launch the ASP.NET Web Site Administration Tool. From here you can add/edit Users and their security roles.

If you see an error message on the Security tab then you will probably need to do some additional configuration. Here is a handy walkthrough: http://msdn.microsoft.com/en-us/library/879kf95c(v=vs.100).aspx

If you have implemented RoleProvider you need not worry about setting role to the principal .

Other option is to pass in roles to directly to generic principal.

string[] roles = { "Admin", "role2", "role3" };
var principal = new GenericPrincipal(httpContext.User.Identity, roles);
System.Threading.Thread.CurrentPrincipal = principal;

Yes you can use

[Authorize(Roles="manager, admin")]

etc

Refer to http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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