spring - Spring Security 与微服务的问题
问题描述
项目分为----API网关(Zuul)---身份验证服务(登录/注册,生成JWT令牌)---CaclulateFees服务---计算服务我需要使用JWT在身份验证服务上生成令牌(即好的)在执行该方法之前,我需要在其他服务上验证令牌。
我已将所需的库添加到 CalculateFees,然后实现 WebSecurityConfig 扩展 WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate", "/register" ).permitAll().
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
之后我实现 CustomRequestFilter extends OncePerRequestFilter ,检查 Token 并启动 SecurityContext
问题我不断收到 401 UNAUTHORIZED,无论我尝试调用服务和查询,但没有到达 customrequestfilter。
请帮助,我尝试了很多组合和配置但没有成功。
我正在使用 SPRING BOOT 2.2.6。
下面的令牌验证代码
@Component
public class CustomRequestFilter extends OncePerRequestFilter{
@Autowired
private CustomJwtUserDetailsService jwtUserDetailsService;
@Autowired
private CustomJwtTokenProvider jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
Long userID = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
userID = jwtTokenUtil.getUserIdFromJWT(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
}
// Once we get the token validate it.
if (userID != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserById(userID);
// if token is valid configure Spring Security to manually set
// authentication
if (jwtTokenUtil.validateToken(jwtToken)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
解决方案
推荐阅读
- javascript - 在 React 中确定 div 中的文本行数
- assembly - 如果输出文件属性更改,z/OS 汇编程序会奇怪地循环
- docker - 为什么在使用 OfficeOpenXML 时找不到我最新的 Docker 映像构建 libgdiplus
- java - 没有融合模式注册表的反序列化:Avro 序列化数据不包含 avro 模式
- javascript - 如何从 Android WebView 的标题中获取表单数据?
- xml - 将 XML Payload 发布到服务器以检索值
- docker - 如何将 sslmode=require 传递给 liquibase
- spring-boot - Springfox Boot Starter 3.0.0 JsonSerializer 错误
- azure - NLogViewer UDP 目标在 Azure 服务经典中保持静默
- javascript - 从道具内部的redux访问状态更改,状态成功更改,但该对象的道具未定义