Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
How we can generate random , unique and secure token for a web api that will be consumed by different web and mobile applications.

What I have tried:

reserached different techniques
Posted
Updated 30-Mar-17 6:28am
v2

1 solution

You may use this, RNGCryptoServiceProvider Class (System.Security.Cryptography)[^] and it provides a secure random — not a seeded random number. In most secure cases this is the random number generator that should be used instead of the plain old Random class of the .NET framework. You can read more about this object on the MSDN page itself.

Update:

If you are using the token only for the sake of authentication, like OAuth etc. Then I would recommend using the Guid object, to create a new unique string for every device. It has a size of 128 bits (2128 + 1) is a huge amount. You can generate that quite easily as well,
C#
var token = Guid.NewGuid().ToString();

Then this can be stored and used wherever needed. I used this method in my own application. The secure and cryptic way of generating a token would be useful in cases where everything needs to be private — cash management is one of the examples here, encryption/decryption or generating the secure keys or salts for password hashing.

For more on this, please see: Guid Structure (System)[^]
 
Share this answer
 
v3
Comments
Member 9129971 30-Mar-17 13:25pm    
thanks great, any points which you i should keep in mind while using this technique and generating token for webapi.so to make it secure.
Afzaal Ahmad Zeeshan 30-Mar-17 13:35pm    
If the token needs to be secure, such as for currency or for encryption, then you should use it. Otherwise, the pretty old Random or the Guid objects are enough.

If the tokens are just going to serve for authentication, then consider using Guid, they are unique to an extent. I personally used Guid in my web application that I developed a while ago. :-)
Member 9129971 30-Mar-17 15:36pm    
also its always that we find billions of articles for any issue online but for securing webapi found only one article over whole internet that seems to be used by the whole world. and that is this one http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ . But this includes heavy configuration and many things behind the scene and found difficluties in implementing according to my requirement.
Afzaal Ahmad Zeeshan 30-Mar-17 15:41pm    
Security is a tough concept, brother! :-)
Member 9129971 30-Mar-17 15:46pm    
no doubt :), btw thanks for your response and quick reply.And best wishes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900