【发布时间】:2022-02-08 10:18:33
【问题描述】:
我很难使用 cookie。当我的 NextJS 应用程序向我的后端发出 /login 请求时,我在响应中发送和 Http-Only cookie,我认为它将保存在 Cookie 存储中,并且可以在 req.headers.cookie 上使用我的 NextJS 应用程序上的 ServerSideProps,但我的 cookie 从未设置,即使它们出现在我后端的 /login 响应中。
我向我的网关微服务发出请求,然后将其重定向到我的安全微服务,在该安全微服务中,我像这样编写 cookie 并在其中保存 JWT:
Cookie cookie = new Cookie("Authentication", token);
cookie.setMaxAge(28800);
cookie.setSecure(false); //TODO: Change this to false or true depending on dev or prod
cookie.setPath("/");
cookie.setHttpOnly(true);
response.addCookie(cookie);
response.addHeader(AUTH_HEADER_KEY, TOKEN_PREFIX + token);
那么当我的前端执行 /login POST 请求时,我的后端的响应是这样的:
但永远不会保存在我的浏览器中的存储中,如下所示:
在我的 ServerSideProps Next 函数上请求它们时也没有:
export const getServerSideProps: GetServerSideProps = async ({
locale,
req,
}) => {
const cookies = req.headers.cookie;
console.log('Cookies: ', cookies);
return {
props: {
...(await serverSideTranslations(locale ? locale : 'es', ['dashboard'])),
},
};
};
我对 /login 的请求在前端如下所示:
const loginUserMutation = useMutation(
({ email, password }: UserLogin) => {
return axios.post(process.env.NEXT_PUBLIC_DEV_DOMAIN_URL + '/login', {
email,
password,
});
},
{
onSuccess: (data) => {
const loggedUser: LoggedUser = {
role: data.data.role,
email: data.data.email,
token: data.headers.authorization,
};
saveUserInContext(loggedUser);
router.push('/');
},
}
);
我还能做什么?我的 NextJS 应用程序位于 localhost:3000,我的网关位于 localhost:4010,我的安全微服务位于 localhost:4020
编辑:
发现如果在我的 CORS 配置中添加此行,它将起作用,并且还可以在我的前端使用 allowCredentials。但是请注意,我的 Spring Cloud Gateway 微服务正在破坏我的标头,所以我仍然需要调查它,但如果您遇到同样的问题,请尝试直接使用您的端点。
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final var source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
source.registerCorsConfiguration("/**", corsConfiguration.applyPermitDefaultValues());
corsConfiguration.setExposedHeaders(List.of("Authorization", "Set-Cookie"));
corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000"));
corsConfiguration.setAllowCredentials(true);
return source;
}
【问题讨论】:
标签: java spring cookies spring-security next.js