您当前的位置: 首页 >  spring

77分布式电商项目 - CAS 客户端与 SpringSecurity 集成

杨林伟 发布时间:2019-07-18 15:26:31 ,浏览量:4

代码已上传至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 设置为可匿名访问


关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 4浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0750s