Separate authentication server for users and APIs - api

I'm working on a cloud service authentication system and I'm not entirely sure what the optimal way to handle authenticating requests is. We're planning to run our image server as a separate process from our API server so that we can scale them independently of each other. Handling request authentication with API keys is fairly simple, because we can just have the image server store its own API key and check that requests provide it in a header (over HTTPS obviously), same with the API server. For users though it gets more complex.
Right now we have it setup so that the API server will handle generating a session token and storing users in its database, however what we'd like to do is use 3 servers:
authentication server
API server
image server
and have the image and API servers authenticate requests against the authentication server. How exactly should this be done though? It seems like a bad idea performance-wise to hit the authentication server for every request that the API and image servers make. Can/should a token be verified from a different server than it was created on?
So for example: can/should I pass the token received from the authentication server to the image server, verify that the token came from "my.auth.server" and check that the user ID is the right one? Would JWTs be a good type of token for this?

Here's an alternative approach.
Your authentication issues a JWT token that is signed using a secret that is also available in your API and server images. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.
That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API and image servers from having to call the authentication server at all as all the information they need for both authentication and authorisation are in the issued token.
Flow (no refresh tokens):
User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server.
User uses that token to talk to your API and image servers and assuming user is authorised), gets and posts the necessary resources.
There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database to make them revokable before they expire (think "revoked" column in tokens table).
New flow (with refresh tokens):
User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server, alongside a long lived (eg: 6 months) refresh token that they store securely
Whenever the user needs to make an API request, the token's expiry is checked. Assuming it has not yet expired, user uses that token to talk to your API and image servers and assuming user is authorised), gets and posts the necessary resources.
If the token has indeed expired, there is a need to refresh your token, user calls authentication server (EG: POST / auth/token) and passes the securely stored refresh token. Response is a new access token issued.
Use that new token to talk to your API image servers.
OPTIONAL (banning users)
How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.
Things to consider:
You may want to rotate refresh token. To do so, blacklist the refresh token each time your user needs a new access token. That way refresh tokens can only be used once. Downside you will end up with a lot more refresh tokens but that can easily be solved with a job that clears blacklisted refresh tokens (eg: once a day)
You may want to consider setting a maximum number of allowed refresh tokens issued per user (say 10 or 20) as you issue a new one every time they login (with username and password). This number depends on your flow, how many clients a user may use (web, mobile, etc) and other factors.
You can store some additional metadata (ip, geolocation, device, browser cookie, etc.) alongside refresh tokens. That way, you can be smart about when to reject malicious usages of refresh tokens in case it's compromised.
Common Q: Why store all refresh tokens, and not just revoked ones? You could do that. Ask yourself the following: Will I, at any point, need to have a functionality where I can dynamically revoke valid refresh tokens, based on some arbitrary, regulatory, legal, integrity, security etc. criteria? If so, the least you will need is a list of all issued tokens, plus any data required to implement the criterion logic. Example: Due to regulation, I need to ban all EU users equates to a delete from refresh_tokens were user_ip in <... eu logic ...>

one of the best ways to use is a JWT Token , you can generate and share it between all your servers and validate it on the server side .
https://jwt.io
also I think the best architecture to use in this case is the micro service architecture

Related

What are the benefits of implementing OAuth (JWT access tokens with refresh tokens)

Current Setup
I'm currently building an application, and have just finished implementing an OAuth authentication server. This is my first "real" attempt at a project that has a legitimate user authentication and management component, so much of this is new to me.
I've implemented the OAuth specification. This means the following:
The authentication is deployed on a separate webserver with a separate DB than the application server.
The auth server logs in a user, and issues them two tokens. One is a JWT access token that contains information about their user identity. This has a short-lived 15 minutes expiry. The second token is a refresh-token. This is a single-use token with a 7 day expiry. It is used to fetch another access token with the application server returns a 401 (the access token has expired).
The application server shares a secret key with the auth server, and has middleware that verifies the JWT access token.
Concerns
My concern is that I've over-engineered a project that didn't need this much complexity. Since the auth/app are distinct, this means that my client code needs to be aware of, and handle refresh token rotation. It needs to interpret 401s, and fetch another access token.
As far as I can tell from my reading, this wouldn't be necessary with simple session cookies that persist. The cookie is just included in requests to my domain. If I killed this approach, and just had my server do a DB lookup on a signed session cookie - I would avoid a lot of this client complexity.
One consideration is that I’m using a React SPA frontend client. This is also new territory for me, so I’m not sure whether or not this changes the situation.
As I said above, I'm new to a lot of this so could use some advice from people who have worked in this space for longer and have the experience. Is OAuth worth the hassle?
Options
OAuth with access tokens (JWTs) and refresh tokens:
Pros: Provides a secure and scalable way to handle user sessions.
Cons: Client needs to be aware of refresh token rotation procedure and handle 401 responses by using the refresh token to request a new access token, which can add complexity to the client-side code. Also adds complexity (and cost) to the AWS infra stuff. I need to know how to get the auth server and app server on the same base URI. Also makes my local dev environment a little more involved.
Server-side sessions using signed cookies:
Pros: Simpler for the client, as it does not need to handle refresh tokens or 401 responses.
Cons: Server needs to manage session state, which can be more resource-intensive. This means a DB call on every request.

API Authentication for PWA

The Setup
We’re building a PWA (progressive web app). The main components are the app shell (SPA) and the API. The REST API will supply the data needed for the app, while the SPA will handle the rest (as per Google recommendation).
The Problem
Authentication of the end-user seems problematic because the web browser needs to be accounted for. We want the user login to persist through closing down the browser.
We’ve done the research about the possible ways of going about it, however we’d like to ensure that we’re not going in the wrong direction.
Solutions we’ve considered
Session based authentication - the user sends username and password to /accounts/auth and receives a HTTP only cookie with the session ID. The session needs to be stored in a database or Redis. The issue with this option is that cookies are automatically sent by the browser therefore we need a CSRF protection in place. Using the Synchronizer Token Pattern a new token would be generated every time a state changing request has been made e.g. POST. This means that the application needs to supply a CSRF token with every request so that the PWA can send it via AJAX. We determined that it’s not ideal as the user can send multiple post requests in a quick succession making some of them fail and resulting in a bad user experience.
We could also use this method without the CSRF by limiting the CORS policy to same domain and adding a header requirement which technically should stop all CSRF, however we're unsure how secure it would be.
JWT token based authentication - the user sends username and password to /accounts/auth and a new JWT token is issued. The JWT then needs to be stored in localstorage or a cookie. Using localstorage means that JWT is XSS vulnerable and if the token is stolen, an attacker can impersonate the user completely. Using cookies we will still have a CSRF issue to resolve. We considered a double submit cookie method but the CSRF would only refresh every time the JWT is reissued which creates a window for the attacker to find out what the CSRF is. It is not clear which method is best to use.
Session based authentication + JWT token authentication - the user sends username and password to /accounts/auth, a session is created, a HTTP only cookie is set in the browser and a JWT token is sent back to the user. The PWA can authenticate requests with the JWT and whenever the JWT expires the app calls /accounts/auth again to acquire a new one. The /accounts/auth endpoint would still need to be CSRF protected, however the impact of it on usability would be minimised.
There seems to be a large amount of articles claiming that localStorage is insecure and shouldn't be used so why are high profile organisations like Amazon still recommending it? https://github.com/aws/amazon-cognito-auth-js - this SDK uses localStorage to store the token.
You don't need to generate new CSRF token each time a client make a request. It's much easier to use a scheme like token = hash(id + secret + current_day). You only need to update it once a day, or even employ mixed scheme (if the token is invalid today, but is okay for the previous day, the server accepts the operation and returns new token in a predefined header for client to renew it). You may also use the cookie as an id, making the token totally stateless and much easier to check, no need to store them in the database.
Here is how I look at it.
JWT token authentication : with this approach, you can always use a time-bound token with its expiration set to say 2 hours or something?
Or another approach would also be to try and see how you could use some of the approaches the Credentials Management API suggests for example, auto-sign-in of users whenever they come back.
Stuff like 2-step verification with OTPs for instance; for very important features in your web app can be a choice. In this case basic stuff are tied to whichever one time authentication method you have.
Actually, you can also use user-defined pins or short codes (seen a lot in banking apps) to grant access to some features in your web app.
Hope this helps, or sparks some ideation.

Should OAuth 2.0 be used for Authentication Timeouts?

Developers of a mobile application are using the timeout period of OAuth 2.0 tokens to check when the application must re-authenticate with the server.
This conflicts with my understanding of the proper use of OAuth 2.0 tokens, although I am not exactly sure that I am correct.
My understanding:
OAuth is not about authentication but about authorization, e.g. can this device access some resource on a server on behalf of a user. Authentication logically precedes authorization and is about confirming the user is who they say they are.
So a user presents credentials (username and password) and the server authenticates that yes, this user is Bob.
The application Bob has logged into wants access to some resources on the server Bob has been authenticated to - say data from an API. So the application requests an OAuth token and it is granted, and one of its attributes is how long it exists. The application and the server exchange keys, and the data between the application and server is encrypted using the key.
An intruder reading the plaintext communication will not be able to decode it without the key. However, if an intruder is able to get the key they will be able to.
This is where the OAuth token end of life comes in. We don't want to use the same OAuth token (key) forever, because if an intruder was able to get that token they can decript our communication forever. If however, we refresh tokens every x hours, then they could decrepit the information only for x hours (let's say 2 hours).
I don't think the OAuth token expiration time should be connected with how long the user remains authenticated. That is simply up to the developers. In our case, if the user has some device security (a passcode for example), then we can let them remain authenticated for a long time (months for example). If they do not have device security then I want to force them to re-authenticate after a reasonable amount of time of inactivity, maybe 24 hours.
Is this correct or not, and if not, what parts.
Thanks in advance.
Bryan
Your understanding on OAuth 2.0 is correct. In very abstract manner, the protocol define a way to obtain tokens, which can be used by a client to communicate against a protected endpoint.
RFC6749 mandate the usage of TLS when communicating with authorization server (the token obtaining) as well as when using it against an API/protected endpoint (Bearer token usage as defined in RFC6750). This protects token from in-transit attacks.
The OAuth access token is recommended to have a short life time. This is to avoid token stealing as well as token misusing that can be done by client. You can read more about best practices from RFC6819. Access token lifetime specifics can be read from here.
Now about selecting the correct life time. As you already figured out, using a refresh token is the desired approach to renew access tokens instead of having a long lasting access tokens. For example, a refresh token can be valid for few days while access token valid only for few hours.
But be mindful about the following,
+ Whether your application can obtain and secure a refresh token
For example, SPA cannot obtain a refresh token as it cannot store it for extended time. In such case you need to look for alternative mechanisms to renew the access token.
+ Is access token used against external domain
Using access token toward an external API increase the threat vector. For example, if you have a closed system (client and backend in one domain) then you may think of increasing access token life time. But not for an extended period like 24hours.!
+ Single sign on (SSO)
Instead of using long lasting access tokens, you can get the help of authorization server to maintain an SSO behavior on top of browser. This is similar to "remember me" you observe in modern login dialogs. Once logged in, browser maintain a cookie which lasts for some time (ex:- A week). The next time you use OAuth token obtaining flow, your authorisations server detect this logged in state, hence skipping login dialog. Of course, such approach must be decided on exact security/policy requirements.
In conclusion, use access tokens with reduced life time.Using refresh token is the desired approach for token renewal. But depending on the situation, you can choose alternatives as well.

Managing blocked users in ASP.NET Core 2.1 API which uses JWT

I have been using JWT to authenticate the users for the HTTP endpoints in my ASP.NET Core 2.1 API project. I have configured the authentication service and everything is going on well.
while generating the token, I usually set the expiry to 24 hours. My problem is, what if the user is blocked by the admin after issuing the token. Now that the token is issued the authentication middleware will simply authenticate the request.
So, I thought I need to intercept every request to make a backend call to know whether the user is blocked or not. I can do this at every endpoint level, but it is not so efficient I think.
What are the optimal solutions for this issue, which is quite common? Are there better ways to solve it than what I thought?
When you choose to use a JWT then accept the nature of the JWT. This means that the only way to have 'real-time' information is to expire the token when the information becomes obsolete. Set the lifetime of the access token to a small window, like less than five minutes. This way you know the information is always valid and you don't have to change anything about the current handling. This is 'almost real-time', as the changes become effective within five minutes.
The advantage of a short lifetime is that this also increases the security of your website. When the token is compromised, it can only be used for a short time.
You'll have to add support for a refresh token, because you don't want the user to login every five minutes. So when the access token expires use a refresh token to request a new access token. This will only work for apps that can keep a secret. Because the refresh token is very powerful and you don't want it to fall into the wrong hands. You can use one-time only refresh tokens to limit the risks and add strategies to detect different behaviour. For more details read my answer here.
You can also choose to remove authorization claims from the JWT and move authorization to your middleware, where you can real-time check the permissions of the user. In that case the JWT only includes the user claims that identify and model the user. Claims that are not likely to change very often. As a result the access token doesn't have to be short-lived, but for security reasons I think this is still advisable.
The minimal requirement is a sub or userid claim. This is enough to identify the user and grant the user access to the website.
I think the Policy Server is a good example of a possible middleware authorization implementation. Here the middleware reads permissions from a json file and adds permissions as claims to the identity. Where policies decide what the user is allowed to do. Also implement resource-based authorization.
An alternative is to use reference tokens, as implemented by IdentityServer. IdentityServer stores the contents of the token in a data store and will only issue a unique identifier for this token back to the client. The API receiving this reference must then open a back-channel communication to IdentityServer to validate the token.
The advantage here is that you can revoke the reference token at any time, using the revocation endpoint.

I can't understand the JWT Authentication well

Nowadays many developers use the JWT Authentication to authorize the api call.
By the way, if a hacker can capture the api call request of the authenticated user then he can have the authenticated JWT token.
Then the hacker can access this api with the authorized JWT token, without his authenticating.
Is this alright?
I am wondering that the JWT Authentication is actually safe.
Can you explain that?
A jwt is a code that contains information about the identity and claims of a user and is valid for only a limited amount of time.
The code cannot be read nor changed by anyone, except the authorization endpoint that issued the token. It is therefor safe in the sense that it cannot be tampered with. This means that the token can be fully trusted. You don't have to validate the token and you can use the identity information and claims without having to consult the database.
But this is also the disadvantage. Once issued the token is valid until it expires, since the expiration cannot be altered. That is why the token should only be send over a secured line to the server. You wouldn't want a hacker to intercept the token.
But if it happens, then what?
There are several options. You can use short-lived tokens, which means that a token expires short time after being issued. If a token was intercepted, it is only valid for a small amount of time. In that case you take for granted that a hacker can have access for limited time to the system. The advantage is that you need less resources and the effort of hacking is probably not worthwhile.
Another option is to validate the token on each request. This requires more resources (e.g. lookups in the database), though you can use some sort of caching. If something changes, like the ip address, then you can invalidate the token. But the question is if you can detect if a token was send by a hacker.
So it depends on the chosen strategy. But: if you issue a long-lived access token without validation (and thus without the possibility to revoke the token), then you'll have a problem if a hacker gets hold of an access token. So you'll need to do something to use it in a safe way.
While I think this should be enough to help you understand, I would like to mention the use of refresh tokens. If you use short-lived access tokens, then you may want to implement long-lived refresh tokens. These refresh tokens are meant to obtain a new access token after it expires. The advantage is that you don't need to send the credentials, the refesh token suffices. You can however only implement this in an application that can keep a secret. Because you most certainly do not want a hacker to intercept the (long-lived) refresh token.
Being used less frequently (opposed to the access token) you can add logic to validate the refresh token when used. You can consult the database and decide to reject the request (e.g. when ip address changed) and revoke the refresh token. In that case the user has to identify itself again (send credentials).
JWT is just a secure msg transporter between fsb server and client so that fsb server can determine whether the client is logged in or not; if logged in, the fsb server will fetch personal unique user based data.
google oauth
G sends back user gid to my server only if user has a google account and successfully inputs gmail and password correctly.
user id is saved in jwt’s payload.
jwt
if google validates the user and google returns gid
create jwt content and internal maintenance: exp date, encryption
jwt is sent and stored in local store of user’s browser;
each user’s req sends jwt back to my server
my server decodes the jwt using secretOrKey, which only my server has, and gets the content(uid) from the jwt.
if uid is in my db, user had already registered and right now is logged in.
send the requested data from my db to the user because he is logged in
if use fails google validation due to wrong password or G email, jwt isn't created.
Process of JWT
user’s google popup logs in
google server returns information to my server. If the gid isn’t in my db, I’ll save it in my db so that the user can be registered.
create jwt and add uid as content. Exp date.
jwt is sent and stored in local storage of users browser
user requests a page though http, it includes the jwt. my server checks whether this user is logged in or not by Login determination test: if user’s jwt uid is in my DB, user is logged in. the user requested data will be given to the user. If user doesn’t have jwt or uid doesn’t match then the user isn't logged in, send the user to login page.
JWT descriptions
https://medium.com/#rahulgolwalkar/pros-and-cons-in-using-jwt-json-web-tokens-196ac6d41fb4
https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication
https://scotch.io/tutorials/the-anatomy-of-a-json-web-token
https://auth0.com/blog/cookies-vs-tokens-definitive-guide/