expo 项目, 实现 okta 登录(Typescript)

expo 项目, 实现 okta 登录(Typescript)

Button, Text 组件引用于 React Native Elements

expo 使用 okta 的官方文档的使用说明, docs.expo.dev/guides/auth...

官方 code 示例:

javascript 复制代码
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest, useAutoDiscovery } from 'expo-auth-session';
import { Button, Platform } from 'react-native';

WebBrowser.maybeCompleteAuthSession();

export default function App() {
  // Endpoint
  const discovery = useAutoDiscovery('https://<OKTA_DOMAIN>.com/oauth2/default');
  // Request
  const [request, response, promptAsync] = useAuthRequest(
    {
      clientId: 'CLIENT_ID',
      scopes: ['openid', 'profile'],
      redirectUri: makeRedirectUri({
        native: 'com.okta.<OKTA_DOMAIN>:/callback',
      }),
    },
    discovery
  );

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { code } = response.params;
    }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync();
      }}
    />
  );
}

这里的针对自己的项目需要做些调整与解释:

  1. clientId, scopes, redirectUri, discovery
  2. 返回 code 之后, 怎么使用? 怎么拿到 accessToken
  • 设置 .env 存放敏感配置
config 复制代码
EXPO_PUBLIC_OKTA_CLIENT_ID=0oaxxxxxxxxxxxxxxxxx
EXPO_PUBLIC_OKTA_ISSUER=https://<my_company_name>.okta.com/oauth2/ausxxxxxxxxxxxxxxxxx
EXPO_PUBLIC_OKTA_CALLBACK=<my_company_name>-data://callback

注意: CLIENT_ID 一般是 0oaxxxxxxxxxxxxxxxxx 开头, 20 位

  • 直接使用

注意:

  1. redirectUri 是直接使用 process.env.EXPO_PUBLIC_OKTA_CALLBACK 并没有调用 makeRedirectUri
  2. scopes 可能根据个人需要调整
  3. const discovery = useAutoDiscovery(oktaConfig.issuerUrl); 会在 useAuthRequestexchangeCodeAsync 中用到. discovery 的类型是 DiscoveryDocument

codes:

js 复制代码
import { Button, Text } from "@rneui/themed";
import {
  DiscoveryDocument,
  TokenResponse,
  TokenResponseConfig,
  exchangeCodeAsync,
  useAuthRequest,
  useAutoDiscovery,
} from "expo-auth-session";
import * as WebBrowser from "expo-web-browser";
import * as React from "react";
import { ScrollView, StyleSheet, View } from "react-native";

WebBrowser.maybeCompleteAuthSession();

// okta configuration
const oktaConfig = {
  clientId: process.env.EXPO_PUBLIC_OKTA_CLIENT_ID as string,
  scopes: ["openid", "profile", "email", "groups"],
  issuerUrl: process.env.EXPO_PUBLIC_OKTA_ISSUER as string,
  callbackUrl: process.env.EXPO_PUBLIC_OKTA_CALLBACK as string,
};

export default function App() {
  // Endpoint
  const discovery = useAutoDiscovery(oktaConfig.issuerUrl);
  // Request
  const [request, response, promptAsync] = useAuthRequest(
    {
      clientId: oktaConfig.clientId,
      scopes: oktaConfig.scopes,
      redirectUri: oktaConfig.callbackUrl,
    },
    discovery
  );

  React.useEffect(() => {
    if (response?.type === "success") {
      const { code } = response.params;

      if (request && code) {
        // function for retrieving the access token and refresh token from our code
        const getToken = async () => {
          const codeRes: TokenResponse = await exchangeCodeAsync(
            {
              code,
              redirectUri: oktaConfig.callbackUrl,
              extraParams: request.codeVerifier
                ? { code_verifier: request.codeVerifier }
                : undefined,
              clientId: oktaConfig.clientId,
            },
            discovery as DiscoveryDocument
          );
          // get the config from our response to cache for later refresh
          const tokenConfig: TokenResponseConfig = codeRes?.getRequestConfig();

          // get the access token to use
          const jwtToken = tokenConfig.accessToken;

          // caching the token for later
          console.log("jwtToken: ", jwtToken);

          // decoding the token for getting user profile information
        };
        getToken();
      }
    }
  }, [response]);

  return (
    <View style={styles.container}>
      <ScrollView>
        {response && <Text>{JSON.stringify(response, null, 2)}</Text>}
      </ScrollView>
      <Button
        title="Log in"
        loading={false}
        loadingProps={{ size: "small", color: "white" }}
        buttonStyle={{
          backgroundColor: "rgba(111, 202, 186, 1)",
          borderRadius: 5,
        }}
        titleStyle={{ fontWeight: "bold", fontSize: 23 }}
        containerStyle={{
          marginHorizontal: 50,
          height: 50,
          width: 200,
          marginVertical: 10,
        }}
        onPress={() => {
          promptAsync();
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    margin: 10,
    marginTop: 20,
  },
});

参考:

希望对 expo 开发, 对接 okta 的开发者有帮助, saved your time.

相关推荐
codingWhat13 小时前
手撸一个「能打」的 React Table 组件
前端·javascript·react.js
程序员ys21 小时前
前端权限控制设计
前端·vue.js·react.js
不会敲代码121 小时前
从零开始用 TypeScript + React 打造类型安全的 Todo 应用
前端·react.js·typescript
小时前端2 天前
React性能优化的完整方法论,附赠大厂面试通关技巧
前端·react.js
阿慧勇闯大前端2 天前
在AI时代,再去了解react19新特性还有用吗? 最近总有朋友问我:“现在AI写代码这么厉害了,我写个需求丢给ChatGPT,几秒钟就生成一堆组件,还学新特
前端·react.js
喵爱吃鱼2 天前
关于我明明用了ref还是陷入React闭包陷阱
前端·react.js
Lupino2 天前
被 React “玩弄”的 24 小时:为了修一个不存在的 Bug,我给大模型送了顿火锅钱
前端·react.js
是梦终空2 天前
React Native 性能优化指南
react native·性能优化
ZengLiangYi3 天前
React 事件订阅的稳定引用问题:从 useEffect 到 useEffectEvent
react.js
LING3 天前
RN容器启动优化实践
android·react native