Как получить атрибуты и имя пользователя, отправленные сервером CAS с помощью Spring Security - PullRequest
0 голосов
/ 20 февраля 2020

У меня есть приложение с весенней загрузкой, которое MVC по своей природе. Все страницы этого приложения проходят проверку подлинности CAS SSO. Я использовал «spring-security-cas», как описано в https://www.baeldung.com/spring-security-cas-sso Все работает нормально, как и ожидалось. Однако у меня есть одна проблема - я не могу получить атрибуты и имя пользователя, отправленные сервером CAS в следующем @Bean. Что мне нужно сделать, чтобы получить все атрибуты и имя пользователя, отправленные сервером CAS?

@Bean
public CasAuthenticationProvider casAuthenticationProvider() {

    CasAuthenticationProvider provider = new CasAuthenticationProvider();
    provider.setServiceProperties(serviceProperties());
    provider.setTicketValidator(ticketValidator());
    provider.setUserDetailsService(
      s -> new User("casuser", "Mellon", true, true, true, true,
        AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
    provider.setKey("CAS_PROVIDER_LOCALHOST_9000");
    return provider;
}

1 Ответ

0 голосов
/ 23 февраля 2020

Сначала вам необходимо настроить источник attributeRepository и атрибуты, которые необходимо получить, в разделе attributeRepository на сервере CAS, например:

cas.authn.attributeRepository.jdbc[0].singleRow=false
cas.authn.attributeRepository.jdbc[0].sql=SELECT * FROM USERATTRS WHERE {0}
cas.authn.attributeRepository.jdbc[0].username=username
cas.authn.attributeRepository.jdbc[0].role=role 
cas.authn.attributeRepository.jdbc[0].email=email
cas.authn.attributeRepository.jdbc[0].url=jdbc:hsqldb:hsql://localhost:9001/xdb
cas.authn.attributeRepository.jdbc[0].columnMappings.attrname=attrvalue

cas.authn.attributeRepository.defaultAttributesToRelease=username,email,role

Проверка this пример из блога CAS.

Затем вам нужно внедрить AuthenticationUserDetailsService в сервисе для чтения атрибутов, возвращаемых из аутентификации CAS, что-то вроде:

@Component
public class CasUserDetailService implements AuthenticationUserDetailsService {

    @Override
    public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException {
        CasAssertionAuthenticationToken casAssertionAuthenticationToken = (CasAssertionAuthenticationToken) authentication;
        AttributePrincipal principal = casAssertionAuthenticationToken.getAssertion().getPrincipal();
        Map attributes = principal.getAttributes();
        String uname = (String) attributes.get("username");
        String email = (String) attributes.get("email");
        String role = (String) attributes.get("role");
        String username = authentication.getName();
        Collection<SimpleGrantedAuthority> collection = new ArrayList<SimpleGrantedAuthority>();
        collection.add(new SimpleGrantedAuthority(role));
        return new User(username, "", collection);
    }
}

Затем настройте ваш authenticationProvider с помощью provider.setAuthenticationUserDetailsService(casUserDetailService);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...