Spring Boot 集成 Spring Security 使用
创建时间:2018-05-19  访问量:8882  6  2

Spring Boot 集成 Spring Security 使用

WebSecurityConfig类的源代码如下:

package com.zxstrive.fight.sys.config;

import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import com.zxstrive.fight.sys.extend.security.CustomAccessDeniedHandler;
import com.zxstrive.fight.sys.extend.security.CustomAuthenticationFailureHandler;
import com.zxstrive.fight.sys.extend.security.CustomAuthenticationProcessingFilter;
import com.zxstrive.fight.sys.extend.security.CustomAuthenticationSuccessHandler;
import com.zxstrive.fight.sys.extend.security.CustomLogoutHandler;
import com.zxstrive.fight.sys.extend.security.CustomUserDetailsService;
import com.zxstrive.fight.sys.extend.security.UnauthorizedEntryPoint;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
    //自动注入认证管理器
	@Autowired
	private AuthenticationManager authenticationManager;
	
    //向Spring容器中加入自定义认证失败处理,可以自由处理同步或异步返回
	@Bean
	public CustomAuthenticationFailureHandler failureHandler() {
		return new CustomAuthenticationFailureHandler();
	}
	
    //向Spring容器中加入自定义认证成功处理器,也是为了能够同时处理同步和异步登录
	@Bean
	public CustomAuthenticationSuccessHandler successHandler() {
		return new CustomAuthenticationSuccessHandler();
	}
	
    //自己登录拒绝处理器,一般是无权访问时执行
	@Bean
	public CustomAccessDeniedHandler accessDeniedHandler() {
		return new CustomAccessDeniedHandler();
	}
	
    //自定义认证过程中的过滤器,这里加入了验证码过滤,后面会有源码
	@Bean
	public CustomAuthenticationProcessingFilter captchaProcessingFilter() {
		CustomAuthenticationProcessingFilter captchaProcessingFilter = new CustomAuthenticationProcessingFilter();
		captchaProcessingFilter.setAuthenticationFailureHandler(failureHandler());
		captchaProcessingFilter.setAuthenticationManager(authenticationManager);
		return captchaProcessingFilter;
	}
	
    //加载自定义用户信息服务,即自定义UserDetailsService,后面会给出介绍
	@Bean
	@Qualifier("localUserDetailsService")
	public UserDetailsService localUserDetailsService(){
		return new CustomUserDetailsService();
	}

    //这里是核心配置
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		
		/**
		 * 加入验证码过滤功能,将验证码过滤器添加到用户名密码认证之前
		 */
		http.addFilterBefore(captchaProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
		
		
		/**
		 * http 登录配置
		 */
		http
			.authorizeRequests()
			.antMatchers("/admin/**")    //本系统所有以/admin开头的请求都会被安全策略拦截,其它路径请求通过
			.authenticated()
			.anyRequest()
			.permitAll()
		.and()
			.formLogin()
			.loginPage("/login")   //指定登录页面,这个/login是通过Spring MVC路径,将返回登录页面视图
			.loginProcessingUrl("/loginProcess") //同理,登录请求,也就是登录表单中的action。
			.failureHandler(failureHandler()) //添加登录失败处理器
			.permitAll()
			.usernameParameter("loginName")   //登录提交认证的用户名的参数名
			.passwordParameter("password")    //登录提交认证的密码的请求参数名
			.successHandler(successHandler()) //成功处理器
		.and()
			.exceptionHandling()  //异常处理
			.accessDeniedHandler(accessDeniedHandler())   //拒绝请求处理
			.authenticationEntryPoint(new UnauthorizedEntryPoint())    //自定义的未授权异常处理
		.and()
			.logout()
			.logoutUrl("/logout")    //注销地址
			.logoutSuccessHandler(new CustomLogoutHandler())   //注销成功处理
			.permitAll()
		.and()
			.rememberMe()
			.tokenValiditySeconds(3600 * 24 * 7)
			.rememberMeCookieName("authentication")
			.rememberMeParameter("rememberMe")
			.key("fight")    //以上是SpringSecurity记住我规则,使用Cookie记住一周时间,key为cookie键名
		.and()   //此处配置同源策略
			.headers()
			.frameOptions()
			.sameOrigin()
		.and()    //此处配置csrf
			.csrf()
			.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
		.and()
			.httpBasic()
		.and() //此处配置Session数量,如果登录超过2个,则另一个被退出,被退出跳到/login?expired页面,并提示
			.sessionManagement()
			.maximumSessions(1)
			.expiredUrl("/login?expired");
		
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(localUserDetailsService())    //注入自定义UserDetailsService
			.passwordEncoder(new PasswordEncoder() {    //自定义密码认证规则

				@Override
				public String encode(CharSequence rawPassword) {
					return rawPassword.toString();
				}

				@Override
				public boolean matches(CharSequence rawPassword, String encodedPassword) {
					rawPassword = Md5Crypt.md5Crypt(String.valueOf(rawPassword).getBytes(), "$1$fight$");
					return rawPassword.equals(encodedPassword);//比对加密后的算法为true认证成功
				}
				
			});
	}
	
}

这是SpringBoot中的Java注解配置。