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); 会在 useAuthRequest 与 exchangeCodeAsync 中用到. 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.

相关推荐
低代码布道师1 小时前
第06篇:用户新增——React Hook Form + Zod 搭建可复用的表单体系
前端·react.js·前端框架
打工仔折腾 AI2 小时前
智能体开发实战:Agent架构拆解与ReAct执行循环工程落地
前端·后端·python·react.js·架构·langchain·ai agent 实战
黑臂麒麟4 小时前
【鸿蒙心迹】React Native 鸿蒙平板形态适配实战:键盘避让、挖孔安全区与主从栏切换
react native·harmonyos·响应式设计·平板·rnon
黑臂麒麟4 小时前
React Native 鸿蒙升级 RNOH 0.84 实战:TurboModule 注册方式怎么迁
react native·harmonyos·rnoh·turbomodule
少年的范儿6 小时前
React Native + Expo 实战 14|管理远端列表:缓存、刷新与分页
react native·react.js·缓存
少年的范儿6 小时前
React Native + Expo 实战 13|实现登录:会话恢复、过期处理与账号隔离
javascript·react native·react.js
码哥字节20 小时前
Remotion Skills:用 React 代码做视频,简直太爽了
react.js
黑臂麒麟1 天前
React Native 鸿蒙安全存储实战(下):HUKS 密钥托管的加解密与签名验签,四个真机差异实录
安全·react native·harmonyos·加密
黑臂麒麟1 天前
React Native 鸿蒙平板响应式实战:旋转、自由多窗、方向锁定的一次性全清单
react native·harmonyos·响应式设计·平板
传奇开心果编程1 天前
【六大移动UI框架比较学与练】第5课:交互与导航——事件处理、手势与页面路由实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack