react-oauth2-code-pkce ·
React package for OAuth2 Authorization Code flow with PKCE
Adhering to the RFCs recommendations, cryptographically sound, and with zero dependencies!
What is OAuth2 Authorization Code Flow with Proof Key for Code Exchange?
Short version;
The modern and secure way to do authentication for mobile and web applications!
Long version;
https://oauth.net/2/pkce/
https://datatracker.ietf.org/doc/html/rfc7636
Features
- Authorization provider-agnostic. Works equally well with all OAuth2 authentication servers following the OAuth2 spec
- Supports OpenID Connect (idTokens)
- Pre- and Post-login callbacks
- Session expired callback
- Silently refreshes short-lived access tokens in the background
- Decodes JWT's
- A total of ~440 lines of code, easy for anyone to audit and understand
Example
import { AuthContext, AuthProvider, TAuthConfig } from "react-oauth2-code-pkce"
const authConfig: TAuthConfig = {
clientId: 'myClientID',
authorizationEndpoint: 'https://myAuthProvider.com/auth',
tokenEndpoint: 'https://myAuthProvider.com/token',
redirectUri: 'http://localhost:3000/',
scope: 'someScope openid',
}
const UserInfo = (): JSX.Element => {
const {token, tokenData} = useContext<IAuthContext>(AuthContext)
return <>
<h4>Access Token</h4>
<pre>{token}</pre>
<h4>User Information from JWT</h4>
<pre>{JSON.stringify(tokenData, null, 2)}</pre>
</>
}
ReactDOM.render(<AuthProvider authConfig={authConfig}>
<UserInfo/>
</AuthProvider>
, document.getElementById('root'),
)
For more advanced examples, see ./examples/
.
For instance, it's recommended to add a "Session expired"-callback like so:
onRefreshTokenExpire: (event) => window.confirm('Session expired. Refresh page to continue using the site?') && event.login(),
.
Install
The package is available on npmjs.com here; https://www.npmjs.com/package/react-oauth2-code-pkce
npm install react-oauth2-code-pkce
IAuthContext values
The IAuthContext
interface that the AuthContext
returns when called with useContext()
provides these values;
interface IAuthContext {
token: string
tokenData?: TTokenData
login: () => void
logOut: () => void
error: string | null
idToken?: string
loginInProgress: boolean
}
All configuration parameters
The <AuthProvider>
takes a config
object that supports these parameters;
type TAuthConfig = {
clientId: string
authorizationEndpoint: string
tokenEndpoint: string
redirectUri: string
scope?: string
logoutEndpoint?: string
logoutRedirect?: string
preLogin?: () => void
postLogin?: () => void
onRefreshTokenExpire?: (event: TRefreshTokenExpiredEvent) => void
decodeToken?: boolean
autoLogin?: boolean
extraAuthParameters?: { [key: string]: string | boolean | number }
extraTokenParameters?: { [key: string]: string | boolean | number }
extraAuthParams?: { [key: string]: string | boolean | number }
}
Known issues
The page randomly refreshes in the middle of a session
This will happen if you haven't provided a callback-function for the onRefreshTokenExpire
config parameter, and the refresh token expires.
You probably want to implement some kind of "alert/message/banner", saying that the session has expired and that the user needs to login again.
Either by refreshing the page, or clicking a "Login-button".
After redirect back from auth provider with ?code
, no token request is made
If you are using libraries that intercept any fetch()
-requests made. For example @tanstack/react-query
. That can cause
issues for the AuthProviders token fetching. This can be solved by not wrapping the <AuthProvider>
in any such library.
Develop
- Update the 'authConfig' object in
src/index.js
with config from your authorization server and application - Install node_modules ->
$ yarn install
- Run ->
$ yarn start
Contribute
You are welcome to create issues and pull requests :)