代码已上传至Github 地址:https://github.com/ylw-github/Spring-Security-CAS-Demo.git
Spring Security测试工程搭建SpringSecurity工程以前有上传到Github,直接拿来使用(地址:https://github.com/YangLinWei93/Spring-Security-Demo.git)
Spring Security 与 CAS 集成(1)引入依赖
org.springframework.security
spring-security-cas
4.1.0.RELEASE
org.jasig.cas.client
cas-client-core
3.3.3
org.slf4j
log4j-over-slf4j
(2)修改 spring-security.xml
(3)创建 UserDetailsServiceImpl
package com.pyg;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//构建角色集合
List authorities=new ArrayList();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(username, "" , authorities);
}
}
获取登录名
我们在处理后端逻辑需要获得登录名,那么如何获取单点登录的用户名呢? 其实和我们之前获得用户名的方式是完全相同的,我们下面来做个测试。
创建 UserController
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/findLoginUser")
public void findLoginUser() {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
System.out.println(name);
}
}
退出登录
修改 spring-security.xml
退出登录
创建 index2.html,将 index2.html 设置为可匿名访问