How do you generate a Bearer token to call a remote Web API

19,378

I eventually found this article and followed its sample code to create our own OAuth Authorization server. With it we can request users tokens on behalf of users using trusted client id and secrets shared between our UI site and the OAuth server.

http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server

Update 1: After working more with the functionality and things, I stumbled across what creates the tokens. There is a TicketDataFormat class within Owin that does all the magic. It accepts one parameter in the constructor and that is a IDataProtector. If the Owin resource server is using the default AccessTokenFormat(TicketDataFormat) in its middleware options; along with the default DataProtector, you can replicate the token generation on your client side. BTW, the default DataProtector uses the MachineKey, so your two trusted sites must have the same MachineKey set in the web.config. All untrusted or partial trusted sites should utilize the standard oAuth flows available mentioned in the link above.

var protector = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
var tdf = new TicketDataFormat(protector);
var ticket = new AuthenticationTicket(){ ... };
var accessToken = tdf.Protect(ticket);

Update 2: The recommended, and really only way you should do this is with oAuth using the Implicit flow with your client, with the correct scopes and response type set.

The IdentityServer3 docs have very well documented tutorials that got us up and running in very little time. Specifically the Calling the API on behalf of the User section in the Getting Started: MVC Authentication & Web APIs tutorial.

Share:
19,378
John C
Author by

John C

Updated on June 14, 2022

Comments

  • John C
    John C over 1 year

    I have two sites, a site that users login to and manage their account and site that has no UI and is nothing more than a API to store and retrieve content. Both of these sites use the same Owin ASP.Net Identity 2.0 setup. The UI site uses cookies for obvious reasons and the API site uses Bearer tokens. I need to be able to call the API methods/urls from the UI site with the current users authentication. In short I need to generate a valid Bearer token in the UI site to add to the HTTP headers when making the Rest API calls.

    I was looking for some way to use a "trusted" client authentication and call the /Token url for the API to generate the Bearer token, or since both sites share the same code and user table call a Owin method to generate the Bearer Token in the UI sites code that I can pass to the API headers and the API site sees it as a valid token.

    If you need anymore info, just let me know.

    Update: Please see updated answer below with correct way of doing this with oAuth Implicit flow.