java - 即使禁用 csrf,Spring 安全性 403 禁止错误也会不断发生
问题描述
并且由于某种原因,/auth/api/login
即使我禁用了 csrf,REST-API 也会不断抛出 403 禁止错误(访问被拒绝)。
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
httpSecurity.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}
这是在SecurityConfig
扩展类上WebSecurityConfigurerAdapter
。
下面是AuthController
.
@RestController
@RequestMapping("/api/auth")
@AllArgsConstructor
public class AuthController {
private final AuthService authService;
private final RefreshTokenService refreshTokenService;
@PostMapping("/signup")
public ResponseEntity<String> signup (@RequestBody RegisterRequest registerRequest) {
authService.signup(registerRequest);
return new ResponseEntity<>("User Registration Successful", HttpStatus.OK);
}
@PostMapping("/login")
public AuthenticationResponse login(@RequestBody LoginRequest loginRequest) {
return authService.login(loginRequest);
}
@GetMapping("accountVerification/{token}")
public ResponseEntity<String> verifyAccount(@PathVariable String token) {
authService.verifyAccount(token);
return new ResponseEntity<>("Account Activated Successfully", OK);
}
当我尝试请求http://localhost:8080/api/auth/signup
时,它工作得很好,但 http://localhost:8080/api/auth/login
不断返回 403 禁止错误。
为了清楚起见,下面是JwtAuthenticationFilter
课程。
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && jwtProvider.validateToken(jwt)){
String username = jwtProvider.getUsernameFromJwt(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request){
String bearerToken = request.getHeader("Authorization");
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
return bearerToken.substring(7);
}
return bearerToken;
}
有人可以指出错误还是我需要做更多的配置?
解决方案
修复:从 HttpSecurity 配置中删除 cors()。
在学习本教程时,我遇到了同样的问题。坦率地说,即使我是新春靴的新手。正在尝试不同的方法来解决这个问题,这对我来说是一个点击。我不确定为什么这可以解决问题。需要深入研究这一点。但我希望这个可以帮助您在本教程中继续前进。
推荐阅读
- c - 将指向同类型结构成员的结构的指针分配给指向同类型结构的另一个指针
- javascript - 接收具有相同类的元素的值
- google-chrome - 获取每个 gmail 帐户的 authToken
- scala - scaladoc:排除方法
- jestjs - 在 Jest 中获取当前的测试/规范名称
- reactjs - 在承诺返回中调用时文件对话框不会打开
- java - 如何将 JavaFXML 中的单个表列标题与 CSS 对齐
- gradle - 来自 Travis 的 Gradle uploadArchives 破坏暂存存储库
- jenkins - 在自定义路径中创建 jenkins.log - linux
- outlook-web-addins - Outlook 加载项:任务窗格突然关闭 OWA 中的文件夹项目更改