用户已提交Expo React原生应用程序的oidc身份验证端点

eh57zj3b  于 2022-12-14  发布在  React
关注(0)|答案(1)|浏览(136)

我正在尝试构建一个应用程序,该应用程序能够根据输入的URI连接到不同的oidc端点。
我还没有找到任何关于更改或更新“expo-auth-session”useAuthRequest方法的文档。目标是用户输入他们想要连接的URI,然后AuthSession.makeRedirectUri将生成一个新的redirectUri传递给AuthSession.useAuthRequest()。问题是我不能在钩子中访问AuthSession。
我能做的最理想的事

const connect = async (newURI) =>{
 
const redirectUri = AuthSession.makeRedirectUri({
    useProxy:true,
    projectNameForProxy: `${newURI}`,
    path: '/idp/members'
  });

  const discovery = AuthSession.useAutoDiscovery(`${newURI}`);

  const [request, result, promptAsync] = await AuthSession.useAuthRequest(
    {
      clientId: "ess-next",
      redirectUri,
      scopes:['openid', 'api1'],
    },
    discovery
  );
  promptAsync()

}

扩展到我的应用程序大致有点不同

import {  observer } from "mobx-react-lite"
import React, { FC, useEffect, useState } from "react"
import { translate } from "../i18n"
// import { saveString, loadString } from "../utils/storage/storage";
import { MaterialCommunityIcons  } from "@expo/vector-icons";
import {
  Text,
} from "../components"

import { Box, Input, Image, Flex, Button, FlatList, HStack, VStack, IconButton, Icon, Spacer, Pressable } from "native-base"
import { StackScreenProps } from "@react-navigation/stack"
import { AppStackScreenProps } from "../navigators"
import { useStores } from "../models";
import * as AuthSession from 'expo-auth-session';

// import { prefetchConfiguration, authorize  } from "react-native-app-auth";
// import * as WebBrowser from 'expo-web-browser';

// const useProxy = true;
// import { toJS } from "mobx";
const appIcon = require("../../assets/images/icon.png")

export const WelcomeScreen: FC<StackScreenProps<AppStackScreenProps<'Welcome'>>>  = observer(function WelcomeScreen(_props) { 
  const { uriStore, authStore } = useStores()
  const { history, lastConnectedUri } = uriStore
  const [ uriInput, setUriInput ] = useState("")
  // const [ loadingStore, setLoadingStore ] = useState(false)

  
  const redirectUri = AuthSession.makeRedirectUri({
    useProxy:true,
    projectNameForProxy: `${lastConnectedUri}`,
    path: '/idp/members'
  });

  const discovery = AuthSession.useAutoDiscovery(`${lastConnectedUri}`);

  const [request, result, promptAsync] = AuthSession.useAuthRequest(
    {
      clientId: "ess-next",
      redirectUri,
      scopes:['openid', 'api1'],
    },
    discovery
  );

  useEffect(() => {
    // handleAuthorize()
    console.log('effect ');
    setUriInput(lastConnectedUri)
  }, [])
  
  const connect: any = async (uri: string) => {
    const record = uriStore.history.filter(i => i.id === uri)[0]
    await uriStore.connect(record)
    setUriInput(uri)
    
    // const x = await authStore.setAuthToken()
    // console.log(x);
    
  }

  const connectBtn: any = async (uri) => {
    console.log('connect btn', uriStore);
    await uriStore.addUri(uri)          
    connect(uri)
  }

  return (
    <Box _dark={{ bg: "coolGray.800" }} _light={{ bg: "warmGray.50" }} h="100%" >
      <Flex  px="5" pb="2" mt="50px" mb="3" mx="3" alignItems="center" 
        borderWidth="1"
        borderRadius="4"
        borderColor="gray.300" >
        <Image size={150} source={appIcon} resizeMode="contain" alt="logo" />
        <Text mb="3"
            tx="welcomeScreen.header"
            preset="heading" />
        <Text tx="welcomeScreen.instructions" />
        <Input placeholder={ translate('common.uri') } h="50px" w="100%" bg="white" my="5" 
              value={uriInput}
              onChangeText={setUriInput} />
        <Button rounded="2" w="100%" pt="5" h="50px" mb="2"
          onPress={ () => connectBtn(uriInput) } 
            > 
          { translate('common.connect') } </Button>
      </Flex>
      <Text p="3" preset="heading" tx="common.history"/>
        <FlatList
        data={[...history]}
        flex="1"
        renderItem={({item}) => 
              <Pressable p="2" mx="3" mb="1.5"
              borderWidth="1"
              borderRadius="4"
              borderColor="gray.300" onPress={ ()=>{ connect(item.id) } }>
                <HStack  space="3" alignItems="center">
                  <VStack>
                    <Text preset="subheading">{item.id}</Text>
                    <HStack>
                      <Text tx="common.added"></Text>
                      <Text>: {item.created?.toLocaleString()}</Text>
                    </HStack>
                    <HStack  alignItems="center"> 
                      {/* <Text tx="common.lc"></Text>
                      <Text  fontSize="xs">: {item.lastConnected?.toLocaleString()}</Text> */}
                    </HStack>                              
                  </VStack>
                  <Spacer/>
                  <IconButton icon={<Icon as={MaterialCommunityIcons} name="delete" onPress={()=>{ uriStore.removeUri(item) }} />}
                    _icon={{ color: "error.700", size: "lg" }}/>
                </HStack>
              </Pressable>
          }
      />
    </Box>
    )
})
ia2d9nvy

ia2d9nvy1#

解决了我想用这个

import {  observer } from "mobx-react-lite"
import React, { FC, useEffect, useState } from "react"
import { translate } from "../i18n"
// import { saveString, loadString } from "../utils/storage/storage";
import { MaterialCommunityIcons  } from "@expo/vector-icons";
import {
  Text,
} from "../components"

import { Box, Input, Image, Flex, Button, FlatList, HStack, VStack, IconButton, Icon, Spacer, Pressable } from "native-base"
import { StackScreenProps } from "@react-navigation/stack"
import { AppStackScreenProps } from "../navigators"
import { useStores } from "../models";
import * as AuthSession from 'expo-auth-session';

// import { prefetchConfiguration, authorize  } from "react-native-app-auth";
// import * as WebBrowser from 'expo-web-browser';

// const useProxy = true;
// import { toJS } from "mobx";
const appIcon = require("../../assets/images/icon.png")

export const WelcomeScreen: FC<StackScreenProps<AppStackScreenProps<'Welcome'>>>  = observer(function WelcomeScreen(_props) { 
  const { uriStore, authStore } = useStores()
  const { history, lastConnectedUri } = uriStore
  const [ uriInput, setUriInput ] = useState("")
  // const [ loadingStore, setLoadingStore ] = useState(false)

  useEffect(() => {
    // handleAuthorize()
    console.log('effect ');
    setUriInput(lastConnectedUri)
  }, [])
  
  const connect: any = async (uri: string) => {
    const record = uriStore.history.filter(i => i.id === uri)[0]
    await uriStore.connect(record)
    setUriInput(uri)
    
    const redirectUri = AuthSession.makeRedirectUri({
      useProxy:true,
      projectNameForProxy: `https://${uri}.attendanceondemand.com/`,
      path: '/idp/members'
    });

    const disc = await AuthSession.fetchDiscoveryAsync(`https://${uri}.attendanceondemand.com/idp/members`)
      .catch(err => {
        // invalid uri
        console.log(err);
        console.log('uri no longer valid');
      });
  
    if(disc){
      console.log(disc);
      const response = await AuthSession.loadAsync({
        clientId: "ess-dev",
        scopes:['openid', 'api1'],
        redirectUri,
        
        }, disc);
        console.log(response);
        const loginResponse = await response.promptAsync(disc)
        console.log('after login');
        console.log(loginResponse);
      }
  }
  
  const connectBtn: any = async (uri) => {
    console.log('connect btn', uriStore);
    const disc = await AuthSession.fetchDiscoveryAsync(`https://${uri}.attendanceondemand.com/idp/members`)
      .catch(err => {
        // invalid uri
        console.log(err);
        console.log('invalid uri');
      });
    
    if(disc){
      console.log(disc);
      await uriStore.addUri(uri)          
      connect(uri)
    }
  }

  return (
    <Box _dark={{ bg: "coolGray.800" }} _light={{ bg: "warmGray.50" }} h="100%" >
      <Flex  px="5" pb="2" mt="50px" mb="3" mx="3" alignItems="center" 
        borderWidth="1"
        borderRadius="4"
        borderColor="gray.300" >
        <Image size={150} source={appIcon} resizeMode="contain" alt="logo" />
        <Text mb="3"
            tx="welcomeScreen.header"
            preset="heading" />
        <Text tx="welcomeScreen.instructions" />
        <Input placeholder={ translate('common.uri') } h="50px" w="100%" bg="white" my="5" 
              value={uriInput}
              onChangeText={setUriInput} />
        <Button rounded="2" w="100%" pt="5" h="50px" mb="2"
          onPress={ () => connectBtn(uriInput) } 
            > 
          { translate('common.connect') } </Button>
      </Flex>
      <Text p="3" preset="heading" tx="common.history"/>
        <FlatList
        data={[...history]}
        flex="1"
        renderItem={({item}) => 
              <Pressable p="2" mx="3" mb="1.5"
              borderWidth="1"
              borderRadius="4"
              borderColor="gray.300" onPress={ ()=>{ connect(item.id) } }>
                <HStack  space="3" alignItems="center">
                  <VStack>
                    <Text preset="subheading">{item.id}</Text>
                    <HStack>
                      <Text tx="common.added"></Text>
                      <Text>: {item.created?.toLocaleString()}</Text>
                    </HStack>
                    <HStack  alignItems="center"> 
                      {/* <Text tx="common.lc"></Text>
                      <Text  fontSize="xs">: {item.lastConnected?.toLocaleString()}</Text> */}
                    </HStack>                              
                  </VStack>
                  <Spacer/>
                  <IconButton icon={<Icon as={MaterialCommunityIcons} name="delete" onPress={()=>{ uriStore.removeUri(item) }} />}
                    _icon={{ color: "error.700", size: "lg" }}/>
                </HStack>
              </Pressable>
          }
      />
    </Box>
    )
})

相关问题