Теперь я добавил авторизацию с помощью JSR250 и получаю только 403 Access отказано.
WS:
Код: Выделить всё
@RestController
@RequestMapping("/password")
public class ServicioPassword {
@GetMapping(path = "ldap")
public ResponseEntity getLdap() {
var authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println("EN LDAP " + authentication.getPrincipal() + " - " + authentication.isAuthenticated());
for (var authority : authentication.getAuthorities()) {
System.out.println("Authority= " + authority);
}
return ResponseEntity.ok("DE LDAP");
}
EN LDAP LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou= IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия=[AGNI_OIMIVR]] - true
Authority= AGNI_OIMIVR
Тем не менее, если я добавлю @RolesAllowed("AGNI_OIMIVR" ), когда я вызываю его, я получаю 403 Forbidden.
The MethodSecurityConfig:
Код: Выделить всё
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)
public class MethodSecurityConfig
extends GlobalMethodSecurityConfiguration{
}
Код: Выделить всё
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Autowired
private Environment environment;
@Bean
BindAuthenticator bindAuthenticator(
final BaseLdapPathContextSource contextSource) {
var bindAuthenticator = new BindAuthenticator(contextSource);
bindAuthenticator.setUserDnPatterns(new String[]{environment.getRequiredProperty("spring.ldap.userdnpattern")});
return bindAuthenticator;
}
@Bean
AuthenticationProvider ldapAuthenticationProvider(
final LdapAuthenticator ldapAuthenticator) {
var ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator);
var ldapUserDetailsMapper = new CustomUserDetailsMapper();
var ldapMemberRoles = environment.getRequiredProperty("spring.ldap.roleattributes");
ldapUserDetailsMapper.setRoleAttributes(ldapMemberRoles.split(","));
ldapUserDetailsMapper.setRolePrefix("");
ldapAuthenticationProvider.setUserDetailsContextMapper(ldapUserDetailsMapper);
return ldapAuthenticationProvider;
}
@Bean
SecurityFilterChain filterChain(
final HttpSecurity http)
throws Exception {
http.csrf().disable()
.cors().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.httpBasic();
return http.build();
}
Обратите внимание, что строка: 2022 -07-07 13:04:27.464 ПРЕДУПРЕЖДЕНИЕ 81968 --- [nio-8080-exec-2] e.s.d.o.s.ws.CustomUserDetailsMapper: createAuthority agni_oimivr берется из журнала одного из моих пользовательских классов.
07.07.2022 13:04:27.441 СЛЕД 81968 --- [nio-8080-exec-2] o.s.s.w.a.www.BasicAuthenticationFilter: в заголовке базовой авторизации обнаружено имя пользователя «ivr_apl_user»
2022-07-07 13:04:27.442 TRACE 81968 --- [nio-8080-exec-2] o.s.s.authentication.ProviderManager : Аутентификация запроса с помощью LdapAuthenticationProvider (1/1)
2022-07-07 13:04:27.444 TRACE 81968 --- [nio-8080-exec-2] o.s.s.l.a.BindAuthenticator: попытка привязки как cn=ivr_apl_user,ou =[УДАЛЕНО]
2022-07-07 13:04:27.444 TRACE 81968 --- [nio-8080-exec-2] s.s.l.DefaultSpringSecurityContextSource: удаление флага объединения для пользователя cn=ivr_apl_user,ou=[УДАЛЕНО]
07.07.2022 13:04:27.463 DEBUG 81968 --- [nio-8080-exec-2] o.s.s.l.a.BindAuthenticator: Bound cn=ivr_apl_user,ou=[УДАЛЕНО]
2022-07-07 13:04:27.463 ОТЛАДКА 81968 --- [nio-8080-exec-2] o.s.s.l.u.LdapUserDetailsMapper : Сопоставление сведений о пользователе из контекста с DN cn=ivr_apl_user,ou=[УДАЛЕНО]
2022-07-07 13:04:27.464 WARN 81968 --- [nio-8080-exec-2] e.s.d.o.s.ws.CustomUserDetailsMapper : createAuthority agni_oimivr
2022-07-07 13:04:27.464 DEBUG 81968 --- [nio-8080-exec-2] o.s.s.l.a.LdapAuthenticationProvider: прошедший проверку подлинности пользователь
2022-07-07 13:04:27.465 DEBUG 81968 --- [nio-8080-exec-2] o.s.s.w.a.www.BasicAuthenticationFilter: установите для SecurityContextHolder значение UsernamePasswordAuthenticationToken [Principal=LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou=IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия = [AGNI_OIMIVR]], Учетные данные = [ЗАЩИЩЕНО], Аутентифицировано = true, Подробности = WebAuthenticationDetails [RemoteIpAddress = 0:0:0:0:0:0:0:1, SessionId = null], Предоставленные полномочия = [AGNI_OIMIVR] ]]
07.07.2022 13:04:27.465 TRACE 81968 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy: вызов RequestCacheAwareFilter (7/12)
07.07.2022 13:04: 27.465 СЛЕД 81968 --- [nio-8080-exec-2] o.s.s.w.s.HttpSessionRequestCache: нет сохраненного запроса
2022-07-07 13:04:27.465 TRACE 81968 --- [nio-8080-exec-2] o.s.security. web.FilterChainProxy: вызов SecurityContextHolderAwareRequestFilter (8/12)
2022-07-07 13:04:27.466 TRACE 81968 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy: вызов AnonymousAuthenticationFilter (9/ 12)
2022-07-07 13:04:27.466 TRACE 81968 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter: не установлен SecurityContextHolder, поскольку уже прошел аутентификацию UsernamePasswordAuthenticationToken [Principal=LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou=IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия = [AGNI_OIMIVR]], Учетные данные = [ЗАЩИЩЕНО], Аутентифицировано = true, Подробности = WebAuthenticationDetails [RemoteIpAddress = 0:0:0:0:0:0:0:1, SessionId = null], Предоставленные полномочия = [AGNI_OIMIVR] ]]
07.07.2022 13:04:27.466 TRACE 81968 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy: вызов SessionManagementFilter (10/12)
07.07.2022 13:04: 27.467 СЛЕД 81968 --- [nio-8080-exec-2] s.CompositeSessionAuthenticationStrategy: подготовка сеанса с помощью ChangeSessionIdAuthenticationStrategy (1/1)
2022-07-07 13:04:27.467 DEBUG 81968 --- [nio-8080- исполнительный-2] w.c.HttpSessionSecurityContextRepository : HttpSession в настоящее время имеет значение NULL, а HttpSessionSecurityContextRepository запрещено создавать HttpSession (поскольку свойствоallowSessionCreation имеет значение false) - поэтому SecurityContext не сохраняется для следующего запроса
2022-07-07 13:04:27.467 TRACE 81968 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy: вызов ExceptionTranslationFilter (11/12)
07.07.2022 13:04: 27.467 СЛЕД 81968 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy: вызов FilterSecurityInterceptor (12/12)
2022-07-07 13:04:27.468 TRACE 81968 --- [nio-8080 -exec-2] o.s.s.w.a.i.FilterSecurityInterceptor: не выполнена повторная аутентификация UsernamePasswordAuthenticationToken [Principal=LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou=IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия = [AGNI_OIMIVR]], Учетные данные = [ЗАЩИЩЕНО], Аутентифицировано = true, Подробности = WebAuthenticationDetails [RemoteIpAddress = 0:0:0:0:0:0:0:1, SessionId = null], Предоставленные полномочия = [AGNI_OIMIVR] ]] перед авторизацией
07.07.2022 13:04:27.468 TRACE 81968 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor: авторизация вызова фильтра [GET /password/ldap] с атрибутами [аутентифицированный]
2022-07-07 13:04:27.469 ОТЛАДКА 81968 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor: авторизованный вызов фильтра [GET /password/ldap] с атрибутами [аутентифицированный]
2022-07-07 13:04:27.470 TRACE 81968 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor: не переключена аутентификация RunAs, поскольку RunAsManager вернул ноль
2022-07-07 13:04:27.470 DEBUG 81968 --- [nio-8080-exec -2] o.s.security.web.FilterChainProxy: Защищено GET /password/ldap
2022-07-07 13:04:27.471 TRACE 81968 --- [nio-8080-exec-2] o.s.s.a.i.a.MethodSecurityInterceptor: Не выполнено повторно аутентифицироваться UsernamePasswordAuthenticationToken [Principal=LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou=IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия = [AGNI_OIMIVR]], Учетные данные = [ЗАЩИЩЕНО], Аутентифицировано = true, Подробности = WebAuthenticationDetails [RemoteIpAddress = 0:0:0:0:0:0:0:1, SessionId = null], Предоставленные полномочия = [AGNI_OIMIVR] ]] перед авторизацией
07.07.2022 13:04:27.472 TRACE 81968 --- [nio-8080-exec-2] o.s.s.a.i.a.MethodSecurityInterceptor: Авторизация ReflectiveMethodInvoke: public org.springframework.http.ResponseEntity es.ssib.dtic.oimivr.service.ws.v1.ServicioPassword.getLdap(); цель имеет класс [es.ssib.dtic.oimivr.service.ws.v1.ServicioPassword] с атрибутами [ROLE_AGNI_OIMIVR]
2022-07-07 13:04:27.475 TRACE 81968 --- [ нио-8080-exec-2] o.s.s.a.i.a.MethodSecurityInterceptor: не удалось авторизовать ReflectiveMethodInvoke: public org.springframework.http.ResponseEntity es.ssib.dtic.oimivr.service.ws.v1.ServicioPassword.getLdap(); цель имеет класс [es.ssib.dtic.oimivr.service.ws.v1.ServicioPassword] с атрибутами [ROLE_AGNI_OIMIVR] с использованием AffirmativeBased [DecisionVoters=[org.springframework.security.access.annotation.Jsr250Voter@6797e2e2, org.springframework.security.access.vote.RoleVoter@2ab76862, org.springframework.security.access.vote.AuthenticatedVoter@152f6a2e], AllowIfAllAbstainDecisions=false]
07.07.2022 13:04: 27.484 СЛЕД 81968 --- [nio-8080-exec-2] o.s.s.w.a.ExceptionTranslationFilter : Отправка UsernamePasswordAuthenticationToken [Principal=LdapUserDetailsImpl [Dn=cn=ivr_apl_user,ou=IVR,ou=Applicaciones,dc=pre,dc=aplssib; Имя пользователя = ivr_apl_user; Пароль=[ЗАЩИЩЕНО]; Включено=истина; AccountNonExpired=истина; CredentialsNonExpired=истина; AccountNonLocked=истина; Предоставленные полномочия = [AGNI_OIMIVR]], Учетные данные = [ЗАЩИЩЕНО], Аутентифицировано = true, Подробности = WebAuthenticationDetails [RemoteIpAddress = 0:0:0:0:0:0:0:1, SessionId = null], Предоставленные полномочия = [AGNI_OIMIVR] ]] для доступа к обработчику отказа, поскольку доступ запрещен
org.springframework.security.access.AccessDeniedException: Доступ запрещен
на org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:73) ~[spring- security-core-5.7.1.jar:5.7.1]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:239) ~[spring-security-core-5.7.1.jar:5.7.1]
[... ]
2022-07-07 13:04:27.497 ОТЛАДКА 81968 --- [nio-8080-exec-2] o.s.s.w.access.AccessDeniedHandlerImpl : ответ с кодом состояния 403
Что я делаю не так?
Подробнее здесь: https://stackoverflow.com/questions/728 ... -boot-rest