Authenticating a .NET MVC application with a Web A

2019-04-09 14:02发布

问题:

I have a Web Api 2 project based on SPA VS 2013 Template. I have a bearer token authentication configured in that Api.

I also have a separate MVC 5 project, I want to authenticate using that Web Api. Is that possible? How?

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?

回答1:

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[...]

Edit:

With HttpClient you would do something like this:

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


回答2:

I suspect with the SPA you're using resource owner flow (uid/pwd). If you now have a new client that is a separate MVC project, it'd be considered a code flow client, so this means you need to support code flow in your OAuth2 authorization server. Unfortunately the Katana OAuth2 authorization server middleware from Microsoft wasn't really designed to support more elaborate OAuth2 scenarios, so you might have to look into using a separate, dedicated OAuth2 authorization server. Thinktecture AuthorizationServer is a free, open source implementation in .NET that you could potentially use:

http://thinktecture.github.io/Thinktecture.AuthorizationServer/

Otherwise you're almost implementing an OAuth2 authorization server from scratch.



回答3:

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

ASP.NET Identity can be used with all of the ASP.NET frameworks, such as ASP.NET MVC, Web Forms, Web Pages, Web API, and SignalR.

for more information about it check out this link

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

hope that helps.