Spotify API: How to get access token for only myself - spotify

I'm following this tutorial to get the track list from my Discover Weekly playlist. The tutorial mentions that I need to get an OAuth token for my own account before requesting the playlist info. This is done by going to a random Console page and click on 'Get token' at the end of the page (which requires me to log into my Spotify account and approves the Console to access my account data).
However, I want to acquire this token programmatically, instead of manually clicking on 'Get token' and logging into my account every time I need this token. What I have is:
My Spotify user ID (from my Account page)
The Spotify client ID for an application I just created under Spotify for Developers
The client secret for this application
Basic knowledge of how to send GET and POST requests (using Python's requests library)
How can I get an OAuth token, or at least generate a new token each time, using some of these above
information?

It depends on what you're trying to do. If all you want is a token to query the api to lookup songs/artists/etc., then you can use the Client Credentials auth flow that doesn't require any user input. All you need to do here is exchange your client ID and secret for an access_token that you'll use in subsequent requests.
If you want access or change certain user information, you'll have to use one of the two other flows on the same spotify authorization page. You'll need to pass a list of scopes with this request, directing the user to a spotify-url-based authorization page, and be able to give it a redirect url that will handle the receiving of the access_token object once the user logs in to the spotify page.
I don't think there's a way to implement one of these flows where you need to request user scopes without having some sort of web server running to accept the redirect passed into the spotify auth url and then save the given token.
After looking at the link you posted for spotify's console pages, it looks like you can use any of those API requests to generate a token including the scopes you want. All it's doing is performing the normal authorization flow in the background, skipping the step where it returns a secret to you that your server that you can then exchange for an access_token and refresh_token. Using the spotify console pages seems like an easy quick way to get scripts or prototypes running without having to deal with setting up your own webserver.

Related

Google API Authentication Tasks API

I want to create a Lambda function that uses the Google Tasks API to add tasks every evening at a certain time.
I am unsure of how to authenticate with my account and be able to store access tokens / credentials securely in my lambda environment variables.
As I understand it since my lambda is making a request on behalf of a user (which will always be me in this case) it seems like everything in the docs points to needing to use OAuth2.0 to authenticate which makes sense since you'd want the user's permission to make changes in their account. However since I only want to do so on my account, I wanted to know if there was a way to simply authorize my account without doing a OAuth flow which I don't believe is possible from a lambda since I won't be responding to it every time it runs.
How would I authenticate my application so I can make calls to the tasks API and be authenticated against my account?
This is surprisingly more work than I'd imagined and unfortunately google doesn't generate developer tokens which would have solved a lot of this problem.
Authorization & Consent
There are no immediate ways of authorizing your account for the app that you've created without going through the consent flow. Some cloud service providers generate a developer token for testing your app with your credentials - but google doesn't seem to have this functionality. Not for the Tasks API anyways. AdWords API talks about a developer token but I'm not sure if it's the same concept.
You won't have to re-authorize once you've given consent. This general principal applies to other OAuth using parties, unless the level of consent changes (example: the app starts asking for write permissions in addition to previously consented read) you won't get re-prompted. If permission levels change, you'll get re-prompted.
Now - the second part - how do you make one?
Google explains it in detail here - but I'll further simplify because you don't need to setup a web-server for your case, you're only doing this for yourself.
Our goal is to only to get you the initial refresh token. Once you've retrieved the refresh token, you can use that from your Lambda to retrieve a new access + refresh token whenever you're accessing the tasks API. You just need to keep the refresh token stored somewhere, so you can continuously keep on accessing the tasks API. You're just looking to get the access + refresh token.
Head over to https://console.developers.google.com and create a new application.
After the creation, click 'Enable APIs and Services' and look for Tasks API.
Proceed with creating the credentials and make sure you select you'll be calling this API from a Web Server. Selecting Browser (JavaScript) would only give you an access token and not a refresh token, because they would trust you to store the refresh token on your server, but not on a browser. An access token is time-limited to (conventionally) 60 minutes.
You should also select the User Data / Information and not the App Data / Information for the types of data you want to access. The app one is generally used for GSuite.
Set your redirect uri to be http://localhost:8080 - This is where you normally would need a web-server but we'll just redirect back to your machine and get the parameter from here. It obviously won't find a web-server but the parameter we want is in the url, we'll just copy it.
Now here comes the authentication part. Google's auth url is: https://accounts.google.com/o/oauth2/v2/auth
We will add parameters to this url
access_type=offline // so your daemon app can access it offline
response_type=code // required if you have access_type=offline
scope=https://www.googleapis.com/auth/tasks // what do you want to access to
redirect_uri=http://localhost:8080 // where would google send the code
client_id=
so the whole thing should look like https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&scope=https://www.googleapis.com/auth/tasks&redirect_uri=http://localhost:8080&client_id=
Go to this URL and you should get prompted for consent.
Consent to it and google should redirect you to http://localhost:8080/?code= We'll need that code. That needs to be sent to google to get an access + refresh token.
Code exchange: Make a post request to Google. You can use PostMan. Again normally all of this would be automatically handled by a webserver (detect code parameter, make post request etc..) - but we just need the refresh token here, so we can stick that into our Lambda app.
POST to:
https://www.googleapis.com/oauth2/v4/token
with parameters:
code=<the code you've retrieved>
client_id=<your_client_id>&
client_secret=<your_client_secret>&
redirect_uri=http://localhost:8080&
grant_type=authorization_code
Google should return you the access token and the refresh token. From this point on you need to save the refresh token into your Lambda app - and if it's running on a scheduled job on every bootup:
Read the refresh token
Call Google for a new refresh token + access token
Save the new refresh token.
Use the access token to access your Tasks API.

Instagram Feed Jquery Plugin

I would like to add your Instagram feed to my website. I post pictures on Instagram here. How Can I do this. https://www.instagram.com/developer/clients/manage/ at this address, a new client I have created. I'm doing but something is missing. I couldn't do with Instafeed.
i guess u stuck with the place about access token.. u should approve Client-Side (Implicit) Authentication..
If you are building an app that does not have a server component (a purely javascript app, for instance), you will notice that it is impossible to complete step three above to receive your access_token without also having to store the secret on the client. You should never pass or store your client_id secret onto a client. For these situations there is the Implicit Authentication Flow.
Step One: Direct your user to our authorization URL
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
At this point, we present the user with a login screen and then a confirmation screen where they grant your app’s access to their Instagram data. Note that unlike the explicit flow the response type here is “token”.
Step Two: Receive the access_token via the URL fragment
Once the user has authenticated and then authorized your application, Instagram redirects them to your redirect_uri with the access_token in the url fragment. It will look like this:
http://your-redirect-uri#access_token=ACCESS-TOKEN
Simply grab the access_token off the URL fragment and you’re good to go. If the user chooses not to authorize your application, you’ll receive the same error response as in the explicit flow

Authentication with React Native and API backend

I'm trying to wrap my head around oauth with a React Native app and a separate NodeJS/Express API backend. I understand https://github.com/adamjmcgrath/react-native-simple-auth offers authentication for a React Native app and http://passportjs.org/ offers authentication for a NodeJS backend. I'm unsure how to connect these two for authentication for login and access to the API.
I'd like users to login to the React Native app either by email and password or via Facebook/Twitter/Google. Once logged into the app, what do I send to the API to make sure they are authenticated and have access to a specific route?
Here is an example flow to login and see the logged-in user's settings:
User logs into React Native app via email/password or Facebook/Twitter/Google.
User is authenticated
App makes request to GET /api/settings
API verifies user is authenticated and returns that user's settings or API verifies user is not authenticated and returns a 403.
There's a whole lot to this question, so much so that it wouldn't all fit in a single SO answer, but here's some tips and a general outline that should broadly fit into what you want to accomplish.
OAuth2 Authorization
From the sounds of it, you are interested in using OAuth 2 to provide social login authorization, and would like to do first-party authentication as an alternative with an email and password. For social logins you will end up using the OAuth 2 Implicit flow to retrieve an access token, which is a widely recognized pattern. Because you are also looking to authenticate users with an email and password, you may want to familiarize yourself with OpenID Connect, which is an extension of OAuth 2 and which explicitly supports authentication in addition to authorization.
In either case, once your user has either submitted an email/password combo or granted permission through the social identity providers, you will receive in response an access token and (optionally) an ID token. The tokens, likely a JWT (JSON Web Token, see jwt.io) will come across as a base64 encoded string that you can decode to inspect the results of the JWT, which will include things like the ID of the user and other details like email address, name, etc.
For more info on the different types of flows, see this excellent overview on Digital Ocean.
Using Tokens for API Authentication
Now that you have an access token, you can pass it along with all requests to your API to demonstrate that you have properly authenticated. You'll do this by passing along the access token in your HTTP headers, specifically the Authorization header, prefacing your base64-encoded access token (what you originally received in response to your authorization request) with Bearer . So the header looks something like this:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJh...
On your API's side, you will receive that token, decode it, and then verify the ID and claims in it. Passed as part of the token in the sub property will be the subject, or ID of the user making the request. This is how you identify access and start to do things on your API side with the respective user's rights, perms, etc. It is also important that you validate the access token once you receive it on your API side, to ensure it wasn't spoofed or hand-crafted.
How it looks in RN for Implicit flows
Here's what the general process looks like in React Native for OAuth 2 Implicit flows, which is what you'll use for social identity providers:
User taps one of your social login buttons on React Native UI
Your code that responds to the buttons will build a request URL to those providers, depending on what each wants (because it differs slightly).
Using the Linking API in RN, you will open up that URL in a browser on the device which sends the user off to the social provider for them to do the login/authorization dance.
Once complete, the social provider will redirect the user to a URL you provider. On a mobile device, you will use your own custom URL scheme to move the user from the web view to your app. This scheme is something you register as part of your app, such as my-awesome-app://, and the redirect URL you pass to the social provider could look like my-awesome-app://auth_complete/. See the Linking API docs for how to configure these URL schemes and deep linking.
In the handler for that new URL scheme/deep link, you'll get the tokens passed as part of the URL. Either by hand or using a library, parse out the tokens from the URL and store them in your app. It's at this point that you can start inspecting them as JWTs, and pass them along in the HTTP headers for API access.
How it looks in RN for Resource Owner Password Grant flows
You have the option for your email/password combo for your own accounts of either sticking with the Implicit flow, or switching to the Resource Owner Password Grant flow if your API and app are trusted by each other, meaning that you are making both the app and the API. I prefer the ROPG flow on mobile apps where possible because the UX is much nicer--you don't have to open up a separate web view, you just have them type in their email and password into UI elements directly in the app. So that being said, here's what it looks like:
User taps the email/password combo login button, and RN responds with a UI that includes TextInputs for the email and password
Build a POST request to your authorization server (which may be your API, or may be a separate server) that includes the properly crafted URL and body details that passes along the email and password. Fire this request.
The auth server will respond with the associated tokens in the response body. At this point you can do the same thing previously done in step 5 above, where you store the tokens for later use in API requests and inspect them for relevant user information.
As you can see, the ROPG is more straightforward, but should only be used in highly trusted scenarios.
At the API
On the API side, you inspect for the token in the Authorization header, and as mentioned previously, and if found you assume that the user has been authenticated. It is still good security practice to valid and verify the token and user permissions. If there is no token sent with the request, or if the token sent has expired, then you reject the request.
There's certainly a ton to it, but that provides a general outline.

Spotify API Authorization for cron job

I'm creating a node.js application that will update playlists (owned by an account in which I have credentials) daily. According to the Spotify documentation, to add tracks to a playlist (https://developer.spotify.com/web-api/add-tracks-to-playlist/), authorization must be supplied using oauth2.
I'm struggling to find a way to do this completely server side with no redirects/etc. It seems like if I can get a refresh token, I can just use that?
I've been looking at the spotify web api node module (https://github.com/thelinmichael/spotify-web-api-node), oauth.io, and the spotify api.
Any ideas would be appreciated! There is only one account that will have to be authenticated, so it could be hard-coded at least for now.
You've picked the correct authorization flow - Authorization Code, since you need an access token that's connected to the user who owns the playlists you're updating. This of course also gives you the ability to refresh the token whenever you need to. (The expiration time is one hour, but you don't need to refresh the access token until your application actually needs to use it.)
As a sidenote, the Client Credentials flow is meant for server to server communication that doesn't require a user's permission, e.g. to search, read a playlist, or retrieve new releases. The Implicit Grant flow is meant to be used in frontends, and doesn't allow you to refresh the token.
I'm struggling to find a way to do this completely server side with no redirects/etc. It seems like if I can get a refresh token, I can just use that?
Once you have the refresh token you can continue to use it to retrieve new access tokens, which can be done without any user interaction. You need to do some preparation work to retrieve the refresh token though.
Following the steps describing the Authorization Code flow, you first need to direct the playlist's owner to a URL on Spotify's account server.
The documentation contains the following example URL:
GET https://accounts.spotify.com/authorize/?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback&scope=user-read-private%20user-read-email&state=34fFs29kd09
Simply replace the client_id and redirect_uri with your application's information. Also modify the scope parameter to match the scopes you need, which from my understanding of your use case is playlist-read-private,playlist-modify-private,playlist-read-collaborative since you want to be able to read and modify all of the user's playlists. Supplying state is not required.
Using spotify-web-api-node you can generate this URL using the createAuthorizeURL method, but since you're only doing this once it's unnecessary to write code for it.
Instead, simply open the URL in your browser.
If done successfully, you'll be taken through a little login dance where your application asks for your permission to read and modify your playlists. When this is completed, Spotify's account service will redirect the browser to your redirect_uri URL with a code query parameter included as described in step 3 in the Authorization Guide.
However, since you're only doing this once, it would be enough to start a webserver on your own machine, set your application's redirect_uri to your localhost, and complete the login flow. Have a look at web-api-auth-examples for a ready-made node.js application that fires up an express server and reads the authorization code.
Once you've got the code, you can trade it for an access token using cURL as it's done in step #4 in the Authorization Guide, or use the code in the web-api-auth-examples repository.
Finally, with the tokens retrieved (step #5), you can start to use the Web API with the access token, and get a new one when it expires using the request in step #7.
spotify-web-api-node has a helper method to refresh the token. Search the main documentation for the refreshAccessToken method.
This use case is slightly mentioned in the FAQ section of the Authorization Guide.
As you said, you need to obtain a refresh token using the authorization code flow. For that you will need to carry out the OAuth process using your user account, the client_id of the app you have registered, and the scopes you need (it will vary depending on whether the playlist is private or public). Then, take the refresh token you have obtained and the client secret key of your app, and you can obtain access tokens without the need of the login form.
This related StackOverflow question might help too Spotify automated playlist management with PHP back-end and rate limits

how to secure azure mobile service / html - javascript

When I call an oauth provider like gmail and I get the token back, how can I make sure that all future calls I make are from that same client that did the authentication? that is, is there some kind of security token I should pass pack? Do I pass that token back everytime?
For example, if I have a simple data table used for a guest book with first,last,birthdate,id. How can I make sure that the user who "owns" that record is the only one who can update it. Also, how can I make sure that the only person who can see their own birthday is the person who auth'd in.
sorry for the confusing question, I'm having trouble understanding how azure mobile services (form an html client) is going to be secure in any way.
I recently tried to figure this out as well, and here's how I understand it (with maybe a little too much detail), using the canonical ToDoList application with server authentication enabled for Google:
When you outsource authentication to Google in this case, you're doing a standard OAuth 2.0 authorization code grant flow. You register your app with Google, get a client ID and secret, which you then register with AMS for your app. Fast forwarding to when you click "log in" on your HTML ToDoList app: AMS requests an authorization code on your app's behalf by providing info about it (client ID and secret), which ultimately results in a account chooser/login screen for Google. After you select the account and log in successfully, Google redirects to your AMS app's URL with the authorization code appended as a query string parameter. AMS then redeems this authorization code for an access token from Google on your application's behalf, creates a new user object (shown below), and returns this to your app:
"userId":"Google:11223344556677889900"
"authenticationToken":"eyJhbGciOiJb ... GjNzw"
These properties are returned after the Login function is called, wrapped in a User object. The authenticationToken can be used to make authenticated calls to AMS by appending it in the X-ZUMO-AUTH header of the request, at least until it expires.
In terms of security, all of the above happens under HTTPS, the token applies only to the currently signed-in user, and the token expires at a predetermined time (I don't know how long).
Addressing your theoretical example, if your table's permissions has been configured to only allow authenticated users, you can further lock things down by writing logic to store and check the userId property when displaying a birthday. See the reference docs for the User object for more info.

Resources