欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Spring Boot 使用Spring security 集成CAS

程序员文章站 2024-02-20 16:02:22
1.创建工程 创建maven工程:springboot-security-cas 2.加入依赖 创建工程后,打开pom.xml,在pom.xml中加入以下...

1.创建工程

创建maven工程:springboot-security-cas

2.加入依赖

创建工程后,打开pom.xml,在pom.xml中加入以下内容:

<parent> 
    <groupid>org.springframework.boot</groupid> 
    <artifactid>spring-boot-starter-parent</artifactid> 
    <version>1.4.3.release</version> 
  </parent> 
  <properties> 
    <project.build.sourceencoding>utf-8</project.build.sourceencoding> 
    <java.version>1.8</java.version> 
  </properties> 
  <dependencies> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter</artifactid> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter-web</artifactid> 
    </dependency> 
    <!-- security starter poms --> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-starter-security</artifactid> 
    </dependency> 
    <!-- security 对cas支持 --> 
    <dependency> 
      <groupid>org.springframework.security</groupid> 
      <artifactid>spring-security-cas</artifactid> 
    </dependency> 
    <!-- security taglibs --> 
    <dependency> 
      <groupid>org.springframework.security</groupid> 
      <artifactid>spring-security-taglibs</artifactid> 
    </dependency> 
    <!-- 热加载 --> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-devtools</artifactid> 
      <optional>true</optional> 
    </dependency> 
    <dependency> 
      <groupid>org.springframework.boot</groupid> 
      <artifactid>spring-boot-configuration-processor</artifactid> 
      <optional>true</optional> 
    </dependency> 
  </dependencies> 
  <build> 
    <plugins> 
      <plugin> 
        <groupid>org.springframework.boot</groupid> 
        <artifactid>spring-boot-maven-plugin</artifactid> 
      </plugin> 
    </plugins> 
  </build> 

3.创建application.properties

创建application.properties文件,加入以下内容:

#cas服务地址 
cas.server.host.url=http://localhost:8081/cas 
#cas服务登录地址 
cas.server.host.login_url=${cas.server.host.url}/login 
#cas服务登出地址 
cas.server.host.logout_url=${cas.server.host.url}/logout?service=${app.server.host.url} 
#应用访问地址 
app.server.host.url=http://localhost:8080 
#应用登录地址 
app.login.url=/login 
#应用登出地址 
app.logout.url=/logout 

4.创建入口启动类(mainconfig)

创建入口启动类mainconfig,完整代码如下:

package com.chengli.springboot; 
 
import org.springframework.boot.springapplication; 
import org.springframework.boot.autoconfigure.springbootapplication; 
import org.springframework.security.access.prepost.preauthorize; 
import org.springframework.web.bind.annotation.requestmapping; 
import org.springframework.web.bind.annotation.restcontroller; 
 
@restcontroller 
@springbootapplication 
public class mainconfig { 
  public static void main(string[] args) { 
    springapplication.run(mainconfig.class, args); 
  } 
 
  @requestmapping("/") 
  public string index() { 
    return "访问了首页哦"; 
  } 
 
  @requestmapping("/hello") 
  public string hello() { 
    return "不验证哦"; 
  } 
 
  @preauthorize("hasauthority('test')")//有test权限的才能访问 
  @requestmapping("/security") 
  public string security() { 
    return "hello world security"; 
  } 
 
  @preauthorize("hasauthority('admin')")//必须要有admin权限的才能访问 
  @requestmapping("/authorize") 
  public string authorize() { 
    return "有权限访问"; 
  } 
   
  /**这里注意的是,test与admin只是权限编码,可以自己定义一套规则,根据实际情况即可*/ 
} 

5.创建security配置类(securityconfig)

创建security配置类securityconfig,完整代码如下:

package com.chengli.springboot.security; 
 
import org.jasig.cas.client.session.singlesignoutfilter; 
import org.jasig.cas.client.validation.cas20serviceticketvalidator; 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.context.annotation.bean; 
import org.springframework.context.annotation.configuration; 
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.method.configuration.enableglobalmethodsecurity; 
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 com.chengli.springboot.custom.customuserdetailsservice; 
import com.chengli.springboot.properties.casproperties; 
 
@configuration 
@enablewebsecurity //启用web权限 
@enableglobalmethodsecurity(prepostenabled = true) //启用方法验证 
public class securityconfig extends websecurityconfigureradapter { 
  @autowired 
  private casproperties casproperties; 
   
  /**定义认证用户信息获取来源,密码校验规则等*/ 
  @override 
  protected void configure(authenticationmanagerbuilder auth) throws exception { 
    super.configure(auth); 
    auth.authenticationprovider(casauthenticationprovider()); 
    //inmemoryauthentication 从内存中获取 
    //auth.inmemoryauthentication().withuser("chengli").password("123456").roles("user") 
    //.and().withuser("admin").password("123456").roles("admin"); 
     
    //jdbcauthentication从数据库中获取,但是默认是以security提供的表结构 
    //usersbyusernamequery 指定查询用户sql 
    //authoritiesbyusernamequery 指定查询权限sql 
    //auth.jdbcauthentication().datasource(datasource).usersbyusernamequery(query).authoritiesbyusernamequery(query); 
     
    //注入userdetailsservice,需要实现userdetailsservice接口 
    //auth.userdetailsservice(userdetailsservice); 
  } 
   
  /**定义安全策略*/ 
  @override 
  protected void configure(httpsecurity http) throws exception { 
    http.authorizerequests()//配置安全策略 
      //.antmatchers("/","/hello").permitall()//定义/请求不需要验证 
      .anyrequest().authenticated()//其余的所有请求都需要验证 
      .and() 
    .logout() 
      .permitall()//定义logout不需要验证 
      .and() 
    .formlogin();//使用form表单登录 
     
    http.exceptionhandling().authenticationentrypoint(casauthenticationentrypoint()) 
      .and() 
      .addfilter(casauthenticationfilter()) 
      .addfilterbefore(caslogoutfilter(), logoutfilter.class) 
      .addfilterbefore(singlesignoutfilter(), casauthenticationfilter.class); 
     
    //http.csrf().disable(); //禁用csrf 
  } 
   
  /**认证的入口*/ 
  @bean 
  public casauthenticationentrypoint casauthenticationentrypoint() { 
    casauthenticationentrypoint casauthenticationentrypoint = new casauthenticationentrypoint(); 
    casauthenticationentrypoint.setloginurl(casproperties.getcasserverloginurl()); 
    casauthenticationentrypoint.setserviceproperties(serviceproperties()); 
    return casauthenticationentrypoint; 
  } 
   
  /**指定service相关信息*/ 
  @bean 
  public serviceproperties serviceproperties() { 
    serviceproperties serviceproperties = new serviceproperties(); 
    serviceproperties.setservice(casproperties.getappserverurl() + casproperties.getapploginurl()); 
    serviceproperties.setauthenticateallartifacts(true); 
    return serviceproperties; 
  } 
   
  /**cas认证过滤器*/ 
  @bean 
  public casauthenticationfilter casauthenticationfilter() throws exception { 
    casauthenticationfilter casauthenticationfilter = new casauthenticationfilter(); 
    casauthenticationfilter.setauthenticationmanager(authenticationmanager()); 
    casauthenticationfilter.setfilterprocessesurl(casproperties.getapploginurl()); 
    return casauthenticationfilter; 
  } 
   
  /**cas 认证 provider*/ 
  @bean 
  public casauthenticationprovider casauthenticationprovider() { 
    casauthenticationprovider casauthenticationprovider = new casauthenticationprovider(); 
    casauthenticationprovider.setauthenticationuserdetailsservice(customuserdetailsservice()); 
    //casauthenticationprovider.setuserdetailsservice(customuserdetailsservice()); //这里只是接口类型,实现的接口不一样,都可以的。 
    casauthenticationprovider.setserviceproperties(serviceproperties()); 
    casauthenticationprovider.setticketvalidator(cas20serviceticketvalidator()); 
    casauthenticationprovider.setkey("casauthenticationproviderkey"); 
    return casauthenticationprovider; 
  } 
   
  /*@bean 
  public userdetailsservice customuserdetailsservice(){ 
    return new customuserdetailsservice(); 
  }*/ 
   
  /**用户自定义的authenticationuserdetailsservice*/ 
  @bean 
  public authenticationuserdetailsservice<casassertionauthenticationtoken> customuserdetailsservice(){ 
    return new customuserdetailsservice(); 
  } 
   
  @bean 
  public cas20serviceticketvalidator cas20serviceticketvalidator() { 
    return new cas20serviceticketvalidator(casproperties.getcasserverurl()); 
  } 
   
  /**单点登出过滤器*/ 
  @bean 
  public singlesignoutfilter singlesignoutfilter() { 
    singlesignoutfilter singlesignoutfilter = new singlesignoutfilter(); 
    singlesignoutfilter.setcasserverurlprefix(casproperties.getcasserverurl()); 
    singlesignoutfilter.setignoreinitconfiguration(true); 
    return singlesignoutfilter; 
  } 
   
  /**请求单点退出过滤器*/ 
  @bean 
  public logoutfilter caslogoutfilter() { 
    logoutfilter logoutfilter = new logoutfilter(casproperties.getcasserverlogouturl(), new securitycontextlogouthandler()); 
    logoutfilter.setfilterprocessesurl(casproperties.getapplogouturl()); 
    return logoutfilter; 
  } 
} 

6.用户自定义类

(1)定义casproperties,用于将properties文件指定的内容注入以方便使用,这里不注入也是可以的,可以获取spring 当前的环境,代码如下:

package com.chengli.springboot.properties; 
import org.springframework.beans.factory.annotation.value; 
import org.springframework.stereotype.component; 
 
/** 
 * cas的配置参数 
 * @author chengli 
 */ 
@component 
public class casproperties { 
  @value("${cas.server.host.url}") 
  private string casserverurl; 
 
  @value("${cas.server.host.login_url}") 
  private string casserverloginurl; 
 
  @value("${cas.server.host.logout_url}") 
  private string casserverlogouturl; 
 
  @value("${app.server.host.url}") 
  private string appserverurl; 
 
  @value("${app.login.url}") 
  private string apploginurl; 
 
  @value("${app.logout.url}") 
  private string applogouturl; 
......省略 getters setters 方法 
} 

(2)定义customuserdetailsservice类,代码如下:

package com.chengli.springboot.custom; 
 
import java.util.hashset; 
import java.util.set; 
 
import org.springframework.security.cas.authentication.casassertionauthenticationtoken; 
import org.springframework.security.core.userdetails.authenticationuserdetailsservice; 
import org.springframework.security.core.userdetails.userdetails; 
import org.springframework.security.core.userdetails.usernamenotfoundexception; 
 
/** 
 * 用于加载用户信息 实现userdetailsservice接口,或者实现authenticationuserdetailsservice接口 
 * @author chengli 
 * 
 */ 
public class customuserdetailsservice /* 
  //实现userdetailsservice接口,实现loaduserbyusername方法 
  implements userdetailsservice { 
  @override 
  public userdetails loaduserbyusername(string username) throws usernamenotfoundexception { 
    system.out.println("当前的用户名是:"+username); 
    //这里我为了方便,就直接返回一个用户信息,实际当中这里修改为查询数据库或者调用服务什么的来获取用户信息 
    userinfo userinfo = new userinfo(); 
    userinfo.setusername("admin"); 
    userinfo.setname("admin"); 
    set<authorityinfo> authorities = new hashset<authorityinfo>(); 
    authorityinfo authorityinfo = new authorityinfo("test"); 
    authorities.add(authorityinfo); 
    userinfo.setauthorities(authorities); 
    return userinfo; 
  }*/ 
   
   
  //实现authenticationuserdetailsservice,实现loaduserdetails方法 
  implements authenticationuserdetailsservice<casassertionauthenticationtoken> { 
 
  @override 
  public userdetails loaduserdetails(casassertionauthenticationtoken token) throws usernamenotfoundexception { 
    system.out.println("当前的用户名是:"+token.getname()); 
    /*这里我为了方便,就直接返回一个用户信息,实际当中这里修改为查询数据库或者调用服务什么的来获取用户信息*/ 
    userinfo userinfo = new userinfo(); 
    userinfo.setusername("admin"); 
    userinfo.setname("admin"); 
    set<authorityinfo> authorities = new hashset<authorityinfo>(); 
    authorityinfo authorityinfo = new authorityinfo("test"); 
    authorities.add(authorityinfo); 
    userinfo.setauthorities(authorities); 
    return userinfo; 
  } 
 
} 

(3)定义authorityinfo类,用于加载当前登录用户的权限信息,实现grantedauthority接口,代码如下:

package com.chengli.springboot.custom; 
 
import org.springframework.security.core.grantedauthority; 
 
/** 
 * 权限信息 
 * 
 * @author chengli 
 * 
 */ 
public class authorityinfo implements grantedauthority { 
  private static final long serialversionuid = -175781100474818800l; 
 
  /** 
   * 权限code 
   */ 
  private string authority; 
 
  public authorityinfo(string authority) { 
    this.authority = authority; 
  } 
 
  @override 
  public string getauthority() { 
    return authority; 
  } 
 
  public void setauthority(string authority) { 
    this.authority = authority; 
  } 
 
} 

(4)定义userinfo类,用于加载当前用户信息,实现userdetails接口,代码如下:

package com.chengli.springboot.custom; 
 
import java.util.collection; 
import java.util.hashset; 
import java.util.set; 
 
import org.springframework.security.core.grantedauthority; 
import org.springframework.security.core.userdetails.userdetails; 
 
/** 
 * 用户信息 
 * @、这里我写了几个较为常用的字段,id,name,username,password,可以根据实际的情况自己增加 
 * @author chengli 
 * 
 */ 
public class userinfo implements userdetails { 
  private static final long serialversionuid = -1041327031937199938l; 
 
  /** 
   * 用户id 
   */ 
  private long id; 
 
  /** 
   * 用户名称 
   */ 
  private string name; 
 
  /** 
   * 登录名称 
   */ 
  private string username; 
 
  /** 
   * 登录密码 
   */ 
  private string password; 
 
  private boolean isaccountnonexpired = true; 
 
  private boolean isaccountnonlocked = true; 
 
  private boolean iscredentialsnonexpired = true; 
 
  private boolean isenabled = true; 
 
  private set<authorityinfo> authorities = new hashset<authorityinfo>(); 
....省略getters setters 方法 
} 

到这里基本就已经完成了,运行cas server ,将以上的application.properties文件中的地址修改为实际的地址即可运行。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。