oauth-2.0 如何使用supertest和jest测试oAuth2

r7knjye2  于 2022-10-31  发布在  Jest
关注(0)|答案(1)|浏览(279)

我有一个使用不同OpenId授权服务(例如salesforce、google-login、ms-teams等)进行授权的应用程序
现在,我希望实现测试,并尝试使用独立服务器(https://github.com/navikt/mock-oauth2-server)模拟身份验证工作流
我使用标准的openID客户端(https://www.npmjs.com/package/openid-client

/**
 * /AUTH TESTS
 */

describe('GET the auth route', () => {
    test('return 302 when redirect correctly', async () => {
        const response = await api
            .get('/auth')
            .query({ user: 'tester@test.com', oauth: 'testoauth2'})
            .set('Authorization', `${token}`)
            .expect(302)
    })
})

describe('GET the authcallback route', () => {
    test('return content when auth is successful', async () => {
        const response = await api
            .get('/authcallback')
            .set("Cookie", ['oauthKey=testoauth2; nonce=4DwCl4XuvRcckI_7Yv2smA0hnRxQtj2_mU1Q13NbU9A; codeVerifier=c-WoROhqZHBS13rSJ1ePd4O5p4W-_aqB1n3fJSjLXaU; user=tester@test.com' ])
            .set('Authorization', `${token}`)
            .query({
                code: "aPrxi6BfM_yOlkX6zB4nTDQCYgASP_69O.ZCuOWYNe7DyP2UxaNc5ZwtbDsPrG_wnUgvb3WJ8Q=="
            })

    })
})

所以我的问题是:
1.一般来说,是否可以使用supertest测试oAuth2工作流?
1.我错过了什么?错误大多数时候是:“随机数不匹配”
//编辑:
深入研究了这个问题,发现很难用supertest测试oauth工作流。也许Cypress或TestCafe是更好的选择。有人能证实这一点吗?

kiayqfof

kiayqfof1#

我想我自己解决了

describe('test the whole oauth2 workflow', () => {
    test('correctly create new integration after complete workflow', async () => {
        let response = await api
            .get('/auth')
            .query({ user: 'tester@test.com', oauth: 'testoauth2'})
            .set('Authorization', `${token}`)
            .expect(302)

        let cookies = response.headers['set-cookie']

        // we need to try/catch the call to get the correct callback url with the code
        try {
            response = await axios
                .get(response.headers.location, {
                    headers: {
                        Cookie: response.headers['set-cookie']
                    }})
        } catch (e) {
            expect(e.request.path).toContain('authcallback')

            response = await api
                .get(e.request.path)
                .set("Cookie", cookies)
                .set('Authorization', `${token}`)
                .expect(200)
        }

        let integration = await api
            .get('/integration')
            .set('Authorization', `${token}`)
            .query({channel: 'testoauth2'})
            .expect(200)

        expect(integration.text.channel).toBe('testoauth2')
    })
})

trycatch有点笨拙,但否则Cookie不会出现在下一个请求中

相关问题