Bearer token in MVC controller to access Web API

2.4k views Asked by At

I have two projects: MVC, Web Api

In the Web API project I am using bearer token authentication. This token expires after 24 hours. In my MVC project I'd like to call the Web api project via MVC controller (server to server). What's the best way to:

  1. Get a token
  2. Renew token after 24 hours (or whatever expiration is)
  3. Make call to secured action method

My idea was to use WebClient but I wasn't sure if there was a better way to go about this.

I am not set on using bearer tokens either. But need a solid way to authenticate both server to server and client (angularjs) to server (api).

1

There are 1 answers

1
JotaBe On BEST ANSWER

OAuth flow for server to server:

  • your web server connects to your Authorization server (AS, included in the Web API host, in this case) with a shared secret
  • the AS (web API) returns the token to your web server
  • the web server stores the token to use it on the next Web API calls

As to the client to server, the flow is different:

  • when a user is using your web application, and it needs to access the Web API, your application redirects the browser to the auth server, where it informs the user which resources (Scopes) is trying to access the application, and asks for approval. This redirect includes an url callback
  • if the user approves the access, the AS redirects the browser to the callback url with some information in the query string, which includes a token
  • the browser checks the url and, if the user approved the access, it uses the token in the url to go ask the Auth server for the Bearer token
  • if it's an SPA, the browser stores the bearer token and uses it to access the Web API. If it's not an SPA, the token is usually stored in a cookie, so that it's not lost

Handling the token expiration:

The token has information on the expiration time, and usually includes a refresh token. You can use the refresh token to present it to the AS before it expires, so that you don't need to askfor a new token

Notes on configuration

The different flows must be configured in a different way in the server.

The first flow for "server to server" uses a shared secret to directly return the berare token to the server application. In this case there is no need for user approval, because there is no user involved in this process

The second flow, from (not trusted) client to server needs the authorization of the user because your client application is going to access some resources of the user (resource owner) on his behalf, so it needs his approval.

There are other flows, for eample fro trusted clients, but they don't apply to this case.

A typical implementation of all these things is dotnetopenauth. It's very well documented, and it handles all the nitty-gritty for you.