【发布时间】:2020-07-31 20:20:48
【问题描述】:
所以,我正在尝试使用 SpringSecurity 和 JWT 令牌来保护 api。我可以获得令牌,但每次我尝试使用令牌访问受保护的端点时,我都会得到 403 Forbidden。我有一个包含角色和用户的数据库。 这是我的春季安全配置:
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);
我试了调试,可以解码token,可以访问用户信息,可以得到一个包含角色的用户对象。这就是为什么我真的不知道发生了什么。
这是我在 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);
抱歉这么长的消息:)
【问题讨论】: