使用Web Api验证.NET MVC应用程序 [英] Authenticating a .NET MVC application with a Web Api
本文介绍了使用Web Api验证.NET MVC应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基于SPA VS 2013模板的Web Api 2项目.我在该Api中配置了承载令牌身份验证.
I have a Web Api 2 project based on SPA VS 2013 Template. I have a bearer token authentication configured in that Api.
我还有一个单独的MVC 5项目,我想使用该Web Api进行身份验证.那可能吗?怎么样?
I also have a separate MVC 5 project, I want to authenticate using that Web Api. Is that possible? How?
到目前为止(在Mvc客户端中)我做了什么:
What I did so far (in my Mvc Client) :
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/MyApi/");
var response = client.PostAsync("Token", new StringContent("grant_type=password&username=teste&password=123456", Encoding.UTF8)).Result;
if (response.IsSuccessStatusCode)
{
//
}
}
它获得了令牌,但是现在呢?
It got the Token, but what now?
推荐答案
如果获得了令牌,则应该全部设置好.您只需要在每个请求的标头中提供它,例如:
If you get the token you should be all set. You just need to provide it in the header on each request like:
Authorization: Bearer boQtj0SCGz2GFGz[...]
使用HttpClient,您将执行以下操作:
With HttpClient you would do something like this:
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/MyApi/");
requestMessage.Headers.Add("Authorization", "Bearer boQtj0SCGz2GFGz[...]");
这篇关于使用Web Api验证.NET MVC应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文