Authentication on Instagram to get the access_token using the API - authentication

I'm using the Instagram API and want to get the access_token in order to throw api requests over my own account. When I try to follow the first step and get the authorization code programmatically using RestTemplate I can't get it work.
String AUTHORIZE_URL = "https://api.instagram.com/oauth/authorize/?client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&response_type=code";
String url = String.format(AUTHORIZE_URL, clientId, redirectUri);
String o = restTemplate.getForObject(url, String.class);
The response is the html code of the login page because Instagram requires the user to be logged in to check if the app is authorized (of course it is, since the app an the user belongs to my own account).
How can I authenticate before throwing that request so they return the code to my redirectUri and not complain about login?
Note: I tried simulating the request to their login form but it returned a 403 Forbidden.
NOTE: I already got a valid access_token, manually generated, and it works perfectly but I want to implement also a process to re-generate a new access_token automatically since they may invalidate it at any time in the future.
Even though our access tokens do not specify an expiration time, your app should handle the case that either the user revokes access, or Instagram expires the token after some period of time. If the token is no longer valid, API responses will contain an “error_type=OAuthAccessTokenError”. In this case you will need to re-authenticate the user to obtain a new valid token.
In other words: do not assume your access_token is valid forever.

Instagram is upgrading their APIs and the flows. Earlier we needed access token to bypass forced login screen. Since yesterday, they have removed that.
Now if you call this code, it will check if you are already logged in or not. If so, it will call the AUTHORIZE_URL of yours and will send a response code. The format will be either:
On success validation - http://your-redirect-uri?code=CODE
On error - http://your-redirect-uri?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request
Now what I'm doing is I'm directly calling the above URL of yours every time. Now if the user is logged in, a response code will be sent to you, else user will be asked to login and validate your app and then the code will be sent. Technically, you are eliminating the possibility of the error case! So no need of overhead of storing access token in your database or verifying its validity.
Just try and check now what happens.
PS: If you want to check API behavior, simply type the URL on the browser and check what it returns! It helped me a lot while coding and debugging! :)

Related

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.

Amplify federated saml sign in not authenticated

So I'm not quite understanding why this isn't working. Some background; We have a SAML identity provider in our user pool, its a registered identity in our identity pool as well which i see when i go to dashboard. I am pretty frustrated form the lack of central documentation for Amplify, it's incredibly difficult to find anything online and I just keep trying things I see and they don't work.
What I already have:
I already have it working in the sense that I get an access_token back from the SAML provider, and that all works fine. So I know it's working fine (the login part), but the issue I am having is basically updating Amplify to now have the user in session so we can take advantage of functionality within Amplify that lets you refresh tokens when they expire.
Essentially, this is the flow I am using, from different sources I've found online:
await Auth.federatedSignIn({ provider });
this line of code can either be google, facebook or our custom SAML one we made. I already know this works, bc again, I already get my access token. So now, this is where my confusion starts. Obviously this function call here will take the user away from the page, hence we cant await this call, or i mean, you can, but it wont return the user on page reload. Which is fine, that part makes sense. So I have a function when the component is loaded that checks to see if theres a access_token in the url hash, which works as well.
Now, the issue is, Amplify doesn't know we signed in. We have "logged in" in the sense that yes, we have a valid JWT token now from the url hash access_token but the local Amplify does not know that this user is logged in.
So this is what I am talking about with the lack of documentation, perhaps I am crazy but I can't find a central source for how to handle this anywhere. I figured, once we have an id_token perhaps we can take advantage of Amplify Auth's federatedSignIn but now instead of just passing in a provider, they do have an option to send in a provider name, an id token, and expiree time and a user object, as noted here
As you can see there's different ways you can use this function, so I figure now that I have the id_token back from the response, I can use this method to actually tell Amplify that yes I am indeed logged in. As such:
await Auth.federatedSignIn(
provider_name,
{
token: id_token,
expires_at: expires_in,
},
user
)
When this fires I get the following error:
issue with access token NotAuthorizedException: Invalid login token. Issuer doesn't match providerName
Now I have verified 100% that the providerName is correct. This is the SAME provider name we pass in the original federatedSignIn call. the id_token is also the jwt id_token we get back from the Cognito and the SSO provider. the expiree is also 3600 so im assuming thats valid, and if it wasnt, the error would be different. I am just lost as to what I need to do at this point.
How can I have amplify recognize a federated sign in user? Since all we get back is a access_token and im beginning to think im not using the federatedSignIn method properly.

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

How to handle expired auth tokens in Xamarin MobileServiceClient?

I am using client-flow authentication in Xamarin.Forms and am trying to figure out how to handle when an authentication token expires.
My Code:
Upon initial login, the user logs in with the native Facebook SDK and I pass the access_token to MobileServiceClient to get back an authenticated user.
var user = await client.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token).ConfigureAwait(false);
I then save the user's UserId and MobileServiceAuthenticationToken in local settings (using the Xam.Plugins.Settings plugin).
The next time the user opens the app, I set the user from settings and skip manual login:
if (!string.IsNullOrWhiteSpace(Settings.AuthToken) && !string.IsNullOrWhiteSpace(Settings.UserId))
{
client.CurrentUser = new MobileServiceUser(Settings.UserId);
client.CurrentUser.MobileServiceAuthenticationToken = Settings.AuthToken;
}
My Question:
This works great. However, I know that the MobileServiceAuthenticationToken has an expiration on it. What will happen in my app when the expiration date is reached? How do I refresh the token without requiring the user to re-log-in to Facebook? I have tried the MobileServiceClient's RefreshUserAsync() method, but I get the following exception:
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: Refresh failed with a 400 Bad Request error. The identity provider does not support refresh, or the user is not logged in with sufficient permission.
Is there a way to test this? (since the token expiration is 3 months from now.) Thanks for the help!
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: Refresh failed with a 400 Bad Request error. The identity provider does not support refresh, or the user is not logged in with sufficient permission.
Since you are using client-flow authentication, you could not use RefreshUserAsync() for refreshing the MobileServiceAuthenticationToken. Your mobile backend does not cache the related access_token and refresh_token for renewing the authentication Token.
Is there a way to test this? (since the token expiration is 3 months from now.) Thanks for the help!
AFAIK, the MobileServiceAuthenticationToken expiration is one hour by default, you could use https://jwt.io/ to decode your token and check the exp property, then use https://www.epochconverter.com/ to convert your timestamp to human date.
For your requirement, you could follow adrian hall's blog about Caching Tokens and refer to the IsTokenExpired method for decode your authenticationToken and check the exp, then manually renew the authenticationToken.
Per my understanding, there are two approaches for you to achieve your purpose:
You need to cache the facebook access_token in your mobile client side, after you manually checked the authenticationToken and found that it expired, then you could manually execute the following code for renewing the token and explicitly update your local cache.
var user = await client.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token).ConfigureAwait(false);
Note: Your facebook access_token has the Expiration Date, so if your access_token expired, then you need to force the user to log into Facebook again before acquiring the new authenticationToken.
Or you could build your custom endpoint for refreshing the authenticationToken and explicitly set a long lifetime for your new authenticationToken, details you could follow this similar issue. Note: For your client-side expiration processing, you need to renew the token before your local authenticationToken is about to expire.

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).