In flask-security-too, can a passwordless login token expire after first use? - authentication

We've been using password-less login feature from flask-security for some time but we now discovered that login link can actually be used multiple times which is not ideal security-wise. I've spent some time reading through https://flask-security-too.readthedocs.io/en/stable/configuration.html trying to find a setting which would make login token invalid after first use but I only came across SECURITY_LOGIN_WITHIN option that sets the token's lifetime. What I would like would be:
token made invalid once used
token expired if not used within ..
Does flask-security provide such a config?

You are correct - these tokens aren't one-time - but they are timed - so the token will expire if not used after SECURITY_LOGIN_WITHIN seconds (which is your second ask).
The newish feature - unified_signin provides a more flexible way of providing authentication - including email links (like passwordless) or one-time codes, SMS, authenticator app.
In unified_signin - all the codes are generated using passlibs TOTP - which are ALSO timed tokens - not truly one time. However - as documented here: https://flask-security-too.readthedocs.io/en/stable/api.html#flask_security.Totp
you can implement the recommended counter persistence to ensure one-time use/no replays.

app.config['SECURITY_LOGIN_WITHIN'] = "10 minutes"
is a good value.
If the link has expired, a new message is sent (flask-security-too)

Related

Is it bad practise to automatically use the refresh token in an interval?

As I am working on implementing a proper auth flow into a react web app, I am presented with different patterns of how to use access and refresh tokens.
I am considering the following two patterns:
Creating some sort of middleware to the fetch API:
This middleware runs before every request to the backend and checks whether the access token is still valid or not.
If it is invalid, it first calls the auth server to fetch a new access (and refresh) token.
Creating an interval which is independent from all other logic to keep the access token alive.
Say if the access token is valid for 5 minutes, the interval will run every 5 minutes to fetch a new access token
I would also make sure it only runs every five minutes, if the user is still active , so that the application left open without any user interaction for a long time will automatically log out
Any API call simply uses the currently active access token and does not need to worry about checking the token first or anything
The second approach seems much much easier and cleaner to implement for me, since it does not add any complexity to fetching data and is completely independent/seperate to the app otherwise.
I've been having a hard time to research this question though tbh. I'm not sure if there is some security issue I'm missing with that approach.
So my questions are:
Is there any security issue with fetching a new access token in an interval from the clients side?
Is there a common practise on how SPA apps (like the react app I mentioned) handle access tokens?
If yes, what is that common practise?
If there is no security issue, are there other cons of the second approach that I am missing out on?
Thank you for your answers in advance!
I think the answer depends, if you always do it every X minutes, and you have many active clients, it might create more load on the backend, compared do doing it on a need basis. Perhaps all clients are not so active all the time?
One thing to look out for is to make sure you don't trigger multiple requests at the same time to request new refresh tokens. If you get a race condition here, then you might be logged out (if you use one-time refresh tokens)
Also it is worth considering to use the BFF pattern, do watch this video
Using the BFF pattern to secure SPA and Blazor Applications - Dominick Baier - NDC Oslo 2021

How to set the expiry time of an applications token to -1 for WSO2 APIM 2.1.0?

I have tried creating a new application and setting the expiry time to -1 on the UI for the store which looks like it worked based on what I saw on the UI. However when I tried a curl to get a token it defaulted to 3600 seconds still.
I then looked into it and found another way in which I can edit the identity.xml default to be -1 and restart WSO2. Apparently that is supposed to change it for all new applications and leave existing ones as is. So I did that and created a second new application. Again the UI looked like it was working but when I did the curl for the token it was still 3600 seconds.
Please could someone tell me if I am missing something or have done something wrong. I need to create just one application that has a token that never expires ( or at least lasts an extremely long time )
Thanks
When generating the Token from the Store UI, the API Manager uses the Client Credentials grant to generate the Access Tokens (explicitly passing the validity period).
As per the shared comment, you are trying to generate an access token using the Password Grant. In such a scenario, we can perform the following configurations (Doc) to generate the User access token with an infinite lifetime
Configure the identity.xml to configure newly created applications with an infinite token span
As you have already performed, update the UserAccessTokenDefaultValidityPeriod value in the <apim>/repository/conf/identity/identity.xml with larger values (example: 9223372036854775) to generate a long-lasting token
<UserAccessTokenDefaultValidityPeriod>9223372036854775</UserAccessTokenDefaultValidityPeriod>
Once the configurations are made, please do restart the API Manager node to take effect on the changes and try the scenario again with the Password Grant with a new Application
Hope this helps to achieve your requirement

Alternate approaches to token based authentication

I have a RESTful API which will be users will reach via a set of web/mobile clients, and I am trying to figure out how to handle token auth. My understanding is that traditional token auth works as follows:
User auths by providing user/pass, receives back a token and expiration
Until , token is passed with every request
Upon expiration, a new token is requested (either by providing a separate 'refresh' token or just by re-authenticating with user/pass)
Is there a good reason not to generate a new token with each request? That is: an initial token is requested via user/pass. This token is passed with the first API request, which returns the content of the api response plus a new token which must be passed with the following request... The advantage to this approach would be that each request (action) the user takes 'resets' the expiration of the token auth such that the token expiration time basically becomes the period of time the user can be inactive without being logged out. Is there a good reason not to use this approach? The approach laid out above seems more commonplace (which is why I ask).
Finally, one only slightly related question. What stops someone who is watching the network from grabbing the token from the user? In particular in the first scheme, it seems easy to do (in the second method, you would need to capture the incoming request and then quickly get the next token before the user does).
From what I read is that you want a sliding window in which a user is authenticated. Every new request within the expiry window prolongs the session.
If I understand that correctly I would suggest an alternate approach; every time a request is successfully authenticated update your store in which you have your tokens and update the expiration time.
This way you don't have to bother your users with all the hassle of grabbing the new token every single time.
So, yes, there's a good reason not to do that: it's not necessary for your use case and only annoys the user.
With the above approach I assume that you have a store (database) in which you keep your tokens + an expiration date.
So the process is this:
The user provides username + password
Create record in store
Give user the token
Update store every time a successful request is made
On a related note; don't give the users the expiration date. That's fine when using cookies for example but that is merely useful as an additional security measure.
On your slightly related question; nothing stops anyone from grabbing the token if you don't use TLS/SSL/HTTPS. Always use TLS (which is SSL, which is HTTPS, more or less).

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

how to use and store token from oauth2 to do authentication

sorry if this is question is too broad, but I have to ask this since I'm learning web development and I feel if don't ask I won't know.
So, I'm doing authentication using oauth2, and right now I'm already at point where I successfully authenticate user, and now I'm receiving what they call tokens. The question is, how do you use token to authenticate user to your own server?
I'm thinking something like creating a cookie that maps to a token, so when user acts, each time I'll get a cookie and I know that this is user A. Is method like this safe or not? If not, in what way people usually use the token? Although this is only a hobby project, I'd like to be "as real as possible". Any thoughts?
As per my knowledge Oauth2.0 provides InMemoryTokenStore and JdbcTokenStore for persisting tokens. When a request comes from an authenticated user Oauth2.0 will check if it has a valid token already. In case it doesn't it will create one.
Basically usage of tokens depends on the grant-type you are using . Following are the two commonly used grant types -
1) Implicit - The token is send back in the url as a parameter and is included in the subsequent request* in the parameter.
2) Authorization Code - In this case the token is generated and set in the header of the request*.
*the request here is the one which is finally sent to resource server for accessing protected resources.
I think you dont need to create a cookie for storing tokens. In case you are using Authoziation Code grant type which is the default, Oauth2.0 will use session for storing state and code which will be used for retrieving token.