AccessDeniedHandler не вызывается при использовании AadResourceServerHttpSecurityConfigurerJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 AccessDeniedHandler не вызывается при использовании AadResourceServerHttpSecurityConfigurer

Сообщение Anonymous »

Мое приложение представляет собой простой сервер ресурсов. Я использую AadResourceServerHttpSecurityConfigurer.aadResourceServer() для проверки данного токена доступа. Конкретную документацию, которой я пользовался, можно найти здесь.
Цель: возвращать пользовательское сообщение об ошибке при указании неверного токена (например, «123»). Кажется, мой accessDeniedHandler не вызывается. Напротив, когда я вообще не указываю JWT, он работает нормально и возвращается пользовательское сообщение об ошибке (

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

authenticationEntryPoint
).
Это код, который я использую (я изменил пример Microsoft, поскольку в нем использовались устаревшие методы):

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

@Autowired
private ErrorHandler errorHandler;

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrfCustomizer -> csrfCustomizer.disable())
.with(AadResourceServerHttpSecurityConfigurer
.aadResourceServer(), Customizer.withDefaults())
.authorizeHttpRequests(requests -> requests
.requestsMatchers(antMatcher("/users/**")).permitAll()
.requestMatchers(antMatcher(HttpMethod.GET, "/admin")).hasRole(ADMIN_ROLE)
.anyRequest().authenticated()
)
.exceptionHandling(exceptionHandlingCustomizer -> exceptionHandlingCustomizer.authenticationEntryPoint(errorHandler))
.exceptionHandling(exceptionHandlingCustomizer -> exceptionHandlingCustomizer.accessDeniedHandler(errorHandler))
.sessionManagement(sessionManagement -> sessionManagementCustomizer.sessionCreationPolicy(sessionCreationPolicy.STATELESS)));

return http.build();
}
Конкретный обработчик ошибок (упрощенный):

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

@Configuration
public class ErrorHandler authenticationEntryPoint, AccessDeniedHandler {
@Override
public void commence() {
// this is called
}

@Override
public void handle() {
// this is not called
}
}
Напротив, эта конфигурация работает нормально, и когда я предоставляю неверный токен, возвращается пользовательское сообщение об ошибке, но я не использую AadResourceServerHttpSecurityConfigurer.aadResourceServer():

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

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrfCustomizer -> csrfCustomizer.disable())
.oauth2ResourceServer(httpSecurityOAuth2ResourceServerConfigurer -> httpSecurityOAuth2ResourceServerConfigurer
.authenticationEntryPoint(errorHandler)
.accessDeniedHandler(errorHandler)
)
.authorizeHttpRequests(requests -> requests
.requestsMatchers(antMatcher("/users/**")).permitAll()
.requestMatchers(antMatcher(HttpMethod.GET, "/admin")).hasRole(ADMIN_ROLE)
.anyRequest().authenticated()
)
.sessionManagement(sessionManagement -> sessionManagementCustomizer.sessionCreationPolicy(sessionCreationPolicy.STATELESS)));

return http.build();
}
Есть ли способ использовать AadResourceServerHttpSecurityConfigurer.aadResourceServer() как с обработчиками исключений аутентификацииEntryPoint, так и с accessDeniedHandler?

Подробнее здесь: https://stackoverflow.com/questions/787 ... yconfigure
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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