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

Sha*_*tin 3 membership asp.net authentication roles asp.net-web-api

我们正在使用ASP.NET Web应用程序和个人用户帐户来学习这个优秀的教程.

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

Request URL:http://localhost:3067/token
grant_type=password&username=alice&password=password123
Run Code Online (Sandbox Code Playgroud)

正如所料,令牌提供程序返回:

{
   "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"
}
Run Code Online (Sandbox Code Playgroud)

这很好.现在,我们如何向JSON响应添加角色属性?

   "userRole":"admin"
Run Code Online (Sandbox Code Playgroud)

ptf*_*ner 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);
}
Run Code Online (Sandbox Code Playgroud)

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