【发布时间】:2019-03-25 01:06:06
【问题描述】:
我正在使用 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 的完全访问权限:@987654322 @
由于某种原因,当我在邮递员中尝试这些请求时,"signup" 请求运行良好,但 "signin" 不起作用并给了我 “401 未经授权”
我也试过 .antMatchers("/**").permitAll()
这是我的控制器:
@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));
}
}
【问题讨论】:
-
您可以尝试禁用
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint)行吗?通常入口点方法也会返回 401 状态。 -
它给了我 403 禁止
-
展示你对
JwtAuthenticationFilter的实现。 -
@Ayoubk 您的配置看起来不错 - 您可以尝试删除 HttpMethod.POST 并使其 antMatchers("/api/auth/**") 仅用于测试目的。您能否确认在调用 REST 端点时从 Postman 发送了正确的 HTTP 请求类型?
-
请将
signin请求添加到问题中。
标签: java spring spring-mvc spring-boot spring-security