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.

相关推荐
PleaSure乐事5 小时前
【React.js】AntDesignPro左侧菜单栏栏目名称不显示的解决方案
前端·javascript·react.js·前端框架·webstorm·antdesignpro
getaxiosluo5 小时前
react jsx基本语法,脚手架,父子传参,refs等详解
前端·vue.js·react.js·前端框架·hook·jsx
新星_6 小时前
函数组件 hook--useContext
react.js
阿伟来咯~8 小时前
记录学习react的一些内容
javascript·学习·react.js
吕彬-前端8 小时前
使用vite+react+ts+Ant Design开发后台管理项目(五)
前端·javascript·react.js
学前端的小朱8 小时前
Redux的简介及其在React中的应用
前端·javascript·react.js·redux·store
bysking9 小时前
【前端-组件】定义行分组的表格表单实现-bysking
前端·react.js
September_ning13 小时前
React.lazy() 懒加载
前端·react.js·前端框架
web行路人13 小时前
React中类组件和函数组件的理解和区别
前端·javascript·react.js·前端框架
番茄小酱00113 小时前
Expo|ReactNative 中实现扫描二维码功能
javascript·react native·react.js