从零开始java安全权限框架篇(七):spring security整合Redis实现session共享

本文详细介绍了如何使用Spring Security结合Spring Session实现在分布式环境下的session共享,包括配置、自定义session管理、用户锁定机制的实现。文章还讨论了在实现过程中遇到的问题和解决方案,如登录验证、记住我功能、权限检验等,并提供了完整代码链接。
摘要由CSDN通过智能技术生成

目录

 

一:spring security整合spring session实现session共享

二:代码

        1.springsecurity的配置文件

        2.自定义的session管理

三:获取到当前的所有用户以及踢出一个用户

四:用户锁定

1.我们先来看看锁定的时序图

2.流程解析

3.代码

(1)登录流程验证验证

(2)登录失败加锁

五:安全权限的总结

1.为什么要用Spring security

2.为什么要大量自定义和重写security的框架方法

3.主要的技术要点

4.主要实现功能


一:spring security整合spring session实现session共享

  其实这边坑还是还是很多了,我照着官网整合了半天,发现记住我的功能用不了(真的是springboot的几个版本都是用不了的)。然后就想跳过这个功能,毕竟之前也弄到过Redis上去了。那就去实现基于Redis的Session共享吧,结果整出来发现官网上一个说明心态崩了。

  我这边也尝试了用spring session整合来实现session共享,但是不知道为何很多Bug无法解决。比如记住我功能的无法实现,因为每一次都需要重写Cookie的机制很不好弄然后session共享也没办法获取到所有的用户等。最后,只能重写speing security的方法了具体实现如下:主要是就是Session共享。(完整代码块在最后)

二:代码

1.springsecurity的配置文件

package com.config.Seurity;






import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.session.HttpSessionEventPublisher;





import org.springframework.stereotype.Repository;

import com.config.Seurity.hander.AjaxSuccessHander;
import com.config.Seurity.hander.AjaxfailHander;

import com.config.Seurity.permission.CustomPermissionEvaluator;
import com.config.Seurity.pwdEnder.MyPasswordEncoder;
import com.config.Seurity.repository.MyPersistentTokenRepository;
import com.config.Seurity.repository.MySessionRegistryImpl;
import com.config.Seurity.service.LoginService;







/**
 * spring security的配置
 * ClassName: SecurityConfig 
 * Function: 一句话描述功能. 
 * auth: monxz
 * date: 2019年8月28日 上午10:04:50 
 * @param <S>
 *
 *
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
		@Autowired
		private LoginService loginService;
		
		
		
		//静态文件夹忽略
		private String[] allowedRes= {"/static/**","/css/**","/js/**","/my/**","/img/**","/ajax/**","favicon.ico"};
		
		//不需要验证的
		private String[]  allowedUrl= {"/api/**","/user/user/current"};


		//登录执行的逻辑
		 @Autowired
		 public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
		      auth.userDetailsService(loginService).passwordEncoder(new MyPasswordEncoder());
		     
		  }

		 
		//配置信息
		 @Override
		    protected void configure(HttpSecurity http) throws Exception { 
			 	
		       
			 	//配置访问权限
		        http.authorizeRequests()
		        		//允许匿名访问(如api)
		                .antMatchers(allowedUrl)
		                .permitAll()		                        
		                //其他地址的访问均需验证权限
		                .anyRequest()
		                .authenticated();
		        		
		        
		         //配置登录以及成功失败的处理方式
		         http.formLogin()		               
		                //指定登录页是"/view/login"   
		                .loginPage("/view/login").permitAll()    //
		                
		                
		                //ajax方式登录		               
		                .successHandler(new AjaxSuccessHander())
		                .failureHandler(new AjaxfailHander())
		                .loginProcessingUrl("/login")
		                .usernameParameter("username")  //ajax请求必须的
		                .passwordParameter("password");
		                
		                //form表单登录
//		                .defaultSuccessUrl("/view/index")       //登录成功后默认跳转到路径"
		               
		                
		         //注销 ,直接访问   ip:port/logout		
		         http .logout()
		                .logoutSuccessUrl("/view/login")          //退出登录后跳转到登录主界面"
		                .deleteCookies()						//有记住我功能,删除cookie
		                .permitAll();
		         	
		                
		         //记住我
		         http.rememberMe()
		         .tokenRepository(persistentTokenRepository())
		          		.tokenValiditySeconds(60*15)
		          		
		          	
		          		;
		          		

		         
		                //跨域以及其他的一些配置
		         http .csrf()
		         	  .disable()   // 关闭CSRF跨域
		              .headers()
		              .frameOptions()
		              .sameOrigin();  // 允许加载frame子菜单
		        
		         http.sessionManagement()
//		         	 .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
		         	 .sessionFixation()
		         	 .migrateSession()
		             .invalidSessionUrl("/view/login")
		             .maximumSessions(1)
		             .expiredUrl("/view/login")
		             .sessionRegistry(sessionRegistry())		             
		             ;
		       
		         

		    }
		 
		
		 
		 
		 //静态资源
		 @Override
		  public void configure(WebSecurity web) throws Exception {
			 			
		        // 设置拦截忽略文件夹,可以对静态资源放行
		        web.ignoring().antMatchers(allowedRes);
		   }
		 
//================================权限认证=======================================		 
		 
		 // 注入自定义url和权限验证器	     
		    @Bean
		    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
		        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
		        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
		        return handler;
		    }
			
		
//==========================session管理==================
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值