spring-security - 仅使用过滤器即可使用带有 Cookie 的 Spring Security
问题描述
我有一个从 Web 客户端调用的后端应用程序。通过调用,将发送一个 cookie,其中包含一个已由客户端成功验证的会话 ID。
在后端,我只想检查 cookie 发送的 session id 是否有效。(CSRF 也会被考虑)
简单地创建一个过滤器来联系 sso 系统以检查 cookie 中包含的会话 ID 是否还不够?
安全配置:
http.authorizeRequests()
.antMatchers("/api/**").permitAll()
.and()
.addFilter(new SsoFilter(authenticationManager()));
和一个过滤器:
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws
IOException, ServletException {
Cookie[] cookies = request.getCookies();
if(cookies == null || cookies.length == 0){
filterChain.doFilter(request, response);
return;
}
Cookie tokenCookie = null;
for (Cookie cookie : cookies){
if (cookie.getName().equals(COOKIE_NAME)){
tokenCookie = cookie;
}
}
UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(tokenCookie.getValue());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(String token) {
final Useruser= ssoService.validateToken(token);
return new UsernamePasswordAuthenticationToken(user,null, null);
}
解决方案
推荐阅读
- pandas - 具有重叠坐标的 Pandas double(?) groupby
- php - 在 PHP/mysql 中强匹配街道地址的算法
- node.js - NPM:在带有 nvm 的 Windows 10 上运行 npm -v 时找不到 npm-cli.js
- javascript - 需要查看从成功数据到html表格的整个列表元素。(需要查看列表中的所有元素)
- c - 将十进制数转换为二进制
- python - 如何保护从 Django 到 Flask 微服务的通信?
- python - 如何覆盖所有 Auth 内置模板 Django
- azure - 无法在 MS Authenticator 中选择我的帐户
- javascript - 在 Array 中反应条件渲染
- angular - 带有 requestAnimationFrame 问题的 Angular 组件