首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Spring Security检索CAS服务器发送的属性和用户名

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

Stack Overflow用户
提问于 2020-02-21 02:39:12
回答 1查看 802关注 0票数 0

我有一个spring引导应用程序,它本质上是MVC。此应用程序的所有页面都由CAS SSO进行身份验证。我使用了在https://www.baeldung.com/spring-security-cas-sso中描述的"spring-security-cas“,一切都像预期的那样工作正常。然而,我有一个问题-那就是,我不能在下面的@Bean中检索CAS服务器发送的属性和用户名。要检索CAS服务器发送的所有属性和用户名,我需要做什么?

代码语言:javascript
复制
@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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-23 21:31:14

首先,您需要在attributeRepository服务器的attributeRepository部分配置CAS源和要检索的属性,如下所示:

代码语言:javascript
复制
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博客中的this示例。

然后,您需要在服务中实现一个AuthenticationUserDetailsService来读取从CAS身份验证返回的属性,如下所示:

代码语言:javascript
复制
@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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60326575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档