我在一个解决方案中有两个单独的项目,其中一个是WEB API,另一个是MVC。 MVC充当表示层,所有操作均由WEB API执行。我已经成功实现了承载令牌的生成,并且可以通过Postman对其进行测试。当我尝试通过MVC执行相同的操作时遇到错误。
通过MVC登录后,我便能够成功从WEB API接收承载令牌。但是代码执行在MVC的ActionResult“索引”中的consumeData.Wait();
点处中断,错误为'401未经授权。'
我是一个初学者,任何解决此问题的帮助都将大有帮助。
#我试图访问WEB API的MVC中的代码#
public ActionResult Index()
{
IEnumerable<ViewUsers> vu = null;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Session["token"].ToString());
var consumeData = GlobalVariables.WebAPIClient.GetAsync("GetUsers");
consumeData.Wait();
var dataread = consumeData.Result;
dataread.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (dataread.IsSuccessStatusCode)
{
var results = dataread.Content.ReadAsAsync<IList<ViewUsers>>();
results.Wait();
vu = results.Result;
}
}
return View(vu);
}
#GrantResourceOwnerCredentials的代码#
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
ApplicationDbContext dbContext = new ApplicationDbContext();
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser _user = await _repo.FindUser(context.UserName, context.Password);
if (_user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbContext));
var user = await userManager.FindAsync(context.UserName, context.Password);
var oAuthIdentity = await user.GenerateUserIdentityAsync
(userManager, OAuthDefaults.AuthenticationType);
oAuthIdentity.AddClaim(new Claim("token", context.UserName));
var cookiesIdentity = await user.GenerateUserIdentityAsync
(userManager, CookieAuthenticationDefaults.AuthenticationType);
Dictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("UserName", user.UserName);
properties.Add("Role", "user");
AuthenticationProperties _properties = new AuthenticationProperties(properties);
var ticket = new AuthenticationTicket(oAuthIdentity, _properties);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
context.Response.Cookies.Append("Token", context.Options.AccessTokenFormat.Protect(ticket));
context.Validated(ticket);
}
#用于获取在MVC#的登录方法内部访问的承载令牌的代码
public async Task<string> AuthorizeAsync(string usr, string psw)
{
WebRequest request = WebRequest.Create("https://localhost:44300/Token");
request.Method = "POST";
request.ContentType = "application/json";
string postjson = String.Format("grant_type={0}&UserName={1}&Password={2}", "password", usr, psw);
byte[] bytes = Encoding.UTF8.GetBytes(postjson);
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(bytes, 0, bytes.Length);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
return tokenResponse.access_token + ":" + tokenResponse.expires_in;
}
catch (Exception ex)
{
return "failure";
}
}