我正在尝试使用SpringSecurity和JWT令牌来保护API。我可以获取令牌,但每次尝试使用令牌访问受保护的端点时,都会收到403 Forbidden的错误。我有一个包含角色和用户信息的数据库。 这是我的Spring Security配置:
httpSecurity.csrf().disable().cors().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate", "/register").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/system/**").hasRole("ADMIN")
//.antMatchers("/system").permitAll()
// all other requests need to be authenticated
//.anyRequest().permitAll()
.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);
我尝试进行调试,令牌可以被解码,访问用户信息并获得包含角色的用户对象。这就是为什么我真的不知道发生了什么。
下面是来自RequestFilter类的筛选方法:
String username = 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 {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
}
} else {
logger.warn("JWT Token does not begin with Bearer String");
} // Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username); // if token is valid configure Spring Security to manually set
// authentication
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { 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);
抱歉这条消息有点长 :)