Issuing authenticated queries with Graphcool - authentication

I have successfully set up Graph.cool Auth0 authentication and created a User through Relay as described here.
Next I'd like to actually query graph.cool on behalf of this user. As a first step, I simply manually modified the Relay setup to specify the same auth token as was used to create the User in the first place (through the idToken on type AUTH_PROVIDER_AUTH0):
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer(process.env.GRAPHQL_ENDPOINT, {
headers: {
Authorization: 'Bearer XXX.YYY.ZZZ',
},
})
);
However, the app stops rendering and I just get a console warning RelayPendingQueryTracker.js:153 Server response was missing for query Index. Any hints?

When calling the signinUser or createUser mutation, a Graphcool token is returned in the payload. https://www.graph.cool/docs/faq/graphcool-session-user-goij0cooqu
This is the token you need to use in the Authorization header instead of the Auth0 idToken.
Maybe it can also be a help to take a look at how we do it in the dashboard https://github.com/graphcool/dashboard/blob/master/src/views/LoginView/LoginView.tsx
Hope this helps!

Related

How to get a new access token via refresh token using Expo Auth Session?

I'm using Google for auth (expo-auth-session/providers/google)
I can successfully login for the first time and fetch an access token and a refresh token. The refresh token will get stored in SecureStorage.
Now at this point, when the old access token is invalidated, I need to use the refresh token to get a new access token, but Expo's docs don't really provide any guidance on this part. I have checked their API quite thoroughly, but can't see anything that helps me retrieve a new access token with a refresh token.
Any guidance would be welcome.
The AuthSession library has a method specifically for refreshing tokens. It requires the clientId used to retrieve the token initially, so you can reuse that, the refreshToken which you have stored as well as a token endpoint.
const tokenResult = await AuthSession.refreshAsync({
clientId: "<your-client-id>>",
refreshToken: "<your-refresh-token>",
}, {
tokenEndpoint: "www.googleapis.com/oauth2/v4/token",
},
);
I wasn't able to test this myself as we use firebase and useIdTokenAuthRequest as a result, so I wasn't able to get my hands on a refreshToken to run it through that function - but the documentation of that method seems pretty solid.

best practices for refreshing access tokens automatically

I'm building a react native app which uses the spotify web api. I'm using the authorization code flow to authorize a user. First I get a authorization code which can be used to obtain an access token and a refresh token. Everything works!
The problem is: an access token is only valid for a limited amount of time. That's where the refresh token comes in. I understand this concept, but I'm breaking my head about how to implement this.
Let's say a users opens the app, requests an access token and uses this for some time. Then, the user closes the app. After 15 minutes, the users opens the app again. The access token has now expired, so I need to request a new access token.
I've come op with several "solutions". Can someone point me to the correct solution?
Solution 1:
Every time the user opens the app, I request a new access token and use this. Problem: when the user uses the app longer than the valid time of the access token, I won't work anymore.
Solution 2:
I use the access token that's stored in the secure storage on every request. When a request comes back with 'access token invalid' (I don't know the exact error code but you guys know what I mean), I request a new access token with the stored refresh token, and then I send the previous command again (with the new access token). But my question here is: can I use some kind of "wrapper function" which checks the response of the request, and if the response is "access token invalid", it automatically requests a new access token and runs the previous request again.
I think certainly correct solution is solution 2,and i think its clear enough.
and for using solution 2 you need somthing like wrapper function,yes its intelligently.
so you should use interceptor:
what is interceptor ?
You can intercept requests or responses before they are handled by then or catch.
in link below there is a good example of implementing refresh token in axios interceptor:
https://gist.github.com/Godofbrowser/bf118322301af3fc334437c683887c5f
I agree that Solution 2 is the best, each time you do a request you can check to see if the Access Token has expired, and if it has then you can request a new Access Token using the Refresh Token as you mentioned and then make your request, in my own project I do this in a FormatRequestHeadersAsync method which calls a CheckAndRenewTokenAsync method where I perform the following check, here shown in C#:
if(AccessToken?.Refresh != null && (AccessToken.Expiration < DateTime.UtcNow))
{
AccessToken = await GetRefreshTokenAsync(
AccessToken.Refresh,
AccessToken.TokenType,
cancellationToken);
}
You can store the Access Token and the Refresh Token and then use something similar to this before you make each request to the API this will refresh your token and then you can store the new Access Token and the existing Refresh Token.

best practices for authentication in react native

I'm a beginner in react native and I'm creating an app. I've done some research about how to make a secured react native app, but I didn't found much information. I've come up with a "solution" myself, but I want to make sure this is the right way to do this. So I need the help of some react native/javascript/security experts if possible, to quickly check if my approach is OK or not?
I have included 3 questions in this text, but obviously they're related. I've put them in bold. Feel free to answer one or more questions, I appreciate every answer!
I'm creating an app in react native. For a user to be able to use the app, the user should create an account and sign in. I'm using an JSON web token as an access token to authorize the requests made from the app to the server, and to identify the user (I store the user ID in the JSON web token).
At my server, I first check if the access token is valid. If so, I get the user ID out of the access token and use this user ID to identify the user.
For extra security, I'm also using refresh tokens, because an access token is only valid for 10 minutes. When a user send a request with an expired access token, the server responds with a 401 not authorized status.
To make my code more "managable", I've created a wrapper function in react native. I wrap every "request function" (every function where I do a GET/POST/PUT/DELETE request to the server) with this wrapper function. This wrapper function checks the response of the request. If the response status is 200, the response is returned to the code. If the response status is 401, the refresh token is send to a specific endpoint to obtain a new access token. When the access token arrives at the app, the previous request is made again with the new access token. The wrapper function also stores the new access token in (temporary) redux (keychain or shared preferences). 1. Is a wrapper function a good idea? For me, it's more manageble because now I'm reusing the code.
Every time the user opens the app, a new access token is requested, and when a user closes the app, the current access token is deleted, even if it is not expired yet. That way, I want to make sure that every app "session" starts with a new access token. 2. Is this okay? Or should I prevent unnecessary requests to the server when I still have a (possibly) valid access token?
In my react native app, this wrapper function is located in a context component. This "authentication" context is wrapper around my other components in App.js like this:
<AuthenticationProvider>
<AppNavigator />
</AuthenticationProvider>
This way, my wrapper function is accessible to all my other components. My authentication context looks like this:
const AuthenticationContext = createContext({
accessToken: null,
wrapperFunction: () => {}
})
const AuthenticationProvider = (props) => {
let accessToken = null
const refreshToken = useSelector(state => state.auth.refreshToken)
const wrapperFunction = () => {
// wrapper function
// set the access token
// await fetch('server endpoint')...
}
return (
<AuthenticationContext.Provider value={{ accessToken, wrapperFunction }}>
{props.children}
</AuthenticationContext.Provider>
)
}
3. Is using a context a good practice to do stuff like this?
Server-side, I store every refresh token in a database. When a user requests a new access token, I check if the sent request token still exists in the database. If not, I have revoked access for this user and the user should be logged out. This way, I want to make sure I can "manage" users.
Yes, it makes sense. Actually I can't think of a better way to manage the scenario you mentioned. When you wanna temper the request before it's sent, you will need a single function to do so. You could also use some hooks e.g. onBeforeSend and onAfterReceive, but in your case I don't see any extra value for this.
I do not agree with the deletion of a valid token. You can still send request to server on every app start to get user's last data -might have changed on another device-. I don't understand the logic of starting the app with a new session -maybe more information?
I don't think you need to pass the wrapperFunction/token using context. It would be best if you could send user data by context. you wrapper function can access the token directly from asyncStorage. And each component can call the function directly by importing it.
I believe you are taking the approach of using a wrapper function since the relevant API requests are made directly in components. The best practice is to move such requests outside (E.g. Redux actions with a middleware like redux-thunk) the components.
It's better to check if the access token is expired (by decoding the token) before sending the API request and retrieve the new access token. This will reduce the amount of requests to server. You can implement a common request method which handle this check as well.
I think since your access token expires every 10 mins this is unnecessary. Is there a specific reason to start each session with a new access token?
You can pass in user access details using the context. I think it's matter of preference. Passing in the wrapper function is not needed if you're handing the requests through a common request method.

Spotify API scopes not being recognized - not able to access user info

I am currently implementing a feature that you have the ability to save a song displayed on my iOS application (written with Swift) and this save button allows the song to be appended to the user's Spotify library. According to the Spotify Developer guide, the only scope required for this feature is user-library-modify when authorizing the app with the user. The url to be opened goes like this:
https://accounts.spotify.com/authorize/?client_id=my_client_id&response_type=code&scope=user-library-modify&redirect_uri=http://my_redirect_uri
This all works perfectly - the url is opened for the user to approve of the changes my app can make and the callback url with the required code is in the url is opened.
The next step in performing the required function is to get an exact token in order to use the api, which is done by calling the url:
https://accounts.spotify.com/api/token?grant_type=client_credentials&client_id=my_client_id&client_secret=my_client_secret&response_type=code&redirect_uri=http://my_redirect_uri&code=the_code_I_just_retrieved
With this url, a json file is returned with the new token and info with it, BUT when looking at the permitted scopes the token has, it is empty:
["scope": , "token_type": Bearer, "access_token": the_token_string, "expires_in": 3600]
Also, when I still try to perform the request it returns:
["error": {
message = "Insufficient client scope";
status = 403;
}]
In this lengthy process, what am I doing wrong? In case you are wondering, here are a few things I have tried without success:
1) Re-listing the scopes in the explicit token request
2)Adding utf-8 encoding to the redirect uri (not sure if this changes anything)
3)Adding many other scopes (although this clearly does not target the problem)
If anyone knows what I am doing wrong or has any suggestions as to what I should try, I am grateful for any helpful response!
I have found my mistake. The grant_type I have entered in my url set to client_credentials. However, this method of accessing the web API only permits the usage of publicly available data, not user info. Therefore, this method of authorization does not accept the parameter scope, forcing the spotify account service to ingnore this additional parameter. The other options DO allow accessing the user data, which are:
authorization_code, and refresh_token
The way this now has to be done is to:
1) Authorize the user regularly (with supplying the scopes) to retrieve the initial authorization code
2) Then, with this code, make the token request, but specifying the grant_type to be set as authorization_code
3) You have then received a valid access_token valid for one hour AND a refresh_token
4) Use the access_token when necessary and when this token expires, make another token request, but this time with the grant_type set as refresh_token and setting the code parameter to the previously gained refresh_token
5) You now have the next access_token and refresh_token
6) Repeat steps 4-5 until infinity

MVC 5 Web API Login without Bearer Token

Long story short. I have a login form in the header on every single page, when I log in successfully it works fine but when the user is incorrect for example it redirects to the default login page (a view that was originally created with MVC project) with the model errors. I don't want to do that, I want to show errors next to the login form without redirecting. So I decided to implement a login via WEB API - i.e. it does $.ajax jQuery request to the Login API Controller, tries to log user in and returns errors if needed so I can output them where I want.
All examples I've seen say to use Bearer Access Token. I don't understand why would I need to go this path - save the token somewhere and pass it along with every single request in the headers? That's what I did in my Login API Controller:
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
}
else
{
error = "Invalid username or password.";
}
This is the same functionality that is available out of the box when you create MVC5 project. I just moved it from regular controller to API controller. And it works without needing to take care of some bearer access tokens. What's the point of it if you could just do it like I did? I think it just makes requests more complicated when you use bearer token. Am I missing anything?
As I understand this, the bearer token would make more sense when you need to have a separately available backend authenticated with the same login as the front end we site in a pass through so the back end can "see" the request as coming from the same user.
You can verify that after logging in this way both the front end web site and backend api are sending the same session cookie, and if so you are golden. If on different domains, you may have problems with that, but otherwise not. If so, then a bearer token to pass that user to the backend may come back into play.