c# - 如何在基于令牌的身份验证中从 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);
}
}
}
解决方案
推荐阅读
- ios - 如何快速隐藏谷歌地图标记
- javascript - express中路由器划分有什么问题?(反应)
- python-3.x - 收到错误 InvalidArgumentError: indices[10,0] = 92379 is not in [0, 92379) 因为词汇大小不匹配
- angular - 角度通用仅以 /index.html 开头
- django - 在 Django 中设置初始字段
- javascript - 我的护照本地策略出现错误,提示未定义密码
- java - 图形数据的查询修改
- oracle - 从 2 个表中选择数据并匹配 2 个字段(oracle sql developer)
- angular - 已安装 Angular 版本 ~7.1.0 想要安装版本 4
- arrays - Postgres - 如何使用自定义数据类型数组创建自定义数据类型