Authenticating a .NET MVC Application Using Web Api

I have a Web Api 2 project based on the SPA VS 2013 template. I have bearer token authentication configured in this Api.

I also have a separate MVC 5 project, I want to authenticate with this web api. Is it possible? How?

What I have done 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)
      {
           //
      }
}

He received a token, but now what?

+4
source share
3 answers

If you receive a token, you must be installed. You just need to provide it in the header for each request, for example:

Authorization: Bearer boQtj0SCGz2GFGz[...]

Edit:

With HttpClient you will do something like this:

var requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/MyApi/");
requestMessage.Headers.Add("Authorization", "Bearer boQtj0SCGz2GFGz[...]");
+4
source

, SPA (uid/pwd). , MVC, , , OAuth2. , Katana OAuth2 Microsoft OAuth2, OAuth2. Thinktecture AuthorizationServer - .NET, :

http://thinktecture.imtqy.com/Thinktecture.AuthorizationServer/

OAuth2 .

+2

you can defiantly use and configure the ASP.NET Identity and OWIN component in the asp.net web api to provide authentication services.

The ASP.NET ID can be used with all ASP.NET infrastructures, such as ASP.NET MVC, web forms, web pages, web APIs, and SignalR.

for more information on this check this link

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

hope this helps.

0
source

Source: https://habr.com/ru/post/1532539/


All Articles