Call Rest API with user using Python requests - python

I want to call an API using requests.get() method where I have to give username and password as authentication like below.
response = requests.get(url, auth=requests.auth.HTTPBasicAuth('username', 'password'))
but I don't want to give password in auth as it will work dynamically where password will be encrypted.
so is there any way to do this by only giving username and not password?

There are a handful of methods to authenticate with an API, the most popular would probably be Token Authentication with something like JWT. This will allow your users to authenticate with your API without sending username and password. If you are using django rest framework, the link I provided should help to get you started.

Related

How to logout / signout from firebase auth with python flask

I am Creating a simple login, logout, signup flask web app using firebase auth and I successfully created login and signup but stuck in logout. So is there any way to log out or sign out from firebase auth?
Thanks
There is no way to invalidate a specific token, however you can invalidate the refresh token (refer this article)
But that doesn't seem to be your problem. So, Simply the best way to go about this would be to delete the token or forget the user from client side :
auth.current_user = None
After the user is set to None, the requests will not be authenticated and hence it's more like the user has logged out.
Still, if you want to implement this for some specific case, there is a workaround you can refer here
When you log in with firebase, it typically gives you a refresh token and an id token. These are JWT's that identify the user and the other refreshes the id token when it expires as the id token expires after 1 hour.
If you are using something like PyreBase
auth.current_user = None is not secure.
Instead, you should look at the sign out method provided.
import pyrebase
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(email,password)
auth.signOut()

Django REST Custom (token) authentication

Because I'm mixing things up and just making myself more confused, maybe someone can actually guide me through it.
I need to make a Django REST API that requires login. However the User table already exists in a Postgres database. I think token-based authentication is most suitable, however, those tokens don't exist yet.
(Login once to retrieve/create a token, check the token on each request)
How can I use a POST request to submit login details purely for verifying the user?
How would I generate a token upon successful login, and should I store it in a new Token table?
After this, how can I use the token to provide authentication/authorization on API data requests?
All examples I can find use the default Django User model or don't go into enough detail, which I can't use in this case.
I've made a custom authenticator that checks the username and password, however I can't get through the next steps.
from api.models import LogonAccount
from rest_framework import authentication
from rest_framework import exceptions
import bcrypt
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.data.get('username') # get the username request header
password = request.data.get('password') # get the password request header
if not username or not password: # no username or password passed in request headers
return None # authentication did not succeed
try:
user = LogonAccount.objects.get(username=username)
if bcrypt.hashpw(password.encode(), user.password.encode()):
print("succes")
return (user, None) # authentication successful
except LogonAccount.DoesNotExist:
raise exceptions.AuthenticationFailed('No such user')
Don't get confused, you are simply trying to achieve token-based authentication with DRF. DRF already comes with this feature. This article will guide you through that https://simpleisbetterthancomplex.com/tutorial/2018/11/22/how-to-implement-token-authentication-using-django-rest-framework.html

Searching for users in Foursquare API- Missing credentials error 401

Please help. I am trying to search for a specific user in Foursquare but for some reason I got Missing credentials error 401.
user_id = '484542633' # user ID with most agree counts and complete profile
url = 'https://api.foursquare.com/v2/users/{}?client_id={}&client_secret={}&v={}'.format(user_id, CLIENT_ID, CLIENT_SECRET, VERSION) # define URL
# send GET request
results = requests.get(url).json()
user_data = results['response']['user']
# display features associated with user
user_data.keys()
As documentation states, this endpoint is meant to be accessed on behalf of the user:
This endpoint requires user authentication.
User calls require a valid OAuth access token in the query string of each request instead of the Client ID and Secret (&oauth_token=XXXX).
For more information about this authentication method and how to obtain an access token, see the Authentication docs.
This means v2/users can only be accessed by your app, after a user (which can be you, using your own Foursquare account) goes through the OAuth login flow and grants necessary permissions. OAuth doesn't mean your app "logs in" as the user, rather that the user has given you permission to do something on their behalf.
To learn more about OAuth you can watch this talk: https://www.youtube.com/watch?v=996OiexHze0
To read more about Foursquare's API visit their documentation site: https://developer.foursquare.com/docs/api/

Avoid login auth in Docusign

For regular flow: a user has to login (in docusign view) to get a code to get token and upload his docummnet.
I want to user my personal account to get this token without login in docusign view. Is there a way to do this?
You can use JWT for this.
"In the JWT bearer authentication flow, your application posts a JWT to the DocuSign authentication service, asserting its credentials and providing the data of the user that it wishes to impersonate (act on behalf of). DocuSign validates that the assertion is signed and that your application has the permission to act on behalf of the user, then issues an access token that allows you to call DocuSign APIs."
https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-jsonwebtoken

Facebook Login in Django Backend with big Frontend separation.

I'm trying to make a login with Facebook.
What I want is to create and endpoint and use it as I use the "standard" email login endpoint, since I need a big separation between the backend and the frontend.
I think it should be easy to do it, but I don't know how to do it.
I read this and when I use the Url in the browser, it works properly and I get the token in the response Url. But, it happens always on the frontend side.
I tried many tutorials this one is an example, and it works, but I'm the backend, I'm not allowed to have something like that, as the frontend is written in Django too.
So, I don't know how should be the workflow when you're just the Backend, I don't know what the Frontend developers wait from me because the authentication happens actually on the frontend side.
And I'm a little bit lost.
Maybe someone had the same problem as Backend and could help me, at least tell me, how the workflow backend - frontend should be.
Facebook JavaScript/Android/iOs SDKs lets the client to authenticate the users. Once the user is authenticated with facebook, your clients can send the accessToken through a HTTP POST over https.
This is what I have done in a similar situation,
At backend,
Create API endpoint to authenticate user by validating their accessToken,
POST /auth/
Use this endpoint to verify the accessToken sent by the client. The token should be validated calling Facebook services with your app secret. Once done validating, return a response as a JSON detailing the status of the authentication and user identification details if successful.
on the request,
body should contain accessToken as a key/or a header
Content-Type header should be application/json
any additional expected headers must be validated
on the request try to include
status of the operation
user identification detail if operation is success
a JWT or some sorta token to identify the user which users can include in Authorization header, so that you can validate the request just buy validating the token against User. Set an expiry as the accessToken if JWT is expired, refresh accessToken at client side and validate again.
At Frontend.
Let the client do the following to authenticate themselves.
send accessToken to /auth as a POST request.
if authentication status is success, let them store the JWT in locally and use it on the upcoming requests.
at backend on upcoming calls,
if token is expired or tampered, redirect client to authenticate with Facebook again.
on logging out of user, delete the token from client.
So for the frontend developers,
Document your API properly and share it with them

Categories

Resources