Web API - Token

2

An MVC application makes access to the WEB API services.

To access the WEB API, a token is mandatory.

In the WEB API application there is a button that generates the token.

How to make the WEB API accept only the token generated through the MVC application without using a database?

I made the MVC generate the token (a GUID + date) and pass this token to the WEB API that validates if the date is within a 30s period. If it is within the period I consider that the token is valid.

byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));

if (when < DateTime.UtcNow.AddSeconds(-30))
{
    return false;
}

This works, however, any GUID that is entered concatenated from a date will be valid. I need to have my WEB API know exactly which token the MVC application generated.

    
asked by anonymous 21.03.2016 / 21:53

1 answer

3

There are several solutions to your problem ...

  • When generating the token in the MVC application, send it to the WebAPI (through a restricted endpoint, which only you have access to), upon receiving the token, its API will store it in memory in a static list / dictionary. The problem is that you can not kill the process or restart the server where the WebApi is and when the Pool (if you are using IIS) restart, all data will be "lost". (In this case, it would be even easier for you to create the direct token in the WebAPI and create a restricted endpoint that only the MVC accesses to obtain the token, each access generates a new token and deletes the invalid ones from memory [collection / list / dictionary / hashset ])
  • Add a SALT (a pre-defined, random, application-aware string) to your token, encode it with SHA1 or another encryption algorithm (in this case, you do not even need the GUID ...)
  • An unsecured but effective solution to your problem would be a SALT + GUID + date, all this encoded in Base64, however as I said, this is not safe, and anyone with intermediate knowledge, who view the token will realize that it is a base64 string and can pass it in a base64 decoder and see the original pattern without major complications ...
  • Implement OAuth or JWT (but I have a feeling that this will require a database).
  • Why can not you use a database? Is not even a noSQL authorized? Why do not you do this using Redis?

        
    10.01.2017 / 07:11