美文网首页Java World单点登录cas
cas单点登录与springboot关联使用

cas单点登录与springboot关联使用

作者: 水花一现 | 来源:发表于2016-12-28 16:16 被阅读7326次
wallhaven-226884.jpg

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下载编译

jasig cas下载官网地址 https://www.apereo.org/projects/cas
github项目下载地址 https://github.com/apereo/cas/releases

我使用下载的是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

新更新内容

上面的版本有些问题,我这里做了下新修改。
项目地址为:https://github.com/shangjing105/spray-module
cas项目为里面的spray-manage-cas与cas服务端spray-cas

j_spring_cas_security_check 是每个项目客户端spring secrity验证ticket的地址,spring secrity版本4.0以下的是用j_spring_cas_security_check这个地址,4.0以上的用的是/login/cas地址,配置的时候注意项目版本。

//因为我用的cas版本是4.0以上,所以修改为/login/cas
app.service.security=http://localhost:8400/login/cas
app.service.home=http://localhost:8400

cas.service.login=http://localhost:8080/login
cas.service.logout=http://localhost:8080/logout
cas.url.prefix=http://localhost:8080
    @Bean
    public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
        CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
        casAuthenticationFilter.setAuthenticationManager(authenticationManager());
        //这里给上面的配置去掉,因为默认就是/login/cas,可以不用配置。如果是4.0以前就是j_spring_cas_security_check
        return casAuthenticationFilter;
    }

    @Bean
    public SingleSignOutFilter singleSignOutFilter() {
        SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
        //这里增加一个条件,不然启动时会出错:casserverurlprefix cannot be null
        singleSignOutFilter.setIgnoreInitConfiguration(true);
        singleSignOutFilter.setCasServerUrlPrefix(env.getRequiredProperty(CAS_URL_PREFIX));
        return singleSignOutFilter;
    }

4.结束

以上单点登录cas与spring boot的配置使用,对于有多个后台的系统,写一个单独的单点登录系统来对所有的平台来管理感觉非常有必要。 没有使用过的可以去尝试一下,简单好用你值的一学。

有什么问题欢迎给我来信或留言!

相关文章

网友评论

  • 1f49341aebc0:大佬 在未登录情况下 您试过用ajax请求客户端吗
    水花一现:很久的东西了,估计也不记得了,你可以自己尝试一下
  • shirdey:你好,测试了一下Demo,页面注销后还是能够登录,怎么回事?用浏览器向cas发送logout,再去Demo网页注销就可以,谢谢
    水花一现:@shirdey OK
    shirdey:找到原因了,logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")); 请求方式改成GET
    :joy:
  • 若谷先生wwj:楼主能不能把你下载到的cas-4.1.10版本,发给我一份,我下载一直失败。谢谢。我邮箱:by_wwj@163.com,qq:1069078433
    若谷先生wwj:楼主,你发的那个我下载下来,报文件类型不对,不是压缩文件,麻烦你确认一下,谢谢。
    若谷先生wwj:@水花一现 谢谢!
    水花一现:@若谷先生wwj 发了
  • 皮皮虾队长:有没有整合cas到zuul网关的
    水花一现:@蒋祥林菜鸡 没试过
  • 2c8ef4fd092f:你好我想问一下 这是cas-server 的配置吗 那个证书还用自己单独配置吗???
    水花一现:@丿泪雨痕罒 是的,服务端有现成的程序,就是客户端要接入
    2c8ef4fd092f:@水花一现 这样啊 cas-sever是不是就是下载cas.war 部署到tomcat上 然后对应把登录页面改造一下就完事了 然后加上你这个cas-client就可以看做一个单点登录系统
    水花一现:@丿泪雨痕罒 这是客户端的配置,证书我没有配置
  • d11c50cae3ce:默认跳转页在哪里配置? 我这没有index.jsp
    d11c50cae3ce:mainPage.html是client端界面,成功登陆后就不需要cas server的界面了
    d11c50cae3ce:成功登陆后我的需要跳转mainPage.html这个在哪里配置? 我不是太懂
    水花一现:@郭鑫_bcd3 cas项目里面有这个
  • 90b7937abd11:你好,能把代码我发下学习下吗,1037082161@qq.com,谢谢
    水花一现:@离开不曾解脱 我的github上有代码,地址下面评论有发
  • 69638675b7df:您好,请问j_spring_cas_security_check是干嘛的?是项目么?
    7cac59696319:同问啊,app.service.security 这个服务是做什么的 我在代码中也没找到这个链接
    69638675b7df:@水花一现 是干嘛用的呢?
    水花一现:@957411398 一个标识,可以换的
  • 洛小贼:大神,你这种方式,在哪里配置配置文件呀?
    水花一现:@洛小贼 springboot的配置文件properties里
  • 565aa007d4a8:你好我的单点登录OK了。但是两个应用 ,A应用登录了,B应用还跳转到了cas登录页面需要登录,求解
  • zhjwang:您好,spring boot不是自带tomcat吗,看到部署server,是直接在本机tomcat上,那我是不是还要部署到spring boot的tomcat中呢?
    水花一现:@遥纪黑曼巴 这个应该很简单,springboot的web里自带的就有Tomcat
    zhjwang:@水花一现 那如何部署到spring boot自带的tomcat中,谢谢?
    水花一现:@遥纪黑曼巴 是只带了tomcat ,但是也可以从pom 中给tomcat 去掉,然后部署到tomcat 里
  • laterequalsneve:请问一下,你的单点登出的配置,好像并没有将filter至于首位,你这个是怎么实现的???你的这个项目代码有吗?能分享一下吗?1196048228@qq.com
    水花一现:@laterequalsneve :smile: OK
    laterequalsneve:@水花一现 多谢了,我看了下你的代码,和这篇文章变化还是蛮大的,主要是WebSecurityConfiguration,和application-dev.properties,实现单点登录的。我来看下逻辑,十分感谢
    水花一现:我在github上有相关的代码,就在这个项目里,你可以看下,有问题了可以联系我 https://github.com/shangjing105/spray-module/tree/master/spray-manage
  • dfdf70ec7951:这里有个问题,如果集成了CAS的SSO,那对Session在分布式系统的共享有如何影响呢?
    水花一现:@小松同学 你说的我没实践过,但是应该可以实现,cas有redis版的,你可以百度下cas redis 查查资料
    dfdf70ec7951:@水花一现
    1、CAS是在,ngnix负载均衡之前还是之后?
    2、后台的是微服务的分布式架构,在没有CAS之前,我可以使用redis管理session,但是接入了CAS,session被CAS的客户端管理,这样对session共享有影响不?
    水花一现:@小松同学 同一个浏览器session不会变,在不同系统也是可以用的。你表达的什么意思?

本文标题:cas单点登录与springboot关联使用

本文链接:https://www.haomeiwen.com/subject/zqiyvttx.html