npm install openid-client
// 发布者
import { Issuer } from 'openid-client';
// 发布者地址
const googleIssuer = await Issuer.discover('https://xxxxxxx.com');
console.log('Discovered issuer %s %O', googleIssuer.issuer, googleIssuer.metadata);
const client = new googleIssuer.Client({
client_id: 'xxxxxx', // 客户端id
client_secret: 'xxxxxxx', // 客户端密码
redirect_uris: ['http://localhost:3000/cb'], // 回调地址
response_types: ['code'], // 响应类型code、token、id_token、id_token token、code id_token、code token、code id_token token
// id_token_signed_response_alg (default "RS256")
// token_endpoint_auth_method (default "client_secret_basic")
});
import { generators } from 'openid-client';
const code_verifier = generators.codeVerifier();
// 如果是基于cookie的解决方案,则将code_verifier存储在框架的会话机制中
// 它应该是httpOnly(不能被javascript读取)并且加密。
const code_challenge = generators.codeChallenge(code_verifier);
client.authorizationUrl({
scope: 'openid email profile',
resource: 'http://xxx.com/resource/32178', // 可不写
code_challenge,
code_challenge_method: 'S256',
});
const params = client.callbackParams(req);
const tokenSet = await client.callback('http://xxxxxx.com/callback', params, { code_verifier });
console.log('received and validated tokens %j', tokenSet);
console.log('validated ID Token claims %j', tokenSet.claims());
const userinfo = await client.userinfo(access_token);
console.log('userinfo %j', userinfo);
const tokenSet = await client.refresh(refresh_token);
console.log('refreshed and validated tokens %j', tokenSet);
console.log('refreshed ID Token claims %j', tokenSet.claims());
openid-client处理起来简单方便,适合koa/express为服务器的前端接口项目。使用过程中,遇到问题请留意或私信。