V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
guisheng
V2EX  ›  问与答

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

  •  
  •   guisheng · 2022 年 7 月 11 日 · 455 次点击
    这是一个创建于 1362 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    目前尚无回复
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   897 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 22:23 · PVG 06:23 · LAX 15:23 · JFK 18:23
    ♥ Do have faith in what you're doing.