首页 > 解决方案 > 如何在基于令牌的身份验证中从 ASP.NET Web API 发送角色并在 ASP.NET MVC 中设置它

问题描述

当用户进行身份验证时,如何使用 asp.net 身份向响应添加角色?

我正在开发一个需要对用户进行身份验证的项目。我在 ASP.NET 中构建了一个 API,并且正在使用 ASP.NET 身份框架进行身份验证。

现在我需要知道哪个用户登录了,所以我已经为用户分配了角色。我不知道如何将用户的角色与不记名令牌一起发送。我一直在寻找解决方案,但没有找到。

任何帮助将不胜感激。

这是与 API 通信的代码。

public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var getTokenUrl = Wedding_Hall.AppSettings.TOKEN_URI;

    using (HttpClient httpClient = new HttpClient())
    {
        HttpContent content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("username", model.Email),
                    new KeyValuePair<string, string>("password", model.Password)
                });

        HttpResponseMessage result = httpClient.PostAsync(getTokenUrl, content).Result;

        string resultContent = result.Content.ReadAsStringAsync().Result;

        if (result.IsSuccessStatusCode)
        {
            var token = JsonConvert.DeserializeObject<Token>(resultContent);

            AuthenticationProperties options = new AuthenticationProperties();

            options.AllowRefresh = true;
            options.IsPersistent = true;
            options.ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));

            var claims = new[]
                    {
                         new Claim(ClaimTypes.Name, model.Email),

                         new Claim("AcessToken", string.Format("Bearer {0}", token.access_token)),
                    };

            var identity = new ClaimsIdentity(claims, "ApplicationCookie");

            Request.GetOwinContext().Authentication.SignIn(options, identity);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Invalid Login Attempt");
            return View("Login", model);
        }
    }
}

标签: c#asp.netasp.net-mvcasp.net-web-apiasp.net-identity

解决方案


推荐阅读