Search code examples
asp.netwcfgeneric-handler

Create session oriented API's in asp.net Framework 4.0


I am working on a project where mobile apps connects to website through a set of API's. I considered creating API's using "Generic Handlers". This was seems to be working fine until restriction are defined for sensitive data. User has to be authenticated before he makes request for data.

I created a login API where user credentials are validated and a encrypted string which contains the same credentials which he provided at the time of login are returned back to the user after successful validation.

Each time a user makes request after successfull login, an encrypted string was supplied back to server in header. On server side, the encrypted data is decrypted and validated against with the credentials stored in DB. This step is unnecessary as user is recently authenticated. Is there anyway I can avoid authenticating user for each requests. I am planning to go with WCF services where Session can be effectively used to achieve the same (is this is something good idea?)


Solution

  • I did the same steps as you are doing for my API's. Here are some of the changes I made in the authentication part.

    1. Client sends his credentials (username and password) to /api/login
    2. Server validates the credentials and forms an encrypted string with identify of user and some necessary data like expiry date. Call this as token.

      var tokenStr = "user_id=1234;expire_date=" + DateTime.Now.AddMinutes(20).ToString(); var encToken = AESCryptoService.Encrypt(salt, tokenStr);

    3. Return this encrypted token to the client

    4. Client sets this token in the HTTP header (X-App-Token) to make future API calls.
    5. Server detects and decrypts this token. Here you can trust this token if decrypts with your salt. Get the user_id and set the current thread principal and proceed with the request.
    6. If the token expires (read expire_date) then return 401 Authentication request, so that the client can request the token again.

    You can also use SHA-1 or MD5 or some signing/encryption mechanism to make sure that the token string cannot be altered other than you.