【发布时间】:2022-10-15 21:42:45
【问题描述】:
我正在尝试将Oauth2 authentication (passport-oauth2) 和Dex 实现到我的Node.js。
如果我在 docker 容器中运行我的 API,我会得到:Error: connect ECONNREFUSED 127.0.0.1:80。在码头外它工作得很好!
我的 API 在端口 3000 上运行,Dex 在端口 5556 上运行。我使用 nginx 代理传递这些服务。
所以localhost/dex 将访问 dex
localhost/node_api 将访问我的 API 而无需指定端口。
我的相关 API 代码:
app.use(session({
secret: 'XXXX',
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
const oAuthStrategy = new OAuth2Strategy({
issuer: 'http://localhost/dex',
authorizationURL: 'http://localhost/dex/auth',
tokenURL: 'http://localhost/dex/token',
token_endpoint: 'http://localhost/dex/token',
clientID: 'example-app',
clientSecret: 'XXXX',
callbackURL: 'http://localhost/login/callback',
scope: 'openid email',
}, ((accessToken, refreshToken, params, profile, cb) => {
console.log(`params: ${params}`);
console.log(profile);
return cb(null, profile);
}));
passport.use(oAuthStrategy);
passport.serializeUser((user, next) => {
console.log('serializeUser');
console.log(user);
next(null, user);
});
passport.deserializeUser((obj, next) => {
console.log('deserializeUser');
next(null, obj);
});
app.use('/login', passport.authenticate('oauth2'));
app.use('/login/callback', passport.authenticate('oauth2', { failureRedirect: '/error' }), (req, res) => {
res.redirect('/loggedin');
});
相关 docker-compose.yml 代码:
dex:
image: dexidp/dex
volumes:
- ./config-ldap.yaml:/etc/dex/config.docker.yaml
labels:
- traefik.enable=true
- traefik.http.routers.dex.entryPoints=https
- traefik.http.routers.dex.rule=PathPrefix(`/dex`)
- traefik.http.routers.dex.tls=true
- traefik.http.services.dex.loadbalancer.server.port=5556
node_api:
image: xxxxx
build:
./node_api
depends_on:
- timescaledb
environment:
TS_USER: xxx
TS_PASSWORD: xxx
TS_DB: xxx
TS_DOMAIN: timescaledb
restart: always
labels:
- traefik.enable=true
- traefik.http.routers.node_api.entryPoints=https
- traefik.http.routers.node_api.rule=PathPrefix(`/node_api`)
- traefik.http.routers.node_api.tls=true
- traefik.http.services.node_api.loadbalancer.server.port=3000
nginx.conf:
server {
listen 80;
server_name nginx;
# this is the internal Docker DNS, cache only for 30s
resolver 127.0.0.11 valid=30s;
location /node_api/ {
set $upstream http://node_api:3000;
# nginx will also start if host is not reachable
proxy_pass $upstream;
}
location /dex/ {
set $upstream http://dex:5556;
# nginx will also start if host is not reachable
proxy_pass $upstream;
}
}
帮助高度赞赏!
【问题讨论】:
标签: node.js docker authentication passport.js