一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 詳解Spring Boot 使用Spring security 集成CAS

詳解Spring Boot 使用Spring security 集成CAS

2020-10-28 15:21成立_ChengLi Java教程

本篇文章主要介紹了詳解Spring Boot 使用Spring security 集成CAS,具有一定的參考價值,感興趣的小伙伴們可以參考一下

1.創建工程

創建Maven工程:springboot-security-cas

2.加入依賴

創建工程后,打開pom.xml,在pom.xml中加入以下內容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<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文件,加入以下內容:

?
1
2
3
4
5
6
7
8
9
10
11
12
#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,完整代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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,完整代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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 當前的環境,代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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類,代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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接口,代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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接口,代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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文件中的地址修改為實際的地址即可運行。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/cl_andywin/article/details/53998986

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 99精品久久精品一区二区 | 吃胸膜奶视频456 | 欧美日韩国产超高清免费看片 | 视频在线观看高清免费 | 女老板用丝袜脚夹我好爽 | 亚洲国产精品成人综合久久久 | 妹妹骑上来蹭着蹭着就射了 | 亚洲黄色成人 | 四虎免费在线观看视频 | 美女被扒开屁股进去网 | 视频一区国产精戏刘婷30 | 国产精品久久久久无毒 | 天天干夜夜添 | 毛片手机在线视频免费观看 | 日本黄色高清视频网站 | 日韩高清在线观看 | 欧美一级特黄特色大片 | 精品成人在线 | 色妞视频一级毛片 | 97久久久亚洲综合久久88 | 故意短裙公车被强好爽在线播放 | 免费一级毛片在线播放放视频 | 亚洲国产成人精品无码区5566 | 九九精品免视看国产成人 | 九哥草逼网| 把内裤拔到一边高h1v1 | 亚洲天堂网站在线 | 亚洲一区二区三区福利在线 | 天堂在线国产 | 欧洲美女人牲交一级毛片 | 好女孩韩剧免费观看 | 四虎精品成人免费视频 | 欧美日韩一二三区免费视频观看 | 欧美一级h | 高清视频在线观看+免费 | 二次元美女脱裤子让男人桶爽 | xnxx18美女| 亚洲视频999| 日韩一二三 | 精品无码国产AV一区二区三区 | jizz 日本亚洲|