【发布时间】:2021-10-21 13:51:26
【问题描述】:
我正在尝试使用 Spring Boot、带有角色的 JWT 实现身份验证
我有错误:
访问此资源需要完整的身份验证
发送 POST 请求时 到“http://localhost:8080/api/profile/edit_user_detail”(带有授权标头)
下面是我的控制器
@Controller
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api/profile")
public class UserAPI {
@Autowired
UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
QARepository qaRepository;
@Autowired
DiscussRepository discussRepository;
@Autowired
AnnouncementRepository announcementRepository;
@PostMapping(value = {"/edit_user_detail"})
@PreAuthorize("hasRole('ROLE_USER')")
public ResponseEntity<?> editInfo(@RequestBody Map map) throws ParseException {
String username = map.get("username").toString();
String display_name = map.get("display_name").toString();
User user = userRepository.findByUserName(username).get(0);
user.setuDigitalName(display_name);
userRepository.save(user);
return ResponseEntity.ok("Updated");
}
但是当我删除线时
@PreAuthorize("hasRole('ROLE_USER')")
然后我可以成功发布请求并成功编辑用户(我已签入数据库)
这也是我的入口点(捕捉异常)
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger log = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
log.error("Authorized error: " + e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Error: Unauthorized");
e.printStackTrace();
}
}
这是我的配置文件
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ConfigAuthenticate extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServices userDetailsServices;
@Autowired
private AuthEntryPointJwt unauthorizeHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter(){
return new AuthTokenFilter();
}
@Bean
@Override public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServices).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizeHandler)
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
我认为 WebSecurityConfigurerAdapter 中的配置有问题,我已尝试
- 将
@PreAuthorize("hasRole('ROLE_USER')")更改为@PreAuthorize("hasRole('USER')") - 检查标头中的 JWT Token,以及数据库中的 ROLE
还是不行,谁有解决办法
【问题讨论】:
标签: java authentication jwt postman