Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Identity 2 and Web API 2 authorization and call api using bearer token

The following scenario: I have an MVC 5 web app using Identity 2.0 and Web API 2.

Once the user authenticates in MVC 5 he should be able to call a WEB API endpoint let's call it: api/getmydetails using a bearer token.

What I need to know is how can I issue the token for that specific user in MVC 5?

like image 696
David Dury Avatar asked Jul 28 '14 06:07

David Dury


1 Answers

I did solve this.

Here are some screenshots and I will also post the demo solution.

Just a simple mvc 5 with web api support application.

The main thing you have to register and after login. For this demo purpose I registered as [email protected] with password Password123*.

If you are not logged in you will not get the token. But once you loggin you will see the token:

enter image description here

After you get the token start Fiddler.

Make a get request to the api/service endpoint. You will get 401 Unauthorized

enter image description here

Here is the description of the request:

enter image description here

Now go to the web app, stage 1 and copy the generated token and add the following Authorization header: Authorization: Bearer token_here please notice the Bearer keyword should be before the token as in the image bellow. Make a new request now:

enter image description here

Now you will get a 200 Ok response. The response is actually the user id and user name that show's you are authorized as that specific user:

enter image description here

You can download the working solution from here:

http://www.filedropper.com/bearertoken

If for some reason the link doesn't work just let me know and I will send it to you.

P.S.

Of course in your app, you can use the generated bearer token to make ajax call to the web api endpoint and get the data, I didn't do that but should be quite easy ...

P.S. 2: To generate the token:

   private string GetToken(ApplicationUser userIdentity)
    {
        if (userIdentity == null)
        {
            return "no token";
        }

        if (userIdentity != null)
        {
            ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

            DateTime currentUtc = DateTime.UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
            return AccessToken;
        }

        return "no token";
    }
like image 165
David Dury Avatar answered Sep 28 '22 03:09

David Dury