因此,我正在尝试使用SpringSecurity和JWT令牌保护api。我可以获取令牌,但是每次尝试使用令牌访问受保护的端点时,都会得到“ 403禁止访问”。我有一个包含角色和用户的数据库。 这是我的spring安全配置:
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);
对不起,此长消息:)
答案 0 :(得分:1)
您需要在SimpleGrantedAuthority
前面加上ROLE_
。
在您的UserDetailsService
中添加类似的内容。
String ROLE_PREFIX = "ROLE_";
authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + user.getRole()));