22

Web API 2 プロジェクトを開発しています。認証にはベアラートークンを使用しています。認証が成功すると、API は JSON オブジェクトを返します。

{"access_token":"Vn2kwVz...",
   "token_type":"bearer",
   "expires_in":1209599,
   "userName":"username",
   ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
   ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"}

ここで、この JSON オブジェクトでユーザー ロールも返したいと思います。JSON 応答からユーザー ロールを取得するには、どのような変更を行う必要がありますか?

4

2 に答える 2

53

たくさん検索した後、いくつかのカスタム プロパティを作成し、認証チケットで設定できることがわかりました。このようにして、応答をカスタマイズして、呼び出し側で必要になる可能性のあるカスタム値を含めることができます。

ユーザー ロールをトークンと共に送信するコードを次に示します。これが私の要件でした。コードを変更して、必要なデータを送信できます。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (UserManager<ApplicationUser> userManager = _userManagerFactory())
        {
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                context.Options.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                CookieAuthenticationDefaults.AuthenticationType);
            List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x=>x.Value)));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    }


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

これにより、出力が次のように返されます

`{"access_token":"Vn2kwVz...",
 "token_type":"bearer",
 "expires_in":1209599,
 "userName":"username",
 ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
 ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"
 "roles"=["Role1","Role2"] }`

この情報が誰かに役立つことを願っています。:)

于 2014-06-10T12:16:29.423 に答える