Adding JWT to cookie at login using flask security - react-native

Description: I'm trying to set the jwt token at login using
flask_jwt_extended.set_access_cookies and flask_jwt_extended.set_refresh_cookies but the issue is that I cannot set this at the /login endpoint because that is auto created by flask-security. What would be the best way to do this? Would the best way to do this be overriding the /login endpoint and set them there? Or can this be done in the validate method of ExtendedLoginForm even though I would need to add it to a request and not the True or False value that validate requires be returned?
End Result: Use regular cookies (to authenticate) to interact with flask related endpoints. Use JWT tokens (encoded in a cookie) to interact with a react-native compiled code.

My first thought would be to step back - cookies (session) are an easy and secure way to manage all this - why have a JWT that is part of a cookie?
If you really want an Authentication-Token sent with every request - Flask-Security already offers that.
Now - to actually answer your question - You can attach to the "user-authenticated" signal and create your token and cookie there.

Related

fetch httponly cookie persistence through app closures

I am currently using httponly cookie based authentication to authenticate users through a website. On top of this I am creating a react native app which also has to authenticate users, ideally through the same endpoint. At this point users are able to log in through the app and the cookie is correctly send on each subsequent request using credentials: 'include' (fetch). However, if the app is restarted, the cookie does not persist.
So far my searching has led me to the following possible workarounds:
Manage cookies manually by extracting the cookie through something like webview or react-native-cookies, saving the cookie to storage and manually adding it to each subsequent request.
Implement a new endpoint that returns a token and have two authentication flows, one for the website and one for the app.
Have anyone been in a similar situation? Can you point me in the right direction, so not to over complicate my code base and ensure that I am not vulnerable to XSS or other token/cookie theft.
Thanks in advance.
To be honest I never implemented cookie based authentication in react native. How do you handle cookies now ? Basically the flow should be like this:
You authenticate with username and password.
Server will respond with a header "Set-Cookie: sessionIdExample=1234"
Next time when you make a request you should also send that cookie, meaning you have to set a header "Cookie: sessionIdExample=1234"
From your question I guess you don't manually set that cookie, so most probably the http client is doing this for you. Now when you close the app that cookie value is lost as you said. Notice that switching to a token based authentication won't help with this. So what should you do:
Login with username and password.
When you receive that session cookie persist it. You can check async-storage or the more secure react-native-keychain for persisting data.
For the following requests set the session cookie manually.
When you close the app and then open it again, check in your async-storage or keychain if you already have a cookie saved there. If so, set that cookie and everything should work fine.

How to track a user is logged in or not using api?

I am creating api using cakePHP. I have created an api for user log in. This log in functionality is working fine.
Here is the log in function -
public function login(){
if ($this->request->is('post')) {
$user = $this->Auth->identify();
}
}
Now, the I am facing problem is, how I can test from other api that is the user is logged in or not? In web application it can be done by default auth system ($this->Auth->user()). But I am not getting how I can check is this user logged in or not from another api. Do I need to send api parameter to each api request ? or any other suggestion ?
Note : I can't send any token in header. Because in header I am sending jwt token. Because in my application there are two kind of authentication. One is log in or not? and another one is depending some other input from user. That is handling by jwt. So jwt token I am already sending by header. So header is already used.
A couple of things to clarify.
In a regular app, the user logs in with a post request and on successful authentication a session is created. This session is a bit of information that the user supplies in each of the following requests and the server then recognises the user. This accomplished by the Auth component in it's default settings.
In an API you could do the same: the user logs in, receives the session and attaches the session cookie-like object on each following requests. (Example of such a Python client.) However, this is not considered good practice as APIs should be stateless (so without requiring something like cookies). The solution of working with tokens, for instance hashes of some secret token together with a timestamp. The Auth component also supports this pretty well. After setting it up, you can simply call $this->Auth->user(), like you would normally and it returns either false or an array of user information. See link below.
Note that by default this authentication type will block unauthenticated users, so you will never see ->user() return false unless you make pages as public.
See also:
(Cookbook > Authentication > Creating stateless authentication systems)

Social tables authorization and authentication flow

As per the documents received writing down the flow of authorization for version 4.0:
1. call authorize service to get the authorization code back.
2. read the 'code' value for the authorization_code.
3. use this authorization_code to get 'access_token' using '4.0/oauth/token'.
4. for the subsequent calls use 'access_token'.
Please confirm if my understanding above is correct.
My question:
- What will happen when access_token expires? Do we need to go to above flow again?
- the URLs are https does it need certificates?
- what will be the redirect_uri if i want to test in my dev?
I suggest reading a bit about OAuth 2.0 flow. Here's a decent article/example that I would start with from Digital Ocean: https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
But to answer your specific questions:
when the access_token expires you need to make an additional request to Social Tables with the refresh_token -- here's an example: click here. In short, yes you need to use the refresh token to get a new access token which you'll use for subsequent requests
No, you do not need to configure any certificates on your end. These are done via SSL+HTTPS and are ready to go.
The redirect_url for local development can be set to your local running server. You can set it to http://localhost:<port> and that will work just fine.

What does Ember-simple-auth check against?

I have been looking for answer of implementing ember-simple-auth (oauth2-password-grant) for days without luck. I use firebase to sign up users, which is successful. However on the log in page, the action of this.get('session').authenticate('authenticator:oauth2', credentials) seems to cause a json error (SyntaxError: Unexpected token < in JSON at position 0).
So my first question is, in theory, how does this authentication check if the user's email/password is correct? Meaning, in which file is the "answer" located? Am I supposed to define a token? If yes, I already tried "serverTokenEndpoint: 'http://localhost:4200/' or serverTokenEndpoint: 'http://localhost:4200/token" and nothing works. Thanks.
Ember simple auth sends login request to API(in your case Firebase). If entered credentials are valid your API will authenticate user, create and save auth token. Authenticated user with created token will be sent to Ember and token will be saved in local storage by Ember simple auth. Every subsequent request from Ember after login needs to include that token in its header and API will authenticate your request based on that token(comparing token from Ember with the one saved in API).

django rest framework - token authentication logout

I have implemented the Token Authentication according to the django rest framework Docs.
Form what I read, the Token Authentication of DRF is quite simple - one token per user, the token doesn't expire and is valid for use always (am I right?).
I understand that there are better practices out there, but for now the DRF token authentication is fine for me.
my question is- what is the best practice for logout with the normal DRF token authentication?
I mean, when the user logs out, should I delete the token from the client side? and then on login get the token again? should I delete the token and generate a new one?
Anyone with experience with this?
Here's a simple view that I'm using to log out:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
class Logout(APIView):
def get(self, request, format=None):
# simply delete the token to force a login
request.user.auth_token.delete()
return Response(status=status.HTTP_200_OK)
Then add it to your urls.py:
urlpatterns = [
...
url(r'^logout/', Logout.as_view()),
]
WHOLE IDEA OF TOKEN AUTHENTICATION:
Normally in authentication services, there is a lifetime associated with a token. After a specific time, the token will get expired. Here, we get an access token which has an expiry time sent along with it by the server. Now the client needs to send this token everytime in the request header so that the server can identify who the user is. Either we can keep track of when it expires or we can just keep using it until we get an INVALID_TOKEN error. In that case we would have to again get the token from the server.
The lifetime of the access_token is independent of the login session of a user who grants access to a client. OAuth2,lets say, has no concept of a user login or logout, or a session. The token is just used to identify the user if he is who he says he is.
The token is unique for a user and client. You may save it to cookies to enable something like remember me but on the server you don't need to delete it. Whenever the token expires, the client need to send a request to the server to obtain the token again.
Token Expiry in DRF Token Authetication:
Currently, DRF Token authentication does not support this functionality. You would have to implement it yourself or use a third party package which provides this functionality. It should check for token expiry and raise an exception if the token has expired.
To implement it yourself, you can subclass from the DRF Token Authentication class and add your logic.
You can even use a third-party package django-rest-framework-expiring-tokens.
Some References:
1. Token Authentication for RESTful API: should the token be periodically changed?
2. How to Logout of an Application Where I Used OAuth2 To Login With Google?
It sounds like SessionAuthentication is what you are really looking. You can start(login) a session via BasicAuthentication or TokenAuthentication. Then use sessionid as your "token" for the rest of api calls. The "token" expires when you logout or exceed certain timing.
If you run into csrftoken issue using session authentication, this could be a very helpful.