React 中授权码模式有示例吗?

2022 年 7 月 11 日
 guisheng

目前我在自己创建一个 授权码模式 提供者,创建一个 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 则会进入重定向死循环。。

问题有点没头没脑的,求个简单示例吧。

455 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/865440

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX