51
loading...
This website collects cookies to deliver better user experience
http://localhost:3000
to the allowed callback URLs, web origins and logout URLs. If you deploy this application to a cloud provider, the URLs need to be added here as well:.env
file:VITE_APP_AUTH0_DOMAIN=<app-id>.<region>.auth0.com
VITE_APP_AUTH0_CLIENT_ID=<your-auth0-client-id>
.env
:JWKS_URL=https://<app-id>.<region>.auth0.com/.well-known/jwks.json
npm i -D vite-plugin-windicss windicss
vite.config.js
config file:
import WindiCSS from 'vite-plugin-windicss'
export default {
plugins: [WindiCSS()]
}
windi
to your main.js/ts
import 'virtual:windi.css'
npm install @auth0/auth0-react
Auth0Provider
to your main.jsx/tsx
:import 'virtual:windi.css'
import { createRoot, hydrateRoot } from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Auth0Provider } from '@auth0/auth0-react'
import { Routes } from '@/config'
function App(): JSX.Element {
return (
<BrowserRouter>
<Auth0Provider
domain={import.meta.env.VITE_APP_AUTH0_DOMAIN!}
clientId={import.meta.env.VITE_APP_AUTH0_CLIENT_ID!}
redirectUri={
typeof window !== 'undefined' ? window.location.origin! : ''
}
>
<Routes />
</Auth0Provider>
</BrowserRouter>
)
}
const app = document.querySelector('#app') as Element
const root = createRoot(app)
if (app.hasChildNodes()) hydrateRoot(app, <App />)
else root.render(<App />)
index.jsx/tsx
, so we'll add the useAuth0
helper to that page and require authentication:import { useAuth0, withAuthenticationRequired } from '@auth0/auth0-react'
function Home(): JSX.Element {...}
export default withAuthenticationRequired(Home, {
onRedirecting: () => <div>Redirecting you to the login page...</div>
})
error
, isLoading
as well as the user
data and logout
action:const { isLoading, getAccessTokenSilently, error, user, logout } = useAuth0()
Hello {user.name}!
getAccessTokenSilently()
and pass the audience
. Prefixed with Bearer
, we have a valid authentication token for our API:const token = await getAccessTokenSilently({
audience: `https://${import.meta.env.VITE_APP_AUTH0_DOMAIN}/api/v2/`
})
const response = await fetch(url, {
mode: 'cors',
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': ' application/json',
Authorization: `Bearer ${token}`
}
})
const data = await response.json()
Authorization
header. The easiest way is a simple Middleware to decode the token:import Foundation
import Hummingbird
import HummingbirdAuth
import JWTKit
struct JWTPayloadData: JWTPayload, Equatable, HBAuthenticatable {
enum CodingKeys: String, CodingKey {
case subject = "sub"
case expiration = "exp"
}
var subject: SubjectClaim
var expiration: ExpirationClaim
// Define additional JWT Attributes here
func verify(using signer: JWTSigner) throws {
try self.expiration.verifyNotExpired()
}
}
struct JWTAuthenticator: HBAsyncAuthenticator {
var jwks: JWKS
init(jwksUrl: String) throws {
let jwksData = try Data(
contentsOf: URL(string: jwksUrl)!
)
jwks = try JSONDecoder().decode(JWKS.self, from: jwksData)
}
func authenticate(request: HBRequest) async throws -> JWTPayloadData? {
guard let jwtToken = request.authBearer?.token else { throw HBHTTPError(.unauthorized) }
let signers = JWTSigners()
do {
try signers.use(jwks: jwks)
let payload = try signers.verify(jwtToken, as: JWTPayloadData.self)
return payload
} catch {
print("couldn't verify token")
throw HBHTTPError(.unauthorized)
}
}
}
3000
for the vite client, 8080
for the hummingbird server), we'll also need to enable Cross-Origin Resource Sharing (CORS). You can add both middlewares to your Application+configuration.swift`:
`swift
swift
let jwtPayload = request.authGet(JWTPayloadData.self)
let userId = jwtPayload?.subject
.env
variables out of the box, so we'll use a Makefile
to load the environment and build/run the server:
`makefile
.env
file already for the server, so the JWKS_URL
should be available, otherwise make start
will throw an error, as the precondition fails.
npm run dev
3000
and:
make start
8080
. Open your browser on http://localhost:3000
and you should be redirected to an Auth0 login screen:/api
). The application starts with a nice, branded login/signup window and easily integrates with social providers by just enabling them in the Auth0 console. Auth0 credentials are stored in a cookie and a JWT access token can be requested on demand when API requests are made.