我正在使用Identity Server4,我使用ResourceOwnerPassword
授权类型配置了一个Web API项目。
Web API方法:
[HttpGet]
[Authorize(Roles = "Badmin")]
[Route("GetUsers")]
public IActionResult GetUsers()
{
List<ApplicationUser> users = _context.ApplicationUsers
.AsNoTracking().ToListAsync().Result;
return Json(users);
}
在我的控制台程序代码中:
if (response != null)
{
using (HttpClient client = new HttpClient())
{
Console.WriteLine("AccessToken:" + Environment.NewLine + response.AccessToken);
Console.WriteLine(Environment.NewLine);
HttpResponseMessage resourceOwnerPasswordResponse = await client.GetAsync("https://localhost:44366/identity/GetUsers");
client.DefaultRequestHeaders.Add("Bearer", response.AccessToken);
if (!resourceOwnerPasswordResponse.IsSuccessStatusCode)
{
Console.WriteLine(resourceOwnerPasswordResponse.StatusCode);
Console.WriteLine("HttpClient ResourceOwnerPassword Result: " + resourceOwnerPasswordResponse.StatusCode);
Console.WriteLine(Environment.NewLine);
}
else
{
string result = await resourceOwnerPasswordResponse.Content.ReadAsStringAsync();
Console.WriteLine("HttpClient ResourceOwnerPassword Result: " + Environment.NewLine + JsonConvert.DeserializeObject(result));
Console.WriteLine(Environment.NewLine);
}
}
}
第二种方式:
if (response != null)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://localhost:44366/identity/GetUsers");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", string.Format("Bearer {0}", response.AccessToken));
httpWebRequest.Method = "GET";
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string result = string.Empty;
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
if (responseStream != null)
{
StreamReader streamReader = new StreamReader(responseStream);
result = streamReader.ReadToEnd();
streamReader.Close();
}
}
Console.WriteLine("HttpWebRequest ResourceOwnerPassword Result: " + Environment.NewLine + JsonConvert.DeserializeObject(result));
}
所以我的问题是为什么当我使用HttpCliet
时,我得到了未经授权(代码401),
而第二种方式成功地获得了用户数据。
答案 0 :(得分:3)
在发出请求之前,应将令牌添加到客户端,并且您需要确保它是授权标头。
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", response.AccessToken);
//OR
//client.DefaultRequestHeaders
// .Add("Authorization", string.Format("Bearer {0}", response.AccessToken));
var resourceOwnerPasswordResponse = await client.GetAsync("https://localhost:44366/identity/GetUsers");
这就是为什么它在第二个例子中工作而不是第一个
如果使用ToListAsync
[HttpGet]
[Authorize(Roles = "Badmin")]
[Route("GetUsers")]
public async Task<IActionResult> GetUsers() {
var users = await _context.ApplicationUsers.AsNoTracking().ToListAsync();
return Json(users);
}