首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Auth0作为中间件集成到Express.js路由控制器authorizationChecker中

将Auth0作为中间件集成到Express.js路由控制器authorizationChecker中
EN

Stack Overflow用户
提问于 2020-08-26 10:02:52
回答 1查看 511关注 0票数 1

我很难将Auth0的Node (Express) API快速启动转换成中间件变体。特别是使用TypeStack的routing-controllers库,并希望使用它们的装潢工集成Auth0。

app.ts

代码语言:javascript
复制
const app = createExpressServer({

    authorizationChecker: async (action: Action, roles: string[]) => {
        const token = action.request.headers['authorization'];

        // QUESTION: How to validate the bearer token here so it returns true/false
        // + also respect the role ('super-duper-trooper')?

        return true/false;   // <----- this
        
    },

    controllers: [StatusController]
});

status-controller.ts中,我用@Authorized +角色来装饰一个操作:

代码语言:javascript
复制
@Controller()
export class StatusController {

    @Get('/status')
    getAll() {
       return 'OK, anonymously accessible';
    }

    @Authorized('super-duper-trooper')   // <----- that
    @Get('/status/:id')
    getOne(@Param('id') id: string) {
       return 'NOT OK';
    }
}

我的问题是:如何配置authorizationChecker函数,使其既验证令牌又尊重角色(上面示例中的“超级部队”)?

注:我曾尝试将其添加为常规Express.js中间件(app.use(MyMiddleware)),但这是authorizationChecker函数所替代的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-09 07:46:59

我设法让authorizationChecker在Express.js中为路由控制器工作。

我通过合并jsonwebtokenjwks-rsa库实现了这一点。

请参阅验证给定JWT的以下auth函数:

代码语言:javascript
复制
import jwt from 'jsonwebtoken';
import jwksRsa from 'jwks-rsa';

export async function AuthMiddleware(token: string, roles: string[]): Promise<boolean> {
    if (!token) return false;

    // Extracts the bearer token from the request headers
    const bearerToken = token.split(' ')[1];

    // Set up a JWKS client that retrieves the public key from Auth0, this public key will be used to challenge the
    // bearer token against.
    const client = jwksRsa({
        jwksUri: 'https://your_jwks_uri.com/jwks.json' // For example, using Auth0 you can find this in Auth0 Applications -> Advanced Settings -> Endpoints. This should look something like this: https://yourtenant.eu.auth0.com/.well-known/jwks.json
    });
    const getPublicKey = (header: any, callback: any) => {
        client.getSigningKey(header.kid, (err, key) => {
            const signingKey = key.getPublicKey();
            callback(null, signingKey);
        });
    }

    // As jwt.verify cannot be awaited, we construct a promise that we will resolve once the JWT verification has
    // finished. This way, we can simulate awaiting of the JWT verification.
    let jwtVerifyPromiseResolver: (tokenValid: boolean) => void;
    const jwtVerifyPromise = new Promise<boolean>(resolve => {
        jwtVerifyPromiseResolver = resolve;
    });

    const tokenNamespace = 'your_namespace'; // The namespace you have added to the roles in your auth token in an Auth0 rule

    jwt.verify(bearerToken, getPublicKey, {}, (err, decodedJwt: any) => {
        let jwtValid: boolean = false;

        if (err)
            jwtValid = false;
        else {
            // When the requested endpoint requires roles, check if the decoded JWT contains those roles
            if (roles && roles.length > 0) {
                const userRoles = decodedJwt[`${tokenNamespace}roles`];

                if (userRoles)
                    // Token is valid if all roles for request are present in the user's roles
                    jwtValid = roles.every((role) => userRoles.includes(role));
                else
                    // Token does not contain roles, mark token as invalid
                    jwtValid = false;
            }

            jwtValid = true;
        }

        jwtVerifyPromiseResolver(
            jwtValid
        );
    });

    return jwtVerifyPromise;
}

然后,这个函数可以在authorizationToken函数中使用,如下所示:

代码语言:javascript
复制
const app = createExpressServer({
    authorizationChecker: async (action: Action, roles: string[]) => {
        const authorizationToken = action.request.headers['authorization'];

        // Wait for JWT verification to complete, returning whether the token is valid or not
        return await AuthMiddleware(authorizationToken, roles);
    },

    controllers: [StatusController]
});

配置完毕后,您可以使用@Authorize()@Authorize('role')来装饰控制器中的操作,就像您已经在做的那样。这将在对操作的每个请求之前触发authorizationChecker

注意:从端点检索公钥的整个getPublicKey部分也可以替换为在代码中或在某个设置中使用公钥。这样,您也不需要手动创建承诺来等待JWT验证。然而,我认为检索公钥按需是更优雅的解决方案。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63595235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档