目前我在自己创建一个 授权码模式 提供者,创建一个 React 去调用。
关键角色:认证服务,认证客服端,回调地址。
callback.tsx
export default function CallBack() {
useEffect(() => {
window.location.href = 'http://127.0.0.1:8080/';
}, []);
return (
<div>登录跳转中...</div>
);
}
AuthContext.tsx
useEffect(() => {
const initialize = async () => {
//
const code = new URL(window.location.href).searchParams.get('code');
// 是否已经登录了
const accessToken = localStorage.getItem('accessToken');
if (code) {
const body = [];
body.push('grant_type=authorization_code');
body.push(`code=${code}`);
body.push('redirect_uri=http://127.0.0.1:8080/callback');
axios.post('/api/oauth2/token', body.join('&'), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic YmVhci1jbGllbnQ6YmVhcg==',
},
}).then(response => {
if (response.status !== 200) {
return Promise.reject(new Error('Invalid status code received in the token response: '
+ response.status));
}
setSession(response.data.access_token);
});
}
console.log('AuthContext' + code);
// check token
if (accessToken) {
const user = { 'username': 'admin' };
dispatch({
type: Types.init,
payload: {
isAuthenticated: true,
user,
},
});
}
AuthGuard.tsx
if (!isAuthenticated) {
if (pathname !== requestedLocation) {
setRequestedLocation(pathname);
}
let authorize = 'http://127.0.0.1:9000/oauth2/authorize?response_type=code&scope=market&client_id=bear-client&redirect_uri=http://127.0.0.1:8080/callback';
window.location.href = authorize;
}
AuthGuard -> callback -> AuthContext
退出后 callback -> AuthContext ,如果删除 callback 直接进入 AuthContext 则会获取不到 token.
但是我退出如果只是删除了 session 则会进入重定向死循环。。
问题有点没头没脑的,求个简单示例吧。