在我们的网站(ASP.Net MVP 4.7)中,我们希望管理员能够添加Api用户并为此用户生成令牌,而不必以Api用户身份登录。
由于将永远不会使用Api用户的密码,因此可以在刷新令牌时更改密码,但是我无法弄清楚如何以管理员身份登录时如何为Api用户生成令牌。用户(下面的代码不起作用,但我想为澄清起见将其添加):
[HttpPost]
public async Task<JsonResult> getApiUserToken()
{
var userName = "ApiUser";
var password = Guid.NewGuid().ToString() + "A";
var apiUser = await _context.AspNetUsers.FirstOrDefaultAsync(u => u.UserName == userName);
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var code = await userManager.GeneratePasswordResetTokenAsync(apiUser.Id);
var result = await UserManager.ResetPasswordAsync(apiUser.Id, code, password);
var uri = $"{this.HttpContext.Request.Url.Scheme}://{this.HttpContext.Request.Url.Authority}/Token";
var httpClient = new HttpClient();
var loginData = new
{
grant_type = "password",
username = apiUser.Email,
password = password,
ttl = "MAX",
};
var response = await httpClient.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(loginData), Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
{
throw new ApplicationException(response.ReasonPhrase);
}
var responJsonText = await response.Content.ReadAsStringAsync();
return Json(JsonConvert.DeserializeObject(responJsonText), JsonRequestBehavior.AllowGet);
}