问题描述
我在一个解决方案中有两个单独的项目,其中一个是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);
}
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,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";
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)