简体   繁体   中英

Token Based Authorization Web API

I'm building an application using backbone.js and web api. JS client will send ajax requests to access api. Building an API is pretty easy but i want to implement authentication and authorization for API.

I'm planning to return a token after a successful authentication and use this token for further requests. This token will be passed in HTTP Authorization headers. My requirements are as below 1) Verify token on each request and get user id. 2) Use fetched user id for further actions.

First bit can be handled using Custom action filter where the permanent token can be verified against the database. But i'm not able to find any sample or example for doing a second bit. I want to get a userid from a passed token and carry it further for later processing. Is there any way of doing it?

Waiting for suggestions or ideas. Any code sample will really help. Thanks in advance.

You can set Thread.CurrentPrincipal upon successful token verification like this:

IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), null);

Thread.CurrentPrincipal = principal;
// if we're running in IIS...
if ( HttpContext.Current != null )
    HttpContext.Current.User = principal;

The principal might also be an instance of a custom class implementing the System.Security.Principal.IPrincipal interface (in order to be able to have its user ID associated).

I further suggest you use a DelegatingHandler instead of an action filter for the token verification in order to set the current principal as early as possible during the message lifecycle. Additionally, this way you don't have to decorate every action method/controller with the action filter attribute.

I highly recommend to use OAuth. Anyway, you can set the token and user info in session and use them in subsequent calls. ie if the session is active and user info exists then use them otherwise authorize and authenticate user (probably through OAuth) and if it is valid then store them in session to be used in subsequent calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM