forked from authts/react-oidc-context
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
92 lines (81 loc) · 2.98 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import * as React from "react";
import * as ReactDOM from "react-dom";
import { User, IndexedDbDPoPStore } from "oidc-client-ts";
import { AuthProvider, useAuth, type AuthProviderProps } from "../src/.";
const onSigninCallback = (_user: User | void): void => {
window.history.replaceState(
{},
document.title,
window.location.pathname,
);};
const oidcConfig: AuthProviderProps = {
authority: "https://localhost:5001",
client_id: "js_oidc",
redirect_uri: "http://localhost:1234/",
onSigninCallback: onSigninCallback,
scope: "openid profile email offline_access",
monitorSession: true,
dpop: { bind_authorization_code: true, store: new IndexedDbDPoPStore() },
};
function App() {
const auth = useAuth();
const callApi = async () => {
try {
const url = "https://localhost:5005/identity";
const token = auth.user?.access_token;
const nonce = sessionStorage.getItem("api_nonce");
let DPoPProof = await auth.dpopProof(url, auth.user as User, "GET", (nonce === null ? undefined : nonce));
let response = await fetch("https://localhost:5005/identity", {
credentials: "include",
mode: "cors",
method: "GET",
headers: {
Authorization: `DPoP ${token}`,
DPoP: DPoPProof,
},
});
if (response.headers.has("Dpop-Nonce")) {
const nonce = response.headers.get("Dpop-Nonce") as string;
DPoPProof = await auth.dpopProof(url, auth.user as User, "GET", nonce);
sessionStorage.setItem("api_nonce", nonce);
response = await fetch("https://localhost:5005/identity", {
credentials: "include",
mode: "cors",
method: "GET",
headers: {
Authorization: `DPoP ${token}`,
DPoP: DPoPProof,
},
});
}
console.log(await response.json());
} catch (e) {
console.error(e);
}
};
if (auth.isLoading) {
return <div>Loading...</div>;
}
if (auth.error) {
return <div>Oops... {auth.error.message}</div>;
}
if (auth.isAuthenticated) {
return (
<div>
Hello {auth.user?.profile.given_name}{" "}{auth.user?.profile.family_name}
<button onClick={() => void auth.removeUser()}>
Log out
</button>
<button onClick={() => void callApi()}>Call Api</button>
<button onClick={() => void auth.signinSilent()}>Use Refresh token</button>
</div>
);
}
return <button onClick={() => void auth.signinRedirect()}>Log in</button>;
}
ReactDOM.render(
<AuthProvider {...oidcConfig}>
<App />
</AuthProvider>,
document.getElementById("root"),
);