我有一个nodejs作为后端来管理会话。 我想在客户端(角度)中使用authGuard,其canActivateChild可以从服务器接收响应。在后端服务器中,我还需要设置响应,以免被http unauthorize所未经授权。 这是我的代码: nodejs: sessionMng-与服务器相关的功能:
module.exports =
{
getUserSession : function (req, res)
{
if (req.session && req.session.user)
{
res.status(200).json(req.session.user);
}
else{
res.sendStatus(403);
}
},
hasSession : function(req, res, next)
{
if (req.session.user != null)
{
res.status(200).send(true); // Removing that make the response has 403 error code
return true;
}
else
{
res.status(403).send(false);
return false;
}
}
}
session.js-客户端的端点:
const express = require('express');
const router = express.Router();
var sessionMgr = require('sessionMgr');
router.use("/", (req, res, next) => {
sessionManagement.getUserSession(req, res, next);
next();
});
router.use("/hasSession", (req, res, next) => {
return sessionMgr.hasSession(req, res, next);
});
module.exports = router;
客户端CanActivateChild:
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivateChild {
constructor(private sessionSrv : sessionService) { }
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean>
{
return this.sessionSrv.hasSession(); //not working
//return true; // works
//return of(true);//also works
}
}
具有适用于服务器“ hasSession”功能的功能的服务:
hasSession() : Observable<boolean>
{
var path = `.../session/hasSession`;
const options = { withCredentials: true };
return this.http.get<any>(path, options);
}