使用OAuth 2.0和OpenID Connect实现两个不同的身份提供者,以保护SPA调用两个不同的资源服务器。
代码示例:
在SPA中使用OAuth 2.0和OpenID Connect来保护资源服务器:
import { UserManager } from 'oidc-client';
const userManager1 = new UserManager({
authority: 'https://authority1.com',
client_id: 'client_id1',
redirect_uri: 'https://your-spa-url.com/callback1',
response_type: 'code',
scope: 'openid profile',
automaticSilentRenew: true,
silent_redirect_uri: 'https://your-spa-url.com/silent-callback1',
});
const userManager2 = new UserManager({
authority: 'https://authority2.com',
client_id: 'client_id2',
redirect_uri: 'https://your-spa-url.com/callback2',
response_type: 'code',
scope: 'openid profile',
automaticSilentRenew: true,
silent_redirect_uri: 'https://your-spa-url.com/silent-callback2',
});
// 调用第一个资源服务器
userManager1.signinRedirect();
// 在回调函数中查询令牌并使用它调用第一个资源服务器
userManager1.signinRedirectCallback().then(() => {
userManager1.getUser().then((user) => {
const token = user.access_token;
// 使用令牌调用第一个资源服务器
});
});
// 调用第二个资源服务器
userManager2.signinRedirect();
// 在回调函数中查询令牌并使用它调用第二个资源服务器
userManager2.signinRedirectCallback().then(() => {
userManager2.getUser().then((user) => {
const token = user.access_token;
// 使用令牌调用第二个资源服务器
});
});