9

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?

2
  • 2
    This is EXACTLY the question I have. I have opened a ticket with MS and we r getting closer but not there yet. I will let u know once I find out. Commented Aug 2, 2014 at 18:47
  • @MikeW: I added an answer with a working solution bellow. Check it out. The method that generates the token I found it on the net but don't recall exactly where ... Commented Aug 2, 2014 at 20:22

1 Answer 1

7

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";
    }
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for the reply and download it is greatly appreciated. One rather large detail I failed to mention is the web api and mvc apps are separate projects, both secured by OAuth upon project creation. The route I have been using the ADAL classes from my client (MVC) and I get a token but it is not valid in the Web API. I have been going through the code you have generously provided, but what's missing from the token is the resource of the external web api (and probably a few others). I cannot get ADAL to work, and I am going to try yours next, but I am leery...
I think that having them as 2 separate projects is not an issues as long as booth they make use of the same db context which in my example is ApplicationDbContext because tokens are issues per user and then Web Api make's use of that token to authenticate the request. Therefore should have in the background same db where users are located for which the tokens are issued. I will guess you should check the Startup class and make sure you have them right in booth projects.
Another thing what you can do ... is take that method that generates the token, from my project, and implement POST or GET web api endpoint. Let's call it: api/generatetoken that accepts two strings: username and password. Then in your MVC you can call that endpoint when users login for example so you can get the username and password and call the endpoint.
That will return you a string which is the token. You can save that token in a custom userprofile table. You can also add another property to the userprofile table: ExpireDate. Each time the user log's in you can check the expire date of the token if it's not expired make calls to API otherwise call again generatetoken endpoint so you will get a new token.
I have the same problem that you describe but cannot create a valid access token return from Web Api endpoint. The link you provided with your working solution isn't working, please can you provide me with your solution.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.