1. 程式人生 > >cas單點登入與spring boot關聯使用

cas單點登入與spring boot關聯使用

1.cas單點登入介紹

單點登入( Single Sign-On , 簡稱 SSO )是目前比較流行的服務於企業業務整合的解決方案之一, SSO 使得在多個應用系統中,使用者只需要 登入一次 就可以訪問所有相互信任的應用系統。

從結構體系看, CAS 包括兩部分: CAS Server 和 CAS Client 。

CAS Server
CAS Server 負責完成對使用者的認證工作 , 需要獨立部署 , CAS Server 會處理使用者名稱 / 密碼等憑證(Credentials) 。

CAS Client
負責處理對客戶端受保護資源的訪問請求,需要對請求方進行身份認證時,重定向到 CAS Server 進行認證。(原則上,客戶端應用不再接受任何的使用者名稱密碼等 Credentials )。

CAS Client 與受保護的客戶端應用部署在一起,以 Filter 方式保護受保護的資源。

2.cas下載編譯

我使用下載的是cas-4.1.10是maven構建的專案,如果你要下cas-4.2以上的版本可能就是gradle構建的專案,如果你常用的是gradle,那就下載cas-4.2以上的版本,這裡比較坑的就是cas的編譯。

將下載的專案解壓後,進入到專案目錄裡使用mvn clean install 進行編譯,這裡會等待很時間,如果你沒用翻牆可能有些jar包下載不下來,如果編譯不了就在網上找別人編譯後的專案,我在編譯的時候就一直編譯不了,下載太慢,坑了我很長時間。

編譯後將cas-server-webapp專案下的targer的war包放到tomcat的裡,啟動tomcat。這裡的詳細步驟可以參考
Jasig cas 單點登入系統Server&Java Client配置

這裡的搭建cas server一端就不詳細說了,下面主要說說與spring boot的結合配置

3.spring boot的配置

這裡需要你有一個spring boot的專案,如何搭建可以參考網上的教程。

引入jar包

        <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的經驗的應該知道關於許可權登陸的用法 ,實現AuthenticationUserDetailsService 介面或UserDetailsService 介面,用作登陸驗證。

import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Authenticate a user from the database.
 */
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 介面,我們這裡實現這個介面,並定義一些關於使用者的資訊和許可權。如果你在clien要使用這些資訊,比如使用者名稱,角色,許可權等資訊,你可以在這裡處理一下。

package com.shang.spray.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AppUserDetails implements UserDetails {

    /** */
    private static final long serialVersionUID = -4777124807325532850L;

    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 配置類,並配置關於單點登入伺服器的一些資訊和攔截頁面。這裡先放上這個實現類

package com.shang.spray.security;

import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.inject.Inject;

@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
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

4.結束

以上單點登入cas與spring boot的配置使用,對於有多個後臺的系統,寫一個單獨的單點登入系統來對所有的平臺來管理感覺非常有必要。 沒有使用過的可以去嘗試一下,簡單好用你值的一學。

有什麼問題歡迎給我來信或留言!