spring引导返回401-unauthorized,即使我允许

yjghlzjz  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(606)

我正试图通过 Postman 访问我的api。在配置中,我已经设置/验证为允许的,但我总是得到401未经授权。
相关职能:

  1. @Override
  2. protected void configure(HttpSecurity httpSecurity) throws Exception {
  3. httpSecurity
  4. // dont authenticate this particular request
  5. .authorizeRequests().antMatchers("/authenticate").permitAll().
  6. // all other requests need to be authenticated
  7. anyRequest().authenticated().and().
  8. // make sure we use stateless session; session won't be used to
  9. // store user's state.
  10. exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
  11. .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  12. // Add a filter to validate the tokens with every request
  13. httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
  14. }

我的依赖关系

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-devtools</artifactId>
  13. <scope>runtime</scope>
  14. <optional>true</optional>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.postgresql</groupId>
  18. <artifactId>postgresql</artifactId>
  19. <scope>runtime</scope>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-security</artifactId>
  29. <version>2.3.1.RELEASE</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>io.jsonwebtoken</groupId>
  33. <artifactId>jjwt</artifactId>
  34. <version>0.9.1</version>
  35. </dependency>
  36. </dependencies>

任何帮助都将不胜感激

oalqel3c

oalqel3c1#

这里的问题是,即使您将Spring Security 配置为允许每个用户使用,您的请求也将通过与其他请求相同的安全链。我猜您对身份验证端点的调用在授权头中不包含任何内容,或者换句话说,您的令牌是空的,因此您得到的是401。在这种情况下,一种解决方案是对Spring Security 说,对于用于身份验证的url,请求不会通过安全链。您可以在spring安全配置中使用以下代码来实现这一点。

  1. @Override
  2. public void configure(WebSecurity web) throws Exception {
  3. web.ignoring().antMatchers("/authenticate");
  4. }

我希望这能解决你的问题。

相关问题