Salesforce REST API logout - python

Is there a Salesforce endpoint to logout a session (not involving oauth?).
For example, I have a python script that logged in via the REST API using the username, password, security token method (I am using simple_salesforce for this).
simple_salesforce does not provide an inbuilt way to logout. Instead, according to the developer, logging out should be our responsibility:
https://github.com/heroku/simple-salesforce/issues/35
In the url above, it recommends we hit the salesforce revoke endpoint as described here:
https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_revoke_token.htm&language=en_US
However, as I mentioned before, I used the username, password, security token method to login, not the oauth.
Assuming, I cannot use the oauth way to login, what url/endpoint do I need to hit to logout the session?
Thanks!

Answering my own question. Perhaps this may be helpful to anyone else.
When using the username, password, security-token method instead of oauth to login, you still use the oauth revoke endpoint to logout. As shown in Salesforce documentation (https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_revoke_token.htm&language=en), the revoke endpoint has the following url: https://login.salesforce.com/services/oauth2/revoke?token=currenttokenID
The token we will hit the endpoint with is actually our session_id. So, in simple_salesforce, once we have created the sf object as follows
sf = Salesforce(username='myemail#example.com', password='password', security_token='token')
we get the session id by sf.session_id.
Now to hit the endpoint we can use requests (which is already there in the sf object)
payload = { "token": sf.session_id }
url = 'https://test.salesforce.com/services/oauth2/revoke'
r = sf.request.get(url, params=payload)
if r.status_code == 200:
#successfully logged out, good to go!
else:
#uh-oh, something went wrong. check it out
Hope this helps!

Related

How Can I get an ID Token while validating using Username and Password?

I am using Python ADAL library to Authenticate a user using Azure Active Directory. I successfully receive the access token post authentication. Now, I want to verify the validity of the access token. I need the ID_TOKEN in this case. How do I get it?
import adal
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/{{tenant_id}}")
token_response = auth_context.acquire_token_with_username_password("https://management.core.windows.net/", username, password, client_id)
In the token response, I get the access_token and refresh_token but I do not receive the id_token. Following a similar question, How to verify JWT id_token produced by MS Azure AD? I used the code to validate the access token but I need the ID_TOKEN.
Any thoughts on getting this would be great.
No need to get the ID_TOKEN, try the code as below.
import adal
import jwt
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/{{tenant_id}}")
token_response = auth_context.acquire_token_with_username_password("https://management.core.windows.net/", username, password, client_id)
token_header = jwt.get_unverified_header(token_response['accessToken'])
For more details, you could refer to this similar issue and this doc.

Why does Azure Active Directory OAuth work for me and no one else?

I am developing a Python/Flask application and I want to use OAuth for signing in. My employer uses Azure Active Directory so I am trying to integrate with it as an OAuth provider.
I am not an Azure tenant administrator.
I created an App Registration and set up my code following Microsoft's documentation, but I am the only person who can successfully sign in to the app.
I am constructing my authorization URL like this (I have the correct tenant name, client id, and redirect URI in my code):
import urllib.parse
import uuid
authorization_endpoint = 'https://login.microsoft.com/my-tenant.onmicrosoft.com/oauth2/authorize'
query = {
'client_id': 'my-client-id',
'nonce': uuid.uuid4(),
'redirect_uri': 'https://my-app.example.com/authorize',
'response_mode': 'form_post',
'response_type': 'id_token',
'scope': 'openid',
'state': uuid.uuid4()
}
authorization_url = f'{authorization_endpoint}?{urllib.parse.urlencode(query)}'
When I personally test signing in to the app, everything works fine. But when anyone else tries, they visit the authorization URL, sign in with their credentials, and then get a page with this error:
AADSTS165000: Invalid Request: The request tokens do not match the user context. Do not copy the user context values (cookies; form fields; headers) between different requests or user sessions; always maintain the ALL of the supplied values across a complete single user flow. Failure Reasons:[Token values do not match;]
Why does it work for me and for no one else?
The authorization endpoint is wrong. It should be https://login.microsoftonline.com/... instead of https://login.microsoft.com/....

How to apply Spotify API authentication on my current code which uses Spotify Search API?

Earlier I was using Spotify's Search API
without any kind of authentication. But just last week or so, they made their API usage with Authentication only.
So since the past 2-3 days I've not been able to figure how this authorization works for Search API where I as a developer can let users access responses from Search API without having them to login with their Spotify accounts.
Can someone help me with this authorization stuff(The docs from Spotify don't solve my problem :< )
So here's the python code that I was earlier using -
import requests
import json
def Spotify(keyword):
url = "https://api.spotify.com/v1/search?q="+keyword+"&type=track&limit=1"
headers = {
'accept': "application/json",
'access_token':''
}
r = requests.get(url=url,headers=headers).text
jsonwa = json.loads(r)
name = jsonwa["tracks"]["items"][0]["name"]
artists = jsonwa["tracks"]["items"][0]["artists"][0]["name"]
song_preview_url = jsonwa["tracks"]["items"][0]["preview_url"]
image = jsonwa["tracks"]["items"][0]["album"]["images"][1]["url"]
return_this = []
return_this.append(name)
return_this.append(artists)
return_this.append(song_preview_url)
return_this.append(image)
print return_this
return return_this
song = "hello"
Spotify(song)
Per the web authorization docs:
All requests to the Spotify Web API require authorization
You'll need your users to grant permission for your app in order to get an access token. The user must be logged in to gran permission.
Once your app is granted permission by the user, you can use the refresh_token from that point on, and the user shouldn't need to grant permission again unless they revoke permission for example. You'll need to manage the access_token expiration.

Handling two step authentication using Python requests module

My requirement is to capture cookie from authentication server and i'm able to achieve it using requests module. However, this piece of code breaks (doesn't return any cookies) when "two step verification" is enabled. Basically if i enable two-step-verification, it will send secure code to registered devices which can be used as second level of authentication. Appreciate any pointers.
import requests
auth = 'https://auth.corp.xyz.com/authenticate'
params = {"accoundId": "xyz",
"accountPassword": "abc",
"appIdKey": "xxxxxxxxxxxxx"
}
s = requests.session()
r = s.post(auth,params = params)
print r.request.headers['Cookie']
'd01_ac=9eba0c6ec6f1c09bafb29be785ad9d2373d588d3b1633a418ab932166ea5f832ae036a4f2a89a675adc6e31ebdc7c251215a4a354a085865f6c775fb4cd7544d4c64a429f27fce08bc99058d40497202a4abeedb51f73a53f246fe148560GZVX; dslang=US-EN; myacinfo=DAWTKNV2eed01036859507613988fcc6e5540e93e248a4cbee7243868b1bf5f53b3d698002b4823e872d35c848af2be146529062c6ee05e320367fadfe0e5ae507dd3c07baab03e878c12949efbeb9471111e2b0930c38c05a714f3cd8896c8b63a1201468909a0de019534f1652d49f7e7f280a82627920dbdc8a1ea413f570d16b87c063963712d5932d61a658ff380407f96f34c90e58c223d39ca90f11cc76ca521a3babf4c9f21ea0d35b77ece1b0b175ec21bd74d2d9b108759c38b71d285dde24d21c9d2eac3dfe2e4bd01df6968ebc12fe6bf132d80a0232d6b8ee61a7bfe134b86f6662316431313062326531613231MVRYV2'
The idea of 2 step authentication is next:
You app says to the server. I want to authenticate a user. Give me a
token.
Here is a token. Redirect your user to this url and pass a token
with it.
Users logs in on the server
Server redirects user to your site by providing data about user and
a 'token' you gave so you can match the token with an exact user who
wanted to authenticate.
Does it make sense?

couchDB , python and authentication

I have installed couchDB v 0.10.0, and am attempting to talk to it via python from Couch class downloaded from couchDB wiki. Problem is:
Create database 'mydb': {'error': 'unauthorized', 'reason': 'You are not a server admin.'}
I hand edited the local.ini file to include my standard osx login and password. I now have full access via futon but no joy WRT python. Is this an http header issue?
At a a loss - thanks!
To concour David's reply, (i.e. "This is how I do it using module CouchDB 0.8 in python 2.6 with couchdb 1.0.2")
couch = couchdb.Server(couch_server)
couch.resource.credentials = (USERNAME, PASSWORD)
You can also do:
db = couchdb.Database("http://your.url/yourdb")
db.resource.http.add_credentials(username, password)
after which all your requests should work.
The Couch class in the example does not pass any authentication information to the database, so it is not a miracle that it does not allow privileged operations. So your only options are:
disable authentication completely (as you mentioned)
pass the user name and password as part of the URI
pass the user name and password as an Authorization HTTP request header
If you want to pass a user name and a password, then you will need to change the Couch class. Sending an Authorization HTTP request header is easier, since the Couch class uses the httplib.HTTPConnection class. You can add such a header next to the Accept one this way:
headers = {
"Accept": "application/json",
"Authorization": "Basic " + 'username:password'.encode('base64')[:-1]}
Same for the other HTTP request methods.
The documentation on the basic authentication is here:
http://books.couchdb.org/relax/reference/security
Just pass it as part of the URI...python-couchdb will parse the user/pass out and use them:
http://user:pass#localhost:5984
Above are all nice; but I've found that for oauth validation methods versus basic auth, this works really well:
from couchdb import Server, Session
auth = Session()
auth.name = USERNAME
auth.password = PASSWORD
s = Server('http://localhost:5984/', session=auth)
db = s['dbname']
Note: This will not work with basic authentication; in such a case, fviktor has what I consider to be the best answer. You might also look into the security reference material he linked to if you're interested in persistent auth sessions.
There are several patches for python-couchdb that enable authentication. The code probably will be included in Version 0.7 but until then you can usr teh fork at http://github.com/mdornseif/couchdb-python - it allows you to use http://user:pass#127.0.0.1:5984/ type URLs.
http://blogs.23.nu/c0re/2009/12/running-a-couchdb-cluster-on-amazon-ec2/ (at the bottom) shows how to use CouchDB passwords.

Categories

Resources