get value of access token - google-app-engine

I started using google API recently . I am using simpleauth https://github.com/crhym3/simpleauth for authentication to google app engine . Now I am using google blogger API for publishing my blog and fetching data .
This API requires access_token value to use the API https://developers.google.com/blogger/docs/3.0/using#RetrievingPostsForABlog for Authorization . I cant find a way to get value of access token .
Is there a way to get the value of acces token or am I doing something wrong ?

You need to register your webapp with Google to get a client ID and client secret. Then, you can configure your OAuth2 library with these details to allow you to send fully authenticated requests from your webapp to Blogger.
For the specific scenario you listed, retrieving a blog post, I think you can follow step 1 of this page and then follow these steps. You should be able to copy+paste the key from there into the query params of the GET request.
To issue fully authenticated requests, for publishing new posts, for example, you'll have to get your OAuth2 library with the client ID and client secret and have it issue the requests for you.

Related

How can I retrieve a user ID from Firestore via Flask backend (React frontend)?

I'm a newbie with authentication! I'm building a web app where users can log in, and the data shown in the web app is different for each user. I'm using Reactjs as my frontend with Firebase authentication. After a user logs into my web app, I'm storing their user ID (UID) and other information into Firestore. I have a collection usersCollection where each document is labelled with the UID. For the backend, I'm using Flask as mostly a REST API with a Postgres database, but I am not storing user credentials there (UID, password, etc.).
For some of my backend functions I need to change the output based on which user is signed in, but I'm not sure how to retrieve the current user's UID. I'm able to make an axios request to send the current user's UID from the frontend to the backend, so I've tried 2 methods with that:
Saving the axios request output as a global variable - this has led to Flask errors like runtimeerror: working outside of application context. and I don't think this is the best solution.
With each GET request that the frontend is making to the backend (every time there's a function whose output changes based on user), I am passing the UID as a parameter, which causes latency problems.
What is the simplest way for me to request the current UID from Firestore from the backend?
Is structuring our frontend, backend, database, and authentication like this recommended? Or is there a simpler way or better system for our situation (JWT?)? We selected Firebase authentication in the first place because we are using a React MUI template that already set up Firebase for us.
Thank you in advance! Happy to provide more information if needed!
I don't know reactjs, but I have the same setup with flutter (iOS / Android apps).
What I did and what worked out well is:
authenticate your client against firebase (which it looks you already achieved)
extract the idToken from the firebase response
send the idToken to your flask backend, which verifies the id token (see below)
in flask backend, log in the user with login_user() from flask_login. This creates a cookie session which is sent back to the client in the response headers
the reactjs client stores the cookie and needs to attach it to every subsequent API request to flask (this might come out of the box for reactjs, but for flutter I needed some custom code for that)
As for the token validation you can…
use the python sdk
use a jwt library such as pyjwt, see documentation
There is flask-firebase which does a good job for the token validation. I wrote a blog post which gives an example how you would use this.

Using Google OAuth with React-Django Application

I am working on a web application with ReactJs frontend and Django backend. In this app, I will need to send calender notifications to the users and overall need a user authentication feature for which I planned to use google oauth. From react, I am able to log in the user and get the access tokens but since they expire in an hour, I planned to get the authorization code and use it to get the refresh/access tokens from the backend whenever a user logs in/needs to send API request. The issue is that I am not able to find any good resource on how to get refresh tokens from the backend given I have the authorization code. Most of the HTTP based methods I have found are very outdated and I have searched some of the google documentation but have not found anything worthwhile. Since I could not find any package that would handle this, I have been trying to send POST request to the URL mentioned here (https://developers.google.com/identity/protocols/oauth2/web-server#python_1) but only get a 400 response. Below are 2 methods I have tried.
to_send={'code':user_data['code'], 'client_id': cl_id , 'client_secret': cl_secret,
'redirect_uri':'http://localhost:3000/', 'grant_type':'authorization_code'}
test=requests.post('https://oauth2.googleapis.com/token', data=to_send)
print(test)
credentials = service_account.Credentials.from_service_account_file('path/key.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive.metadata.readonly'])
authed_session = AuthorizedSession(scoped_credentials)
response = authed_session.request('POST', 'https://oauth2.googleapis.com/token', data = to_send)
print(response)
Ive also tried other things like creating a flow object.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( JSON_PATH, scopes=API_SCOPE)
flow.redirect_uri = REDIRECT_URL
flow.fetch_token(code=user_data['code'])
credentials = flow.credentials
where user_data['code'] is the authorization token and I get the error
oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request

Azure Active Directory - UI > API - 401 Error

Good Day,
Currently I have a single tenent with a React UI and .NET Core Apis secured by Azure Active Directory without any problems.
We have recently moved to a new Azure Tenent, new Active Directory etc. I have create two new App Registrations, one single App Service for UI and one for API. I have linked the App Service to AAD (UI = UI App Registration, API = API App Registration).
The problem is the API is getting a 401 error and I think see that in the original tenent the Bearer token is in a JWT format but in the new instance it's not, I believe it my be a graph api access key.
New Tenent:
Authorization: Bearer PAQABAAAAAAD--DLA3VO7QrddgJg7WevrQvEQVbZEMD8su-tIp9k2bTFUTort7SZgeDI52P6KRYefHgtmj4YrecgUKZJ2wylGuhvIzIz642n7Sg0VMU1RwKtrzWlaMqK62CaSoJcstxiEf6 *****
Orginal Tenent:
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiI3OThkN2ZkOC0zODk2LTQxOGMtOTQ0Ny0wNGFlNTQ2OGFkNDIiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83ZDE3NTU3Ni03Y2Y3LTQyMDctOTA5My0wNmNiNmQyZDIwNjAvIiwiaWF0IjoxNjE2NDUyNzExLCJuYmYiOjE2MTY0NTI3MTEsImV4cCI6MTYxNjQ1NjYxMSwiYWNyIjoiMSIsImFpbyI6IkFTUUEyLzhUQUFBQU9mejhPZHp *****
Please someone kindly enought to provide some guidance / input where I am going wrong.
Regards
Paul.
When using Azure AD to obtain an access token, an additional resource parameter is required. Otherwise, the access token is not a JWT.
For example, if your web API's application ID URI is https://contoso.com/api and the scope name is Employees.Read.All, then with oidc-client the client configuration should be :
scope: 'openid profile email Employees.Read.All',
extraQueryParams: {
resource: 'https://contoso.com/api'
}
In App Service auth configuration, you can use additionalLoginParams
"additionalLoginParams": ["response_type=code", "resource=https://contoso.com/api"]
If you did not use a custom application ID URI, it may look like
api://868662dd-3e28-4c7f-b7d5-7ec02ac9c601
Quickstart: Configure an application to expose a web API
Firstly, the scope is incorrect.
You should Expose an API in your API App Registration and then add it as a permission in your UI App Registration. You can refer to this document.
And when you try to call the 'https://login.windows.net/{tenant}/oauth2/authorize endpoint, you need to specify the scope to include api://{app id of the API App Registration}. For example: api://{app id of the API App Registration} openid profile email. Then the access token would be for calling your API.
At last, for CORS issue, please configure the CORS as * in your web app to see if it helps.
Try to follow this step: Configure App Service to return a usable access token
In my experience, this problem occurs, when you try to authorize against version 1 of the endpoint.
Instead of calling
https://login.microsoftonline.com/{tenant}/oauth2/authorize
call
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
You might be required to set something like "metadata URL" in you authorization library to:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/.well-known/openid-configuration
Make sure your builder follows this order...lifted from our API program.cs
These must be in order of
UseRouting -> UseAuthentication -> UseAuthorisation -> MapControllers
> app.UseRouting()
> app.UseAuthentication()
> app.UseAuthorization()
> app.MapControllers()
If app.UseAuthentication and app.UseAuthorization are not in this order in statement position you Will get 401 Unauthorised as at 01/2023 .Net 6 Core.

How to get user info with a valid Bearer Token?

At work we are making an SPFx Web Part React client app that deploys to SharePoint as a Web Part. Our back-end is a ASP.NET Core 2.2 Web API that is secured using Azure Portal's built in Authentication feature. The front-end is using AadHttpClient that magically handles the authentication by taking the context of the current page (SharePoint) that has the user already logged in. Doing so, silent authentication occurs and the API call is successfully made with authentication successfully passed. The AadHttpClient is supposed to magically bundle up the token in the request header that gets sent to the back-end Web API. I still need to debug the live development app and see how to retrieve the Bearer Token in the back-end Web API. These are my next probable steps?
Would I just probably use 'string bearerToken = Request.Headers.....;' or 'string bearerToken = Request.Headers["KeyValue"]' to get the token itself?
Assuming I can get this Bearer Token, how can I check the caller's user information? Is it just var userName = User.Identity.Name;? Or would I or could I use the token and some how make a call to Microsoft Graph API to view the user's info?
If you are using ASP.NET Core and using default authentication then things are bit easier. From documentation you can see that several tokens are injected in the request header based on Identity provider so in your case you have to look for following headers which Azure AD injects. These headers would contain ID Token which you would need to verify the claims and get user information.
X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN
Ideally all the claims are injected automatically in ClaimsPrincipal
you can find more here
Official Docs
How To extract Token

WebAPI registered in new v2 endpoint does not prompt consent screen

An app registered in the v2 app registration portal, with a webapi platform added, however when requesting the authorisation with api scope using https://login.microsoftonline.com/common/oauth2/v2.0/authorize endpoint, it directly go to the redirect url with error code AADSTS70002%3a+Error+validating+credentials. Instead if I use the graph api, everything works, not sure what did I did wrong!
The one for the webapi scope:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=222db0-0305-4f86-96cc-d283da2f5020&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2Ftest&response_mode=query&scope=openid%20offline_access%20api%3A%2F%2Fc6599db0-0305-4f86-96cc-d283da2f5020%2Faccess_as_user
The one for the graph api:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=222db0b0-0305-4f86-96cc-d283da2f5020&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2Ftest&response_mode=query&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
EDIT
This is confusing, now I put the offline and open id to the end but get another error:
AADSTS65005%3a+The+application+'v2app'+asked+for+scope+'openid'+that+doesn't+exist+on+the+resource.+Contact+the+app+vendor.
The URL I requested is:
https://login.microsoftonline.com/e0582222da8-ec2b-4c7a-b98e-2c417627657c/oauth2/v2.0/authorize?client_id=c6599db0-0305-4f86-96cc-d283da2f5020&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2Ftest&response_mode=query&scope=api%3A%2F%2Fc6599db0-0305-4f86-96cc-d283da2f5020%2Faccess_as_user%20openid%20offline_access
And if I google this error, there is one saying:
As of today, the V2 Endpoint does not support API access other than the Microsoft Graph.
So this is not achievable? Then how come the sample works?
EDIT 2
So if I make the requested scope the client ID, it works..
I reproduced your error . but if putting the openid%20offline_access scopes after api%3A%2F%2Fc6599db0-0305-4f86-96cc-d283da2f5020%2Faccess_as_user(api scope) , it works on my side , please try :
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=222db0-0305-4f86-96cc-d283da2f5020&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2Ftest&response_mode=query&scope=api%3A%2F%2Fc6599db0-0305-4f86-96cc-d283da2f5020%2Faccess_as_user%20openid%20offline_access
Update
The MSAL error you linked is accessing a Web API from a client that has a different Application ID , that is not supported in v2.0 endpoint . In azure ad v2.0, Web API can receive tokens only from an application that has the same Application ID. That means api://xxxx-xxxx-xxx-xxx (web api url) , the xxxx-xxxx-xxx-xxx part has the same value with your client id of client application . To achive that , you could add two platforms : one web app ,one web api .

Resources