使用ASP.NET WebApi进行身份验证时返回用户的角色

时间:2014-02-03 19:13:13

标签: asp.net authentication asp.net-web-api roles membership

我们正在使用ASP.NET Web应用程序和个人用户帐户关注此excellent tutorial

要验证并获取承载令牌,我们发布以下内容:

Request URL:http://localhost:3067/token
grant_type=password&username=alice&password=password123

正如预期的那样,令牌提供程序返回:

{
   "access_token":"rkg5dP_Lyg ... TIHLD2xIRJ",
   "token_type":"bearer",
   "expires_in":1209599,
   "userName":"Alice",
   ".issued":"Mon, 03 Feb 2014 19:06:32 GMT",
   ".expires":"Mon, 17 Feb 2014 19:06:32 GMT"
}

这很好。现在,我们如何将角色属性添加到JSON响应中?

   "userRole":"admin"

1 个答案:

答案 0 :(得分:5)

如果您在Visual Studio中使用默认项目模板,那么您需要做的就是将userRole添加到您调用Authentication.SignIn时传递的AuthenticationProperties数组中。

因此,如果您仍在使用ApplicationOAuthProvider类,请将userRole添加到CreateProperties方法中的属性字典中,如下所示:

public static AuthenticationProperties CreateProperties(string userName, string userRole)
{
    IDictionary<string, string> data = new Dictionary<string, string>
    {
        { "userName", userName },
        { "userRole", userRole }
    };
    return new AuthenticationProperties(data);
}

然后,无论何时调用Authentication.SignIn,都会传递新的属性列表,userRole也应该显示出来。对于Token身份验证,您需要在ApplicationOAuthProvider类的GrantResourceOwnerCrentials方法中添加它,对于常规cookie authenticatin,需要在GetExternalLogin方法的AccountController中进行修改。