tasoskakour / react-use-oauth2 Goto Github PK
View Code? Open in Web Editor NEW๐ A React hook that handles OAuth2 authorization. Both for Implicit Grant and Authorization Code flows.
License: MIT License
๐ A React hook that handles OAuth2 authorization. Both for Implicit Grant and Authorization Code flows.
License: MIT License
In what form do I need to transfer multiple scopes? I also need to transfer claims. I'm working with Oauth2 Twitch.
Example:
&scope=openid+user%3Aread%3Aemail&claims={"id_token":{"email":null, "email_verified":null}, "userinfo":{"email":null, "email_verified":null, "picture":null, "updated_at":null, "preferred_username":null}}
Otherwise everything is fine, thanks
oauth2 audience
must be requested. Currently, aud
is not requested and not returned. My example:
{
"aud": [], <-------- must NOT be empty
"client_id": "dafc3613-93cc-487f-8b53-acf56c258c87",
"exp": 1705277961,
"ext": {},
"iat": 1705234760,
"iss": "http://192.168.1.93:4444",
"jti": "89dff623-1adb-4c21-8a7a-ee165feed06b",
"nbf": 1705234760,
"scp": [
"openid",
"offline",
"email"
],
"sub": "aed89977-dea1-4e30-a2df-63635fc46d64"
}
My request:
const { data, loading, error, getAuth, logout } = useOAuth2({
authorizeUrl: import.meta.env.VITE_AUTH_URL,
clientId: import.meta.env.VITE_CLIENT_ID,
redirectUri: import.meta.env.VITE_REDIRECT_URI,
scope: "openid offline email ec2",
responseType: "code",
extraQueryParameters: { audience: "MyCorp" }, //<------ Requested `audience`. No success
exchangeCodeForTokenServerURL: import.meta.env.VITE_TOKEN_BACK_URL,
exchangeCodeForTokenMethod: "POST",
onSuccess: (payload: TAuthTokenPayload) => console.log("Success:", payload),
onError: (error_) => console.log("Error", error_),
});
UPD:
Tested the following:
extraQueryParameters: { audience: ["Foo"] },
<--- WorksextraQueryParameters: { audience: ["Foo", "Bar"] },
<--- Failserror: message:invalid_request reason:Requested audience 'Foo,Bar' is not found in the OAuth 2.0 Client. stack_trace
This happens since extraQueryParameters
merges array into a single string, whereas audience
requires an input array
First of all, let me express my gratitude for this library.
I propose a feature to deactivate persisting in the local storage by not calling the respective setData(...). The reason is that I don't need the data persistent as I handle all the rest on the backend. You may have a better idea to achieve this in compliance with your vision of this library.
Would it be okay if I prepare the code and initiate a pull request, or you don't want this enhancement?
Thanks in advance for your consideration.
Hey!
I just followed your guidelines for implementing this, specifically for Twitter Oauth2 in a react 18 typescript app.
Whenever I launch the popup by pressing login, I receive a console warn saying 'Warning: Popup was closed before completing authentication.' Upon inspecting the popupRef it's as if it becomes undefined immediately after opening the popup. After completing the authentication with the callback, the popup never closes, because it's already set as 'closed'.
I can upload a repo to showcase this to you if needed.
thanks
I am encountering the error "You are using React 17 or below. Install with "npm install use-local-storage-state@17"
This can't be corrected using the instruction as the module requires the use-local-storage-state@18 which itself requires react@18. This has been since version 1.0.10.
Thanks for this fantastic library!
When using it in my React app, Webpack complains about non-existent source maps. Can you please remove them so that Webpack doesn't try to find them anymore?
Here is the error message:
WARNING in ../../node_modules/@tasoskakour/react-use-oauth2/dist/esm/index.js
Module Warning (from ../../node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/.../node_modules/@tasoskakour/react-use-oauth2/src/src/components/use-oauth2.ts' file: Error: ENOENT: no such file or directory, open '/Users/.../node_modules/@tasoskakour/react-use-oauth2/src/src/components/use-oauth2.ts'
Question - not an issue.
I am hoping to use this library but first wanted to see if you had plans on adding a license (and for selfish reasons hoping it is MIT :).
If you'd like I would be happy to add one via a PR.
No matter what - thanks for this repo and the detailed article. It was really helpful!
Hello,
I am currently trying to build a React application using this library and I seem to hit a wall. I am trying to use the Authorization Code grant type to log in via a popular LMS (LearnUpon). Using the sample code provided in this repository, I configured the useOauth2 hook using the below settings:
const { data, loading, error, getAuth } = useOAuth2({
authorizeUrl: "https://{{redacted}}.learnupon.com/oauth/authorize",
clientId: "{{redacted}}",
redirectUri: `https://{{redacted}}.ngrok.io/callback`,
scope: "full offline_access",
responseType: "code",
exchangeCodeForTokenServerURL: "http://localhost:9000/auth",
exchangeCodeForTokenMethod: "GET",
onSuccess: (payload) => console.log("Success", payload),
onError: (error_) => console.log("Error", error_)
});
I am exposing the React application in dev mode using ngrok. The OAuth popup screen comes up successfully, however the response I get back from my API via Authlib when attempting issue the access token is as follows:
{
"detail": "mismatching_state: CSRF Warning! State not equal in request and response."
}
Why is the state query parameter not sent to my /auth endpoint? Also another curious thing is that my /auth endpoint is raising an HTTP exception which is originating from the Authlib StarletteOAuth2App client. Although in the React UI, it is being logged to the console as a successful login attempt.
Am I doing something ridiculously wrong here? Any information would be helpful.
Related to this #4
Hello,
I have everything working great so thank you for that!
One functionality that I have not figured out yet is how to logout and to basically set the persisted data to null.
Is there anyway to do this?
Thank you!
So, basically after user authorization, the frontend makes call to the backend with just 5 query params { code, client_id, grant_type, redirect_uri, state }
but in some cases, oauth providers attach extra params to the url which are getting lost while a call is being made to exchangeCodeForTokenServerURL
.
We should have the functionality to pass all the params along with the above ones to the backend server.
Everything is set up and working great. Are there plans to add a refresh token option? Currently I am using this for QuickBooks API and it is working very well. I looked through the source and didn't see anything relating to refreshing an access_token with a refresh_token. For the QB API I am sending to the same auth endpoint with grant_type=refresh&refresh_token= whatever refresh_token I got from the last refresh call. Are there plans to include refreshing an access token or did I gloss over something and it's already there? Thank you so much for this, it has saved countless hours so far.
This plug in is really good. With out a lot of difficulties, I was able to get this used for my project.
However I encountered a small issue.
I have been using this for an OAuth2 flow that is not a login. However the concepts remain the same.
After the login / authorisation has been completed in the popup, the backend token URL is getting called twice.
I have changed the token URL to be a GET as well as POST.
Any updates on this would be highly appreciated
Hi, thanks for maintaining this library @tasoskakour .
Quick question, maybe I am also doing it wrong, but I wonder why exchangeCodeForTokenServerURL
is getting called with GET query parameters, when exchangeCodeForTokenMethod
is explicitly set to POST
. I think this is not correct, it should be given as request body to the POST
request or make it configurable how the actual payload is getting send (https://github.com/tasoskakour/react-use-oauth2/blob/master/src/components/use-oauth2.ts#L119).
At least goauthentik doesn't support GET, but POST expects the content to be in body and not in query parameters. Cross-checked doing it in Postman and it worked.
So something like this in the useOAuth
hook:
const exchangeCodeForTokenUseBody = responseType === 'code' && props.exchangeCodeForTokenUseBody; // bool
// ....
if (responseType === 'code' && exchangeCodeForTokenServerURL) {
let response;
if (exchangeCodeForTokenUseBody) {
response = await fetch(exchangeCodeForTokenServerURL, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: exchangeCodeForTokenMethod || DEFAULT_EXCHANGE_CODE_FOR_TOKEN_METHOD,
body: new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code: payload?.code,
redirect_uri: redirectUri
})
});
} else {
response = await fetch(
formatExchangeCodeForTokenServerURL(
exchangeCodeForTokenServerURL,
clientId,
payload?.code,
redirectUri,
state
),
{
method: exchangeCodeForTokenMethod || DEFAULT_EXCHANGE_CODE_FOR_TOKEN_METHOD
}
);
}
payload = await response.json();
}
// ....
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.