我是 Spring Security 的新手,并尝试在我的服务上添加身份验证层。该服务工作正常@PreAuthorize,但是,当我使用它并添加角色时,@PreAuthorize("hasRole('ROLE_USER')")它在邮递员中向我显示了此错误,甚至在控制台中也没有:org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)\n\tat 包控制器:@RestController@RequestMapping("/api/package")@Slf4j@AllArgsConstructor@CrossOrigin("*")public class PackageController { private final PackageService packageService; @GetMapping("/list") @PreAuthorize("hasRole('ROLE_USER')") public ResponseEntity<?> getAllPackages(){ return ResponseEntity.ok(packageService.getAllPackages()); }}我使用邮递员登录并将承载令牌复制到其字段。用户已使用 postman 注册并登录,并且存在于数据库中。我尝试更改包含/排除前缀的角色ROLE_,但显示相同的结果。我无法弄清楚我做错了什么,因为我做了很多事情并尝试了不同的场景,但给出了相同的输出
1 回答

HUWWW
TA贡献1874条经验 获得超12个赞
.antMatchers(HttpMethod.GET, "/api/package/**", "/api/users/**").permitAll()
和用于@PreAuthorize("hasRole('ROLE_USER')")
端点GET /api/package/list
是矛盾的。
如果您想确保安全GET /api/package/list
,那么您可以使用.antMatchers(HttpMethod.GET,"/endpoint").hasRole("USER")
并确保您在数据库中具有 stroed 角色ROLE_USER
(而不是USER
),因为有时这会导致问题。
确保您在标头中传递了有效的令牌。
添加回答
举报
0/150
提交
取消