I based my sample on this: https://github.com/oauthjs/express-oauth-server/blob/master/examples/postgresql/index.js
However when I try to visit the /public route, I get a 401. The URL I'm accessing is http://localhost:8080/public?client_id=1234&redirect_uri=http%3A%2F%2Flocalhost:4000&response_type=code&scope=email
Here's my index.ts:
var expressApp = require('express')
import express from 'express'
import OAuthServer from 'express-oauth-server'
import {AuthorizationCode, Client, User} from 'oauth2-server'
const app = expressApp()
app.oauth = new OAuthServer({
model: {
getClient: async (clientId: string, clientSecret: string) => {
console.log('Reached getClient')
if (clientId !== '1234')
return null
if (clientSecret && clientSecret !== 'abcd')
return null
return {
id: clientId,
redirectUris: ["http://localhost:4000", "http://localhost:5000"],
grants: ["authorization_code", "refresh_token"],
accessTokenLifetime: 3600 * 24, // 1 day
refreshTokenLifetime: 3600 * 24 * 30, // 30 days
}
},
saveAuthorizationCode: async (code: AuthorizationCode, client: Client, user: User) => {
console.log('Reached saveAuthorizationCode')
return {
authorizationCode: code.authorizationCode,
expiresAt: code.expiresAt,
redirectUri: code.redirectUri,
scope: code.scope,
client: client,
user: user,
}
},
getAccessToken: async (accessTokenKey: string) => {
console.log('Reached getAccessToken')
if (accessTokenKey.startsWith('XYZ'))
return null
const expiry_date = new Date()
expiry_date.setHours(expiry_date.getHours() + 1)
return {
accessToken: accessTokenKey,
accessTokenExpiresAt: expiry_date,
scope: ["email", "profile", "openid"],
client: {
id: '1234',
redirectUris: ["http://localhost:4000", "http://localhost:5000"],
grants: ["authorization_code", "refresh_token"],
accessTokenLifetime: 3600 * 24, // 1 day
efreshTokenLifetime: 3600 * 24 * 30, // 30 days
},
user: {
id: 234567,
email: '[email protected]',
},
}
},
} as any, // Just to avoid TS errors to test sample.
//continueMiddleware: true,
})
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(app.oauth.authorize())
const port = 8080
app.listen(port, () => {
console.log('Running server at port ' + port + '...')
})
// Endpoints
app.get('/public', function(_req: any, res: any) {
console.log('Reached /public')
res.send('Public area')
});
"Reached /public" never gets printed. If I remove app.use(app.oauth.authorize()), it works.
What am I missing?
This was pretty much due to the way middleware ordering works in Express. The line app.use(app.oauth.authorize()) coming before the public route ensures that the request to this route goes via the authorize middleware first.