生成Spring Boot 使用Spring security 集成CAS详细代码 并写出注解
时间: 2024-04-23 08:23:47 浏览: 186
详解Spring Boot 使用Spring security 集成CAS
好的,下面是使用Spring Boot集成Spring Security和CAS的详细代码和注解:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<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>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.4.1</version>
</dependency>
```
2. 配置CAS
在application.properties文件中添加以下配置:
```properties
cas.server.url.prefix=https://cas.server.com:8443/cas
cas.server.login.url=https://cas.server.com:8443/cas/login
cas.server.logout.url=https://cas.server.com:8443/cas/logout
cas.client.server-name=https://your-app.com:8443
```
3. 配置Spring Security
创建一个SecurityConfig类,添加以下配置:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CasAuthenticationProvider casAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(casAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/")
.and().exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint())
.and().addFilter(casAuthenticationFilter())
.addFilterBefore(casValidationFilter(), CasAuthenticationFilter.class);
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setFilterProcessesUrl("/login/cas");
return filter;
}
@Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
entryPoint.setLoginUrl(casServerLoginUrl());
entryPoint.setServiceProperties(serviceProperties());
return entryPoint;
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider provider = new CasAuthenticationProvider();
provider.setAuthenticationUserDetailsService(authenticationUserDetailsService());
provider.setServiceProperties(serviceProperties());
provider.setTicketValidator(cas30ServiceTicketValidator());
provider.setKey("casAuthProviderKey");
return provider;
}
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setService(casClientServiceUrl());
serviceProperties.setSendRenew(false);
return serviceProperties;
}
@Bean
public AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService() {
return new UserDetailsServiceImpl();
}
@Bean
public Cas30ServiceTicketValidator cas30ServiceTicketValidator() {
return new Cas30ServiceTicketValidator(casServerUrlPrefix());
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(casServerUrlPrefix());
}
@Bean
public Cas20ProxyTicketValidator cas20ProxyTicketValidator() {
return new Cas20ProxyTicketValidator(casServerUrlPrefix());
}
@Bean
public Cas10TicketValidationFilter casValidationFilter() {
return new Cas10TicketValidationFilter(casServerUrlPrefix());
}
@Value("${cas.server.url.prefix}")
private String casServerUrlPrefix;
public String casServerUrlPrefix() {
return casServerUrlPrefix;
}
@Value("${cas.server.login.url}")
private String casServerLoginUrl;
public String casServerLoginUrl() {
return casServerLoginUrl;
}
@Value("${cas.client.server-name}")
private String casClientServiceUrl;
public String casClientServiceUrl() {
return casClientServiceUrl;
}
}
```
4. 创建UserDetailsServiceImpl类
该类实现AuthenticationUserDetailsService接口,用于从CAS服务器返回的认证信息中提取用户信息。
```java
@Service
public class UserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
@Override
public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
// 从认证信息中获取用户名
String username = token.getName();
// 根据用户名查询用户信息
User user = userRepository.findByUsername(username);
// 判断用户是否存在
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
// 构造Spring Security的UserDetails对象
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
return new org.springframework.security.core.userdetails.User(user.getUsername(), "", authorities);
}
}
```
5. 创建HomeController类
该类用于展示登录页面和当前登录用户的信息。
```java
@Controller
public class HomeController {
@GetMapping("/")
public String home(Authentication authentication) {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
}
```
6. 创建login.html和home.html
login.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form th:action="@{/login/cas}" method="post">
<button type="submit">Login with CAS</button>
</form>
</body>
</html>
```
home.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1 th:text="${authentication.name}"></h1>
<form action="/logout" method="post">
<button type="submit">Logout</button>
</form>
</body>
</html>
```
以上就是Spring Boot集成Spring Security和CAS的详细代码和注解。希望能对你有所帮助!
阅读全文