我需要允许绕过spring安全认证访问特定的控制器,但我不确定为什么spring仍然认为这些URL是受保护的……\我注意到了这个问题,因为每次我得到的是401响应
在调试模式下,我检查了restAuthenticationFilter()提供的筛选器仍在处理请求,尽管这些请求理论上是公共URL
有人能猜到我做错了什么吗?
我很感激你的帮助
我的ConfigClass
class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(new AntPathRequestMatcher("/authentication/**"));
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
@Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS)
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/authentication/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.and()
.authenticationProvider(tokenAuthProv())
.addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
.authorizeRequests()
.requestMatchers(PROTECTED_URLS)
.authenticated()
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
}
... some other beans
我的控制器
@RestController
@RequestMapping("/authentication")
@FieldDefaults(level = PRIVATE, makeFinal = true)
@AllArgsConstructor(access = PACKAGE)
final class AuthenticationController {
@NonNull
IUserAuthenticationService authservice;
@Autowired
GerenciadorUsuariosIntegracao users;
@PostMapping("/login")
@ApiResponses(value = {
@ApiResponse(code=400, message = "Bad Request", response = ExceptionResponse.class),
@ApiResponse(code=401, message = "Unauthorized", response = ExceptionResponse.class),
@ApiResponse(code=200, message = "OK", response = SuccessLoginResponse.class)
})
ResponseEntity<Object> login(@RequestBody UsuarioAPI usuario) {
LocalDateTime horaAtual = LocalDateTime.now(ZoneId.of("America/Sao_Paulo"));
Optional<String> token = authservice.login(usuario.username, usuario.password);
if (token.isPresent()) {
SuccessLoginResponse sucessResponse = new SuccessLoginResponse(horaAtual, token.get());
return new ResponseEntity<Object>(sucessResponse, HttpStatus.OK);
}
else {
ExceptionResponse exceptionResponse = new ExceptionResponse(horaAtual.toLocalTime(), "credenciais inválidas");
return new ResponseEntity<Object>(exceptionResponse, HttpStatus.FORBIDDEN);
}
}
@PostMapping("/registrarusuario")
String register(@RequestBody UsuarioAPI usuario) {
ApiUser usuariopersistido = (ApiUser) users.registrarNovoUsuario(usuario);
return usuariopersistido.toString();
}
}
我通常在configure
方法中配置这些端点,该方法具有HttpSecurity
参数。您可以根据HTTP方法配置要允许的端点列表或子集:
@Override
protected void configure(final HttpSecurity http) throws Exception {
final String[] SWAGGER_AUTH_WHITELIST = {
"/swagger-ui/**",
"/swagger-resources/**",
"/v3/api-docs",
};
// Set permissions on endpoints
http.authorizeRequests()
// public endpoints (e.g. Swagger)
.mvcMatchers("/login").permitAll()
.mvcMatchers(SWAGGER_AUTH_WHITELIST).permitAll()
.mvcMatchers(HttpMethod.GET, "/products/**").permitAll()
.mvcMatchers(HttpMethod.POST, "/users").permitAll()
// private endpoints
.anyRequest().authenticated();
}