Spring和Security整合详解

Spring和Security整合详解

一、官方主页

Spring Security

二、概述

Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

Git地址:
Gitee

项目地址:
品茗IT-同步发布

品茗IT 提供在线支持:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

三、开始搭建

3.1 依赖Jar包
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.pomit</groupId>
		<artifactId>SpringWork</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>Security</artifactId>
	<packaging>jar</packaging>
	<name>Security</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>cn.pomit</groupId>
			<artifactId>Mybatis</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>Security</finalName>
	</build>
</project>

父pom管理了所有依赖jar包的版本,地址:
https://www.pomit.cn/spring/SpringWork/pom.xml

3.2 web.xml配置Security

Spring整合Security需要配置Security的安全控制策略,首先需要在web.xml中配置Spring Security的filter。

在web.xml中加入这几行即可:

<!-- Spring Security 的过滤配置,表明请求需要经过这个类的过滤和判断 -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
3.3 Security的安全配置

Spring整合Security需要配置Security的安全控制策略,这里先以form登录控制为例,后面文章会讲token系列《Spring和Token整合详解》

FormSecurityConfig依赖于其他组件,后面会一一列出:

package cn.pomit.springwork.security.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationDetailsSource;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import cn.pomit.springwork.security.ajax.AjaxAuthFailHandler;
import cn.pomit.springwork.security.ajax.AjaxAuthSuccessHandler;
import cn.pomit.springwork.security.ajax.AjaxLogoutSuccessHandler;
import cn.pomit.springwork.security.ajax.UnauthorizedEntryPoint;
import cn.pomit.springwork.security.service.SimpleAuthenticationProvider;

@EnableWebSecurity
public class FormSecurityConfig {

	@Configuration                                                   
	public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
		@Autowired
		private SimpleAuthenticationProvider simpleAuthenticationProvider;
		
		@Autowired
		@Qualifier("formAuthenticationDetailsSource")
		private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;
		
		@Autowired
		public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
			auth.authenticationProvider(simpleAuthenticationProvider);
		}

		@Override
		public void configure(HttpSecurity http) throws Exception {
			http.csrf().disable().exceptionHandling()
					.authenticationEntryPoint(new UnauthorizedEntryPoint())
					.and().headers()
					.frameOptions().disable().and().authorizeRequests()
					.antMatchers("/favicon.ico").permitAll()
					.antMatchers("/login").permitAll()
					.antMatchers("/login.html").permitAll()
					.antMatchers("/css/**").permitAll()
					.antMatchers("/pub/**").permitAll()
					.antMatchers("/user/**").hasAnyRole("USER","ADMIN")
					.anyRequest().authenticated()
					.and()
					.formLogin()
				  	.usernameParameter("userName").passwordParameter("userPwd")
				  	.authenticationDetailsSource(authenticationDetailsSource)
					.loginProcessingUrl("/login")
					.successHandler(new AjaxAuthSuccessHandler())
					.failureHandler(new AjaxAuthFailHandler())
					.and()
					.logout()
					.logoutUrl("/logout").logoutSuccessHandler(new AjaxLogoutSuccessHandler());
		}
	}
}

这里面:

  • SimpleAuthenticationProvider 是对安全认证的处理逻辑。校验用户名密码的

  • AuthenticationDetailsSource,其实是不必要的,但是用它我们可以获取除了用户名密码以外的信息,比如验证码之类的。

  • AjaxAuthSuccessHandler 认证成功处理器。

  • AjaxAuthFailHandler 认证失败处理器。

  • AjaxLogoutSuccessHandler 登出处理器。

  • UnauthorizedEntryPoint 未授权处理器。

3.4 Security的校验逻辑

SimpleAuthenticationProvider对form登录校验做了简单的控制:

package cn.pomit.springwork.security.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.pomit.springwork.mybatis.domain.UserInfo;
import cn.pomit.springwork.mybatis.service.UserInfoService;
import cn.pomit.springwork.security.detail.FormAddUserDetails;

@Component
public class SimpleAuthenticationProvider implements AuthenticationProvider {
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// 验证码等校验
		FormAddUserDetails details = (FormAddUserDetails) authentication.getDetails();

		System.out.println(details.getToken() + "+++++++++++++++++" + details.getSessionToken());
		if (StringUtils.isEmpty(details.getSessionToken()) || StringUtils.isEmpty(details.getToken())
				|| !details.getToken().equalsIgnoreCase(details.getSessionToken())) {
			throw new BadCredentialsException("验证码错误。");

		}

		String userName = authentication.getPrincipal().toString();
		UserInfo user = userInfoService.getUserInfoByUserName(userName);

		if (user == null) {
			throw new BadCredentialsException("查无此用户");
		}
		if (user.getPasswd() != null && user.getPasswd().equals(authentication.getCredentials())) {
			Collection<? extends GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;

			return new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPasswd(), authorities);
		} else {
			throw new BadCredentialsException("用户名或密码错误。");
		}
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}

这里用到了UserInfoService ,它是个查询数据库的一个service,UserInfoService是依赖包Mybatis项目中定义的一个数据库访问的service,这里就不写了,可以在快速构建Spring项目工具中查看Mybatis组合组件的代码。

很多博文写到Spring的一个接口:UserDetailsService。
这里我们要讲一下:

  • SimpleAuthenticationProvider控制了校验,需要数据库配合查询用户名密码,和前台传过来的用户名密码做对比,因此,需要一个获取用户信息的service。

  • UserDetailsService是spring定义的接口,用来获取用户信息的。

  • UserDetailsService只有在不使用AuthenticationProvider的情况下需要,因为AuthenticationProvider是自定义处理过程,比如我们的SimpleAuthenticationProvider,自己都实现了处理逻辑,还要UserDetailsService个屁啊!

3.5 额外安全信息处理

FormAuthenticationDetailsSource负责将request对象拿到并交给WebAuthenticationDetails,WebAuthenticationDetails是Authentication的一部分,这样我们在AuthenticationProvider的实现类中就能通过authentication.getDetails()拿到额外信息。

FormAuthenticationDetailsSource:

package cn.pomit.springwork.security.service;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import cn.pomit.springwork.security.detail.FormAddUserDetails;

@Component("formAuthenticationDetailsSource")
public class FormAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {

    @Override
    public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
        return new FormAddUserDetails(context);
    }


}

FormAddUserDetails:

package cn.pomit.springwork.security.detail;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.authentication.WebAuthenticationDetails;


public class FormAddUserDetails extends WebAuthenticationDetails{
	 /**
     * 
     */
    private static final long serialVersionUID = 6975601077710753878L;
    private final String token;
    private final String sessionToken;
    private final Boolean isAjax;
    public FormAddUserDetails(HttpServletRequest request) {
        super(request);
        isAjax = isAjaxRequest(request);
        token = request.getParameter("imgtoken");
        sessionToken = (String) request.getSession().getAttribute("imgtoken");
    }

    public String getToken() {
        return token;
    }

    public String getSessionToken() {
		return sessionToken;
	}

	public Boolean getIsAjax() {
		return isAjax;
	}

	@Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString()).append("; Token: ").append(this.getToken());
        return sb.toString();
    }
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }

}

FormAddUserDetails 需要拿到session中存在的验证码,然后把传过来的验证码都保存下来。

3.6 安全控制处理器

FormSecurityConfig中我们配置了很多处理器,有UnauthorizedEntryPoint、AjaxAuthFailHandler、AjaxAuthSuccessHandler、AjaxLogoutSuccessHandler。
顾名思义,这些是分别处理未授权、校验失败、校验成功、登出操作的,我们这里区分下ajax请求和跳转请求。

UnauthorizedEntryPoint:

package cn.pomit.springwork.security.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if(isAjaxRequest(request)){
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage());
        }else{
            response.sendRedirect("/login.html");
        }

    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}

AjaxAuthFailHandler:

package cn.pomit.springwork.security.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

public class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if(isAjaxRequest(request)){
        	response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
        }else{
        	setDefaultFailureUrl("/login.html");
        	super.onAuthenticationFailure(request, response, exception);
        }
    }
    
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}

AjaxAuthSuccessHandler:

package cn.pomit.springwork.security.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.pomit.springwork.security.ResultModel;

public class AjaxAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	protected final Log logger = LogFactory.getLog(this.getClass());
	
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    	request.getSession().setAttribute("userName", authentication.getName());
    	if(isAjaxRequest(request)){
    		ResultModel rm = new ResultModel("ok");
    		ObjectMapper mapper = new ObjectMapper();
    		response.setStatus(HttpStatus.OK.value());
    		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    		mapper.writeValue(response.getWriter(), rm);
    	}else{
    		super.onAuthenticationSuccess(request, response, authentication);
        }
    }
    
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}


AjaxLogoutSuccessHandler:

package cn.pomit.springwork.security.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

public class AjaxLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler{
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		if(isAjaxRequest(request)){
    		response.setStatus(HttpServletResponse.SC_OK);
    	}else{
    		super.onLogoutSuccess(request, response, authentication);
        }
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}


详细完整及测试代码,可以在《品茗IT-Spring和Security整合详解》中查看,也可以在Spring组件化构建中选择并下载。

快速构建项目

Spring组件化构建
喜欢这篇文章么,喜欢就加入我们一起讨论Spring技术吧!
品茗IT交流群

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值