身份提供商通常使用OAuth 2.0和OpenID Connect这两个协议来验证和授权用户请求。以下是一个使用Auth0的示例:
import auth0 from 'auth0-js';
const webAuth = new auth0.WebAuth({
domain: 'YOUR_AUTH0_DOMAIN',
clientID: 'YOUR_AUTH0_CLIENT_ID',
redirectUri: 'https://your-app.com/callback',
responseType: 'token id_token',
scope: 'openid profile email'
});
function login() {
webAuth.authorize();
}
// After successful login, use the returned access token to authenticate requests to the backend
const accessToken = localStorage.getItem('access_token');
function getData() {
fetch('https://api.your-backend.com/data', {
headers: {
Authorization: `Bearer ${accessToken}`
}
}).then(response => {
// handle response
});
}
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
}),
audience: 'YOUR_API_IDENTIFIER',
issuer: `https://YOUR_AUTH0_DOMAIN/`,
algorithms: ['RS256']
});
app.get('/data', checkJwt, (req, res) => {
// handle request
});
类似地,Cognito使用JSON Web Token(JWT)来验证和授权用户请求。要在前端应用中获取访问令牌并将其附加到请求头中,您可以使用AWS Amplify,这是一个适用于JavaScript和React的开发库。您可以从AWS控制台或AWS CLI中创建Cognito用户池,然后使用以下代码示例:
import Amplify from 'aws-amplify';
import { withAuthenticator } from 'aws-amplify-react';
Amplify.configure({
Auth: {
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_USER_POOL_WEB_CLIENT_ID',
region: 'YOUR_REGION'
}
});
// The withAuthenticator HOC will automatically handle authentication and provide the necessary token for requests
function getData() {
fetch('https://api.your-backend.com/data', {
headers: {
Authorization: `Bearer ${auth.accessToken}`
}
}).then(response => {
// handle response
});
}
export default withAuthenticator(App);
在后端应用中,您可以使用AWS SDK来验证JWT:
const AWS = require('aws-sdk');
const jwksClient = require('jwks-rsa');
const jwtClient = jwksClient({
cache: true,
jwksUri: `https://cognito-idp.${AWS_REGION}.amazonaws.com/${USER_POOL_ID}/.well-known/jwks.json`
});
function getKey(header, callback) {
jwtClient.getSigningKey(header.kid, function(err, key) {
const signingKey = key.publicKey || key.rsaPublicKey;
callback(null