I'm trying to get Cookies work with my new Angular 17 project. I have a route like /person/1/edit and it is protected with a guard like this:
export function authenticationGuard(): CanActivateFn {
return () => {
const authService: AuthService = inject(AuthService);
const router: Router = inject(Router);
const cookieService: SsrCookieService = inject(SsrCookieService);
return authService.getUser().pipe(
map((x) => {
const bearerToken = cookieService.get('access_token');
console.log('Bearer Token: ' + bearerToken);
if (x.role !== 'admin') {
router.navigate(['/home']);
return false;
}
return true;
})
);
};
}
When I directly open the route /person/1/edit in the browser I'm redirected to /home because the cookie is not set (e.g. the bearer token is empty).
I installed ngx-cookie-service-ssr and setup the part of the server.ts like similar to the documentation of the cookie ssr package:
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: 'REQUEST', useValue: req },
{ provide: 'RESPONSE', useValue: res },
],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
Sadly this does not work and the cookie is always empty on the server side even though I have a cookie in the frontend. Has anyone an idea what I could be doing wrong?
Maybe the server.ts part is wrong because the docs still have examples on how to do it with angular universal instead of the new Angular 17 SSR.
