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.

相关推荐
Highcharts.js1 天前
Highcharts Orbit 完全指南:把每一张图表变成交互式分析工具
react.js·前端框架·highcharts·orbit·使用指南·ai 图表·交互式分析工具
鸿蒙开发2 天前
小程序存档写到一半怎么办?双槽保存与损坏恢复实战
前端·javascript·react.js
古茗前端团队4 天前
由 key 引发的思考
前端·javascript·react.js
用户298698530147 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel
終不似少年遊*8 天前
【安全业务Agent】从场景到编排
python·react.js·ai·langchain·agent·安全架构·工作流
JavaPub-rodert8 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
Highcharts.js9 天前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
JudithHuang9 天前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
前端小D9 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
大龄秃头程序员10 天前
从源码里看懂 React Native 新架构:TurboModule 与 Fabric 到底是怎么跑起来的?
react native