Scenario
I have an ASP.NET Web API that uses the OAuth Password Flow to provide Bearer Tokens to gain access to its resources.
I'm now in the process of making an MVC app that will need to use this API.
The plan is to have the MVC controllers make calls to the API on behalf of the client browser.
The ajax requests from the browser will hit the MVC controllers and then the API calls are made. Results are then fed back to the client as JSON and handles in java-script.
The client should never communicate directly with the API.
Getting Authenticated.
I need to find the best way to handle the Bearer Token once it has been received in the MVC app via a successful call to the web api token endpoint.
I need to use this bearer token in any subsequent calls to the api.
My plan is to store it in the System.Web.HttpContext.Current.Session["BearerToken"]
I can then create a custom AuthorizationAttribute
that will check to see if a BearerToken is present in the current HttpContext, if it is not present, the client will need to revisit the token endpoint.
Does this seem feasible?
I'm asking for peoples opinion on this as I am not convinced this the best solution for my project.
Since you have mentioned you are using HttpClient(). I did a similar thing using HttpClient()-
Get token-
Use the token to Post data
Even if you store the Bearer token in HttpContext, you will need to take care of the token expiry time which is set in the Web API. Validating the existence of token just in the session won't help since the old token will be invalid after the expiry time.
I've managed to come up with something that i think will work quite well.
I'm using the Owin Middleware for Cookie Authentication.
Within the MVC Application i have an Owin Startup file where the Cookie Authentication is configured :-
I then made an AccountController with two Action methods for Logging In and Logging out :-
Logging In.
Logging Out
Protecting the Resources