如何使用Spring Security检索CAS服务器发送的属性和用户名



我有一个spring-boot应用程序,它本质上是MVC。此应用程序的所有页面都由CAS SSO进行身份验证。我使用了"春季安全案例",如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;
}

首先,您需要在CAS服务器的attributeRepository部分中配置属性存储库源和要检索的属性,如:

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

请查看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);
}
}

然后,使用provider.setAuthenticationUserDetailsService(casUserDetailService);调整您的authenticationProvider

最新更新