CAS单点登录与Springboot的security整合

cas 企业单点登录

  • Spring Webflow / Spring启动Java服务器组件。
  • 可插拔身份验证支持(LDAP, 数据库,X.509,SPNEGO, JAAS,JWT, RADIUS,MongoDb等)
  • 支持多种协议(CAS,SAML,WS-Federation, OAuth2,OpenID,OpenID Connect)
  • 通过各种提供商(Duo Security,FIDO U2F, YubiKey,Google Authenticator等)支持多因素身份验证
  • 支持授权外部提供商(如ADFS,Facebook,Twitter,SAML2 IdP等)的身份验证
  • 实时监控和跟踪应用程序行为,统计信息和日志。
  • 使用特定的认证策略管理和注册客户端应用程序和服务。
  • 跨平台客户端支持(Java,.Net,PHP,Perl,Apache等)。
  • 与InCommon,Box,Office365,ServiceNow,Salesforce,Workday,WebAdvisor,Drupal, Blackboard,Moodle,Google Apps等集成。

springboot特征

  • 创建独立的Spring应用程序
  • 直接嵌入Tomcat,Jetty或Undertow(不需要部署WAR文件)
  • 提供有意思的“启动”POM来简化您的Maven配置
  • 尽可能自动配置弹簧
  • 提供生产就绪功能,如指标,运行状况检查和外部化配置
  • 绝对没有代码生成,也不需要XML配置

应用新增spring security、spring-security-cas依赖

springboot应用添加安全框架spring security和spring-security-cas客户端。

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
       <groupId>org.springframework.security</groupId>
       <artifactId>spring-security-cas</artifactId>
</dependency>
<dependency>
       <groupId>javax.inject</groupId>
       <artifactId>javax.inject</artifactId>
       <version>1</version>
</dependency>

spring-security与cas客户端整合

应用实现spring-security权限控制时,需要实现AuthenticationUserDetailsService接口或者UserDetailsService接口,来完成登陆验证。springboot要启用权限控制,必须要启用**@EnableWebSecurity**。如果需要对配置扩展,继承实现WebSecurityConfigurerAdapter配置类。

  • 实现AuthenticationUserDetailsService接口
public class CustomUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        String login = token.getPrincipal().toString();
        String username = login.toLowerCase();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new AppUserDetails(username, grantedAuthorities);
    }
}
  • 实现userDetails接口
public class AppUserDetails implements UserDetails {
    private String username;
    private String password;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private boolean enabled;
    private Collection<? extends GrantedAuthority> authorities;
    private List<String> roles;

    public AppUserDetails() {
        super();
    }

    public AppUserDetails(String username, Collection<? extends GrantedAuthority> authorities) {
        super();
        this.username = username;
        this.password = "";
        this.accountNonExpired = true;
        this.accountNonLocked = true;
        this.credentialsNonExpired = true;
        this.enabled = true;
        this.authorities = authorities;
        this.roles = new ArrayList<>();
        this.roles.addAll(authorities.stream().map((Function<GrantedAuthority, String>) GrantedAuthority::getAuthority).collect(Collectors.toList()));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        /*
         * List<GrantedAuthority> l = new ArrayList<GrantedAuthority>(); l.add(new
         * GrantedAuthority() { private static final long serialVersionUID = 1L;
         * 
         * @Override public String getAuthority() { return "ROLE_AUTHENTICATED"; } }); return l;
         */
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
  • 实现WebSecurityConfigurerAdapter配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String CAS_URL_LOGIN = "cas.service.login";
    private static final String CAS_URL_LOGOUT = "cas.service.logout";
    private static final String CAS_URL_PREFIX = "cas.url.prefix";
    private static final String CAS_SERVICE_URL = "app.service.security";
    private static final String APP_SERVICE_HOME = "app.service.home";

    @Inject
    private Environment env;

    @Bean
    public ServiceProperties serviceProperties() {
        ServiceProperties sp = new ServiceProperties();
        sp.setService(env.getRequiredProperty(CAS_SERVICE_URL));
        sp.setSendRenew(false);
        return sp;
    }

    @Bean
    public CasAuthenticationProvider casAuthenticationProvider() {
        CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
        casAuthenticationProvider.setAuthenticationUserDetailsService(customUserDetailsService());
        casAuthenticationProvider.setServiceProperties(serviceProperties());
        casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
        casAuthenticationProvider.setKey("an_id_for_this_auth_provider_only");
        return casAuthenticationProvider;
    }

    @Bean
    public AuthenticationUserDetailsService<CasAssertionAuthenticationToken> customUserDetailsService() {
        return new CustomUserDetailsService();
    }

    @Bean
    public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
        return new Cas20ServiceTicketValidator(env.getRequiredProperty(CAS_URL_PREFIX));
    }

    @Bean
    public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
        CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
        casAuthenticationFilter.setAuthenticationManager(authenticationManager());
        casAuthenticationFilter.setFilterProcessesUrl("/j_spring_cas_security_check");
        return casAuthenticationFilter;
    }

    @Bean
    public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
        CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint();
        casAuthenticationEntryPoint.setLoginUrl(env.getRequiredProperty(CAS_URL_LOGIN));
        casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
        return casAuthenticationEntryPoint;
    }

    @Bean
    public SingleSignOutFilter singleSignOutFilter() {
        SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
        singleSignOutFilter.setCasServerUrlPrefix(env.getRequiredProperty(CAS_URL_PREFIX));
        return singleSignOutFilter;
    }

    @Bean
    public LogoutFilter requestCasGlobalLogoutFilter() {
        LogoutFilter logoutFilter = new LogoutFilter(env.getRequiredProperty(CAS_URL_LOGOUT) + "?service="+ env.getRequiredProperty(APP_SERVICE_HOME), new SecurityContextLogoutHandler());
        logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"));
        return logoutFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(casAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilter(casAuthenticationFilter());
        http.exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint());
        http.addFilterBefore(
                singleSignOutFilter(), 
                CasAuthenticationFilter.class)
                    .addFilterBefore(requestCasGlobalLogoutFilter(), LogoutFilter.class);
        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.authorizeRequests().antMatchers("/assets/**").permitAll().anyRequest().authenticated();

        http.logout().logoutUrl("/logout").logoutSuccessUrl("/").invalidateHttpSession(true).deleteCookies("JSESSIONID");
    }
}

配置cas认证

在springboot的配置文件(application.properties)配置cas认证。

app.service.security=http://localhost:8200/j_spring_cas_security_check
app.service.home=http://localhost:8200
cas.service.login=http://localhost:8080/cas/login
cas.service.logout=http://localhost:8080/cas/logout
cas.url.prefix=http://localhost:8080/cas

注意事项:

  1. 这里是列表文本serviceProperties单点登录服务器地址
  2. 这里是列表文本casAuthenticationProvider权限登录配置
  3. 这里是列表文本客户端登录地址和退出地址的配置
  4. 这里是列表文本客户端拦截的路径配置
  5. 这里是列表文本配置后需要启用配置**@Configuration** 和**@EnableWebSecurity**

 

https://my.oschina.net/u/1033181/blog/1438990

Leave a Comment

Your email address will not be published.