如何在React Native中实现Microsoft Azure单点登录(SSO)?需含代码示例
React Native 集成 Microsoft Azure 单点登录(SSO) 实战指南
一、前置准备
- 拥有Microsoft Azure AD租户(可免费注册)
- 已创建React Native项目(支持0.60+版本)
- 在Azure Portal中完成应用注册:
- 进入Azure AD -> 应用注册 -> 新建注册
- 填写应用名称,选择支持的账户类型(建议选"任何组织目录中的账户和个人Microsoft账户")
- 注册完成后,记录应用程序(客户端)ID和目录(租户)ID
二、安装依赖
使用微软官方维护的react-native-msal库,执行安装命令:
# npm npm install @azure/msal-react-native --save # yarn yarn add @azure/msal-react-native
平台额外配置
iOS端
- 打开
ios/[项目名]/Info.plist,添加以下配置:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <!-- 格式:msal+客户端ID --> <string>msalxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</string> </array> </dict> </array> <key>LSApplicationQueriesSchemes</key> <array> <string>msauthv2</string> <string>msauthv3</string> </array>
- 执行
cd ios && pod install完成依赖安装
Android端
- 打开
android/app/src/main/AndroidManifest.xml,在<application>标签内添加:
<!-- 重定向Activity配置 --> <activity android:name="com.microsoft.identity.client.BrowserTabActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 格式:msal+客户端ID://auth --> <data android:scheme="msalxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" /> </intent-filter> </activity>
- 生成并配置签名哈希:
- 执行命令生成调试哈希:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 - 将生成的哈希值填入Azure应用注册的Android平台配置中
- 执行命令生成调试哈希:
三、核心代码实现
1. 初始化MSAL实例
在项目根目录创建MsalConfig.js,配置MSAL客户端:
import { PublicClientApplication, Configuration } from '@azure/msal-react-native'; import { Platform } from 'react-native'; const config: Configuration = { auth: { clientId: '你的客户端ID', authority: 'https://login.microsoftonline.com/你的租户ID', // 用common可支持个人账户 redirectUri: Platform.OS === 'ios' ? 'msal你的客户端ID://auth' : 'msal你的客户端ID://auth', }, cache: { cacheLocation: 'secureStorage', // 使用安全存储缓存token storeAuthStateInCookie: false, }, }; const pca = new PublicClientApplication(config); export default pca;
2. 封装认证逻辑
创建AuthService.js封装登录、登出、账户查询功能:
import pca from './MsalConfig'; import { InteractionType, AuthError } from '@azure/msal-react-native'; // 登录函数 export const signIn = async () => { try { const result = await pca.acquireToken({ interactionType: InteractionType.Popup, // 弹窗式登录,也可使用Redirect scopes: ['User.Read', 'openid', 'profile'], // 请求的权限范围 }); if (result.accessToken) { console.log('登录成功,Access Token:', result.accessToken); return result.account; } } catch (error) { if (error instanceof AuthError) { console.error('登录错误:', error.errorMessage); } else { console.error('未知错误:', error); } throw error; } }; // 获取当前已登录账户 export const getCurrentAccount = async () => { const accounts = await pca.getAllAccounts(); return accounts.length > 0 ? accounts[0] : null; }; // 登出函数 export const signOut = async () => { const account = await getCurrentAccount(); if (!account) return; try { await pca.signOut({ account, postLogoutRedirectUri: 'msal你的客户端ID://auth', }); console.log('登出成功'); } catch (error) { console.error('登出错误:', error); throw error; } };
3. 组件中调用认证功能
创建AuthScreen.js组件,实现登录/登出UI交互:
import React, { useState, useEffect } from 'react'; import { View, Button, Text, StyleSheet } from 'react-native'; import { signIn, signOut, getCurrentAccount } from './AuthService'; const AuthScreen = () => { const [user, setUser] = useState(null); useEffect(() => { // 组件加载时检查登录状态 checkAuthStatus(); }, []); const checkAuthStatus = async () => { const account = await getCurrentAccount(); setUser(account); }; const handleSignIn = async () => { try { const account = await signIn(); setUser(account); } catch (error) { alert('登录失败,请重试'); } }; const handleSignOut = async () => { try { await signOut(); setUser(null); } catch (error) { alert('登出失败,请重试'); } }; return ( <View style={styles.container}> {user ? ( <> <Text style={styles.userInfo}>欢迎,{user.name}</Text> <Text style={styles.userInfo}>邮箱:{user.username}</Text> <Button title="登出" onPress={handleSignOut} /> </> ) : ( <Button title="使用Microsoft账户登录" onPress={handleSignIn} /> )} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20, }, userInfo: { fontSize: 16, marginBottom: 10, }, }); export default AuthScreen;
四、测试验证
- 运行React Native项目:
# iOS npx react-native run-ios # Android npx react-native run-android
- 点击登录按钮,弹出Microsoft登录界面,输入账户密码完成登录
- 验证用户信息是否正确显示,登出功能是否正常执行
内容的提问来源于stack exchange,提问作者Rifah Salik
相关产品推荐
相关产品推荐

