[英]How to remove a url pattern from spring security authentication?
我需要允許繞過 Spring 安全身份驗證訪問特定控制器,但我不確定為什么 Spring 安全仍然認為這些 URL 是受保護的。 我注意到了這個問題,因為每次我收到 401 響應。
在調試模式下,我檢查了請求仍在由restAuthenticationFilter()
提供的過濾器處理,即使這些在理論上是公共 URL。
誰能猜出我做錯了什么,好嗎?
我感謝您的幫助
我的配置 class:
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
我的 controller
@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();
}
}
我也嘗試了推薦的第一種方法....仍然是相同的結果
protected void configure(final HttpSecurity http) throws Exception {
final String[] SWAGGER_AUTH_WHITELIST = {
"/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/authentication/**"
};
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()
.mvcMatchers("/authentication/login").permitAll()
.mvcMatchers("/authentication/registrarusuario").permitAll()
.mvcMatchers(SWAGGER_AUTH_WHITELIST).permitAll()
//.requestMatchers(PROTECTED_URLS)
.anyRequest()
.authenticated()
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
}
問題是您以錯誤的順序添加了.authorizeRequests()
。 authorizeRequests()
順序很重要, .authenticated()
必須先出現。
.authorizeRequests().anyRequest().authenticated()
.and()
.authorizeRequests().antMatchers("/authentication/login").permitAll()
.and()
....
我通常在具有HttpSecurity
參數的configure
方法中配置這些端點。 您可以根據 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.