React Native Expo:使用Identity Server 4进行身份验证

问题描述

我正在尝试使用EXPO文档“ https://docs.expo.io/guides/authentication/”中的Identity Server4示例代码。我已经从ASP.NET Core Web Application创建了一个React模板。当我运行react native应用程序重定向到ASP应用程序的登录页面时,我可以登录,但是问题是窗口没有关闭以返回令牌。登录后,我进入ASP应用程序的主页。我相信我缺少重定向URL或客户端未正确设置方式。有人可以帮我设置吗?还是我缺少什么部分?

这是从appsettings.json中的ASP应用程序设置的客户端:

"IdentityServer": {
    "Clients": {
      "AAA": {
        "ClientId": "myclientid,"ClientName": "Native Client (Code with PKCE)","RequireClientSecret": false,"RedirectUris": [ "io.expo.auth/@username/Auth" ],"AllowedGrantTypes": "GrantTypes.Code","RequirePkce": "true","AllowedScopes": ['openid','profile','email','offline_access'],"AllowOfflineAccess": "true","Profile": "IdentityServerSPA","ClientSecrets": [
          {
            "Value": "secretvalue"
          }
        ]
      }
    },

以下是我的React Native应用:

import * as React from 'react';
import { Button,Text,View } from 'react-native';
import * as AuthSession from 'expo-auth-session';
import * as Webbrowser from 'expo-web-browser';

Webbrowser.maybeCompleteAuthSession();

const useProxy = true;

const redirectUri = AuthSession.makeRedirectUri({
  native: 'myApp://io.expo.auth/@username/Auth',useProxy,});

export default function App() {
  const discovery = AuthSession.useAutodiscovery('https://demo.identityserver.io');
  
  // Create and load an auth request
  const [request,result,promptAsync] = AuthSession.useAuthRequest(
    {
      clientId: 'myclientid',redirectUri,scopes: ['openid',},discovery
  );

  return (
    <View style={{ flex: 1,justifyContent: 'center',alignItems: 'center' }}>
      <Button title="Login!" disabled={!request} onPress={() => promptAsync({ useProxy })} />
      {result && <Text>{JSON.stringify(result,null,2)}</Text>}
    </View>
  );
}

解决方法

这是您需要修复的代码:

  1. 在appsettings.json上将RedirectUris更改为列表,结果将如下所示:
"IdentityServer": {
    "Clients": {
      "AAA": {
        "ClientId": "myclientid,"ClientName": "Native Client (Code with PKCE)","RequireClientSecret": false,"RedirectUris": [ "io.expo.auth/@username/Auth" ],"AllowedGrantTypes": "GrantTypes.Code","RequirePkce": "true","AllowedScopes": [ "api" ],"AllowOfflineAccess": "true","Profile": "IdentityServerSPA","ClientSecrets": [
          {
            "Value": "secretvalue"
          }
        ]
      }
    },

了解更多here

  1. 确保存在RedirectUris上列出的URL,并且该URL与在本机客户端上为redirectUri设置的值匹配。我不是博览会专家,您可能会使用某种中间件,但是据我从您的代码中了解,这些URL不匹配。
,

@nahidf:我已经从react native和ASP应用程序更新了URL。在android应用程序上登录仍然可以,但是在我登录后,该应用程序仍与该ASP应用程序的主页保持打开状态,并且不会关闭以返回react app并返回令牌。博览会应用程序是否必须发布,因为我是在本地运行的?另外,我已经在本地服务器上发布了ASP。