我正在使用 Spring 安全来保护我的 REST 服务中的一些端点。
这是安全配置类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// Other methods
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers(HttpMethod.POST, "/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
如您所见,我获得了对 /api/auth/signup 和 /api/auth/signin 的完全访问权限,方法是使用:.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
出于某种原因,当我在 postman 中尝试这些请求时,"signup" 请求工作正常,但 "signin" 没有工作并给了我 “401 未经授权”
我也试过 .antMatchers("/**").permitAll()
这是我的 Controller :
@RestController
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/api/auth/signup")
public ResponseEntity<RestResponse> registerUser(@Valid @RequestBody SignUpRequest signUpRequest,
UriComponentsBuilder uriComponentsBuilder) {
RestResponse restResponse = this.userService.register(signUpRequest);
UriComponents uriComponents = uriComponentsBuilder.path("/users").buildAndExpand();
return ResponseEntity.created(uriComponents.toUri()).body(restResponse);
}
@PostMapping("/api/auth/signin")
public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
return ResponseEntity.ok(this.userService.login(loginRequest));
}
}
最佳答案
我有同样的问题,不确定,但我认为你需要这个订单:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/auth/**")
.permitAll()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.anyRequest()
.authenticated()
.and()
.cors()
.and()
.exceptionHandling()
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
关于java - Spring Security 401 未经授权,即使有 permitAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904227/