aet1 aet1 - 3 months ago 14
ASP.NET (C#) Question

ASP.NET Web API - Can't login

How can I log in to my ASP.NET Web Api 2 app? I have tried to log in using webpage and register using POST request, but I cannot authenticate my console app client.

Answer

You have to first obtain an access_token. In order to do this, you should POST application/x-www-form-urlencoded form at {YourBaseAddress:Port}/Token, which contains grant_type=password&username=YourEmailHere&password=YourPassHere content. If provided data is valid, you will get response, that looks like this:

{

  "access_token": "ZlGVovVk6...1dts",    
  "token_type": "bearer",
  "expires_in": 1209599,    
  "userName": "admin@example.com",
  ".issued": "Thu, 29 Aug 2015 12:06:45 GMT",    
  ".expires": "Thu, 31 Aug 2015 12:06:45 GMT"    
}

Finally, if you want to authenticate your next requests in your console app, add an Authorization header which value is: Bearer YourAccessTokenHere.

Sample C# client with Authentication header:

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.BaseAddress = new Uri(@"http://localhost:5000/");
var res = client.GetAsync("/api/values").Result;
Comments