Web api authentication schema - asp.net

I'm implementing a rest api to using the new web api framework. This api will be consumed by other companies so we'll be adding an authentication method.
In relation to authentication, I'm thinking to implement something based on tokens. Something like this
client provide credentials to login method
system authenticate client and send a token
client uses this token on following api calls
I wonder if this schema is useful for my scenario. Operations will be mainly atomic, basically clients will periodically ping this api to get some specific data, so not sure if make sense having a session token (at some point the token should expire and not sure how to manage this).
How would you recommend to implement authentication schema for this scenario?

When you generate a token I would store it in a database with a foreign key back to the authenticated login's primary key. I would also (with the token) store the date and time it was established, and a timeout period (you could set this per token, or store it in a config). Check the token/time everytime the service is pinged by that user, then force them to reauthenticate after that time expires (by checking it against the created date stored with the token).
This would make sure that the login information is only getting transmitted after the token expires, when a new token is generated it would delete the old token record.
Am I understanding your requirements right?

Making a token based authentication scheme like this is not easy.
I don't really have an answer for how you could implement it in a good and secure way. But will offer some thoughts off the top of my head about issues you will have to deal with:
The token generation need to be well randomized and the tokens need to be "sufficiently" (for some definition of sufficient) long in order to prevent someone from simply sending a bunch of different tokens to see if he "gets a hit"
The above issues should not be too difficult to implement. But the more tricky thing to figure out is:
How you can you reliably verify that the token has not been "kidnapped".
If the token is simply some random string, then anyone who happens to "see" it in tranfer (use SSL) will be able to assume the identity of the use for which the token was generated.
The token, when received by your service will let you know that:
Your application issued the token to user/application/entity X
The token is intact (has not been changed)
Any other thing you store with the token (is it expired etc)
But it will not without further effort let you know for sure that it was sent by user/application/entity X. It could be Y who has managed to get hold of the token.
That is the case for many authentication schemes of course, so depending on just how sensitive your data is, and also on what kind of operations can be done via you service, it may not be a huge issue for you.

Related

Is it safe to use JWT token for initial authentication but then express session from then on?

I'm looking at using Firebase authentication (essentially JWT) with my React and express application and I wondering about the sanity/safety of mixing it with long-term session management.
The reason I'm thinking about this is because Firebase is free and very easy to integrate. However, verifying the JWT token server-side is an expensive call that I don't think is supposed to be performed on every request. Firebase offers a secure cookie, but there is a max ttl of 2 weeks. My app doesn't need that much security and I think the majority of my users would be annoyed if I asked them to re-authenticate every 2 weeks so I'm looking at a better solution.
So here's my thought:
User authenticates with Google/Firebase and front-end gets the token.
Front-end sends token to back-end and back-end verifies token with Google and checks that log in time was recent.
Back-end then creates or gets user from my db and sets the user id in a long lasting express session and all subsequent requests use that (except in the case of something rash like deleting your account where I would require the token again).
Essentially this is using the token to do the initial authentication/verification, but afterwards using the standard express session.
As far as I can tell, this really isn't different from what passport does after authenticating. But I would appreciate some verification that this is relatively safe given that it's over HTTPS and I protect against CSRF.
The biggest problem I can see is that it's not as safe as the token method in the case of theft because of the token's shorter lived nature, but is it any worse than using passport and having to store my user credentials myself?
So is this safe or stupid?
Thanks!

How is JSON Web Token more secure than cookie/session?

How is using a JSON Web Token more secure than an opaque session token, In both the scenarios the tokens are first sent to the client and then verified on the server when a client requests a protected resource.
There are several reasons people say JWTs are more secure. I’ll list them and also give you reasons why that might not really be the case as it swings both ways.
JWTs can be signed using a secret with secure algorithms like HS256 and RS256. A comprehensive list can be found here. On top of that, you can also encrypt the payload of the JSON Web token. However, session tokens can also be generated securely with a top-notch algorithm and stored in a signed cookie.
JWT can either be stored in a cookie or Web Storage( local/session Storage ). If you are not storing your JWTs in a cookie, then you are not vulnerable to CSRF. And you can decide to send them through the Authorization header for every HTTP request. However, there is still a caveat. Javascript is used to access the JWT from the Web storage, which still leaves you open to other forms of attack such as XSS (Cross-Site Scripting). Worthy of mention is that it is easier to deal with XSS than CSRF.
In a situation where your JWT has been tampered with, you can revoke or blacklist the token. This involves making a call to the DB every time you want to perform this kind of operation which I won’t advise you to do. The preferred option is to use short-lived tokens.
In the case of OAuth, opaque tokens otherwise known as bearer tokens are random strings that will be stored in some kind of hashed storage on the server together with an expiration, the scope requested (e.g. access to friend list) and the user who gave consent. Later, when the API is called, this token is sent and the server lookup on the hash-table, rehydrating the context to make the authorization decision (did it expire? does this token have the right scope associated with the API that wants to be accessed?). The main difference between opaque tokens and signed tokens(e.g JWT) is that JWTs are stateless. They don’t need to be stored on a hash-table.
Conclusion
The libraries used to sign and encrypt your JWTs should be secure to ensure your authentication process is also secure. You should also use cookies as storage mechanism rather than using them for login. You can argue that there are more benefits to using JWTs like they are easier to scale and they can be used in OAuth cases which you can find in this article. At the end of the day, In my opinion it simply falls on the developers’ reasoning/logic to ensure the right steps are followed to make an app secured regardless of what form of token is used for authentication or authorization. Use case is also key in this context!

RESTful best practice for authentication

and thank all of you for viewing this question.
I am not sure to on how do this so i am asking for the community help on this matter.
I read int his post Can you help me understand this? "Common REST Mistakes: Sessions are irrelevant" that sessions are not "completely" advised on the REST convention, and that all authentication should be made using HTTP Basic authentication or Digest.
Ok, so far i get it.
But has far has i know, basic authentication is made on the actual server against a regular non-encrypted text file.
Would it be going against the convention, putting the username/password in the http request parameters, instead of passing them down trough the headers and letting the web server do the authentication?
This way, for every request made, the user/pass parameters would be checked and managed using my own logic. I mean using a database table, that has all the info necessary for the application.
The method I currently use is the first request is for a auth token via a POST method, which contains Headers of Username and Password, these are then verified against my authentication methods. If the credentials are valid, I return a time limited token. All subsequent requests must have the auth token as a header, which is checked and if valid access is allowed. I maintain the list of valid token in code and expire them as required. This is faster than having to validate the username & password on each call and is slightly safer than the username & password being passed in with each call as a token could be stolen, but it is only valid for a small period of time.
All of this this must be run under SSL otherwise the data is not secure and users credentials can be read.
Basic auth is handled by the server however the server chooses to handle it. There certainly doesn't have to be a plaintext file containing usernames and passwords! My current client stores passwords in a 1-way salted hash in their database. On an incoming request, the plaintext password is pulled from the header, salted, hashed, and them compared to the database value.
Putting a password in a request parameter is a really bad idea. What happens when a user copies and pastes a URL to email to their coworker?

Asp.NET WebAPI custom authorization

I want to create a authorization mechanism for an application based on WebAPI and AngularJs.
I've seen some articles, which use BasicHttpAuthentication, but i really don't like the whole idea of sending username, and password on every request. The more it doesn't fit for me is because i want to use OpenId authentication, where you don't have username/password pair.
I'm thinking about a solution, but I don't really know how to implement it. The concept is that user is authenticated as in an usual Web application - posts a form with user / password or selects an OpenId provider. If the user is authenticated succesfully, it is placed in a static object, which stores the User object for a certain ammount of time. Next a usertoken is generated and passed to the Client Application. The client passes the token on each request to the server, if the user exists in the above mentioned static object with the appropriate authentication token it is authorized to get the data.
Firstly - Do you think this is a good approach to the problem?
Secondly - How should I pass the authentication token, WITHOUT using cookies? I guess it should sit in the request headers, like in BasicHttpAuthentication but, I really dont' know how to handle it.
BasicHttpAuthentication
I'm with you on feeling dirty about caching the username and password on the client and forever transferring it with every request. Another aspect of Basic authentication that might work against you is the lack of sign-off. Other than changing the password, you can't "invalidate" a basic authentication session. Tokens on the other hand, will typically offer an expiration date, and if you want server-side invalidation you can check the issue date and say "any tokens older than issue date xyz are invalid".
Server State
You mention "If the user is authenticated successfully, it is placed in a static object". But this is independent of the token? This sounds like you're wanting to implement server state management of authentication sessions, but this isn't strictly necessary. The token itself should be sufficient for user authentication, managing server state is another potential obstacle. Server state can become difficult to manage when you factor app-pool recycles or web-farm environments (what if you want two services to share the same authentication token, but not require communication with a central "authentication server" for storing the state / session?)
Passing Authentication Token
Headers is definitely a good place for it. Really, where else is there? Cookies, Headers, Message. Other than a browser client, cookies don't make a lot of sense, and including it in the message can muddy your message formatting a bit, so headers is the only remaining option that makes much sense in my view.
Client Implementation
You've not specified, but I suspect you're interested in calling the service from .NET? In which case System.Net.Http.HttpClient could be your friend. In particular, the DefaultRequestHeaders collection. You can use this to add a custom header to store your authentication token.
Server Implementation
When researching ASP.NET authentication recently, I learned a lot about customisation by examining the Mixed Authentication Disposition ASP.NET Module (MADAM). I wasn't interested in using MADAM as-is, but learning about it from that article and examining the source code gave me a lot of ideas of how I could insert my own authentication module into the web stack.

ASP.NET Web Api (REST): Authentication using the users credentials or a token? Leave "Register new user" resource password free?

I am trying to create a REST service using asp.net web api and everything is working fine but I have now come across what to do with authentication.
I am a little confused of where to start, here is what I have been thinking.
I have an REST api that consist of a number of resources, each resource will need the user to be registered, so what is the best action for doing this? Should I just send the username and password in the header on each call to the service so I can authenticate on the server using
AuthorizationFilterAttribute
I should at least encrypt it though? I would be interested to know what others are doing, I know there is a concept of creating a token (which I presume will be short-lived) so hence the user would authenticate and then would receive a token, this token would then be sent on further calls to the service. So how would I handle the problem when the token expires?
I also have a resource that is used to register a new user, actually the only things that will be calling this is my clients (Android, iPhone). SO should I leave it FREE of any authentication methods or put a hard coded password or something similar so that at least nobody else can register new users? Bearing in mind that the service will be public on the internet.
I just don't seem to be able to find the correct way of doing this, I certainly want to try and get it right the first time so I don't have to refactor the service completely.
The following link appears to cover some sensible DIY options http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/. The "Tokens based on Public/Private Keys" section covers an approach I have used effectively in the past and would maybe be of assistance to you.
At the moment though I am using http://identityserver.codeplex.com/ the Thinktecture IdentityServer with OAuth bearer tokens ("Resource Owner Password Credential" grant type)... I am finding this a very good set of code and examples to work from and have IOS clients obtaining tokens and calling the WebApi.
If you really must secure your registration screen you could maybe use client certificates installed on the devices to authenticate... again the Thinktecture service could help here https://identity.thinktecture.com/idsrv/docs/default.htm?RequestingatokenusingOAuth2.html. Although if you registration process is secure What are best practices for activation/registration/password-reset links in emails with nonce e.g. email confirmations and activations etc. it may be safe to leave publicly accessible - this all depends on your business requirements and desired sign up workflow.
You should at least use Transport Level security SSL but as you suggest message level security e.g. encrypting any tokens is very advisable - the OAuth spec has something to say about this http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#mitigation.
Regarding expiring tokens - we tend to expire our tokens with the same frequency as our password changing policy; although keeping the validity time down is important (to minimise impact of token theft) and a consideration to balance against your requirements. OAuth has the concept of refresh tokens Why Does OAuth v2 Have Both Access and Refresh Tokens? some debate and links around this topic here, we are not currently using this approach as the ID server we are using doesn't currently support this.
Keeping your tokens safe is also a consideration e.g. we are using the KeyChain in IOS, but also think about Mobile Device Management policies if possible as if these tokens or passwords are one the device they could be stolen, perhaps look into jailbreak detection, lock screen enforcement etc.

Resources