Как сделать все мои @Requestmapping как @preauthorize ("isauthenticated ()") по умолчанию?JAVA

Программисты JAVA общаются здесь
Anonymous
Как сделать все мои @Requestmapping как @preauthorize ("isauthenticated ()") по умолчанию?

Сообщение Anonymous »

Я хотел бы применить принцип наименьшей привилегии в моих конечных точках, требуя, чтобы все они были аутентифицированы, если не указано иное на уровне метода (поэтому мне не нужно дублировать пути от моих контроллеров в SecurityfilterChain )
Идеальный @Preauthorize ("isauthenticated ()") по умолчанию, в то время как все еще возможно переопределить это, явно указав @preauthorize (или другие аннотации, такие как @permitall ). Конечно, это может быть достигнуто, аннотировав сами @controller , как следующее, но вы все равно можете отменить аннотирование одного, что является причиной, по которой я хотел бы более глобальное решение:

Код: Выделить всё

@RestController
@PreAuthorize("isAuthenticated()")
public class TestController {
@GetMapping("/test")
@PreAuthorize("permitAll()")
public void test() {}
}
< /code>
Я попытался следить за документацией, в которой говорится: < /p>

Важно помнить, что, когда вы используете безопасность метода, основанные на аннотациях, тогда нездоровые методы не защищены. Чтобы защитить от этого, объявите правило авторизации все уловки в вашем экземпляре Httpsecurity.

Поэтому я сохранил Spring Boot по умолчанию. doc: < /p>
@Bean
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin(withDefaults());
http.httpBasic(withDefaults());
return http.build();
}
Затем я попытался использовать @preauthorize ("armitallall ()") в некоторых конечных точках, чтобы переопределить его, без успеха: как описано в моей проблеме по предмету, SecurityFilterChain Правила оцениваются до @preauthize , чтобы они не могли переопределить его. SecurityFilterChain identical to Spring Boot's but with the catch-all line http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) commented out) as advised in the issue, like this:

Код: Выделить всё

@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
//http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin(withDefaults());
http.httpBasic(withDefaults());
return http.build();
}

@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
Advisor preAuthorize() {
return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(AuthenticatedAuthorizationManager.authenticated());
}
}
Без успеха, поскольку Authortization managerbeforemethodinterceptor.preauthorize применяется только к @preauthorize -Annotated Methods:

Код: Выделить всё

public static AuthorizationManagerBeforeMethodInterceptor preAuthorize(
PreAuthorizeAuthorizationManager authorizationManager) {
AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(
AuthorizationMethodPointcuts.forAnnotations(PreAuthorize.class), authorizationManager);
interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE.getOrder());
return interceptor;
}
(и действительно, он работает, если я аннотирую @controller с @preauthorize ("")

Подробнее здесь: https://stackoverflow.com/questions/777 ... ticated-by

Вернуться в «JAVA»