How to mock OAuth flow? #1368
-
Hey, I understand that MSW is mostly used to mock API endpoints. But I was wondering if it can be used to mock something like when authenticating with slack (https://slack.com/oauth/v2/):
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @cmacdonnacha. Yeah, sure. Authentication also involves API requests to endpoints, so no extra case here. I haven't worked with the Slack API per se but I imagine it's not much different from other OAuth protocols. Here's how I'd mock a GitHub OAuth: rest.get('https://github.com/oauth/v2/authorize', (req, res, ctx) => {
const callbackUrl = new URL('http://localhost:3000/oauth/callback')
callbackUrl.searchParams.set('code', 'abc-123')
// Redirect to the local OAuth callback route with a mock "code".
// The route handler for this callback remains as-is, no need to mock it.
return res(ctx.status(301), ctx.set('Location', callbackUrl))
})
rest.post('https://github.com/oauth/v2/authorize', async (req, res, ctx) => {
const { code } = await req.json()
// Mock a successful authorization payload.
return res(ctx.json({
access_token: mockAccessToken()
})
}) Just keep in mind that MSW intercepts fetch requests. So you cannot intercept a navigation request if your app opens For in-browser flows skip the entire thing and only mock the authorization endpoint of your service (i.e. |
Beta Was this translation helpful? Give feedback.
Hey, @cmacdonnacha.
Yeah, sure. Authentication also involves API requests to endpoints, so no extra case here. I haven't worked with the Slack API per se but I imagine it's not much different from other OAuth protocols.
Here's how I'd mock a GitHub OAuth: