前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring和Security整合详解

Spring和Security整合详解

作者头像
品茗IT
发布2019-09-12 09:51:24
9400
发布2019-09-12 09:51:24
举报
文章被收录于专栏:品茗IT品茗IT

Spring和Security整合详解

一、官方主页

Spring Security

二、概述

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

Git地址:

Gitee

品茗IT:提供在线快速构建Spring项目工具。

**如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以<a

href="https://jq.qq.com/?_wv=1027&k=52sgH1J"

target="_blank">

加入我们的java学习圈,点击即可加入

</a>

,共同学习,节约学习时间,减少很多在学习中遇到的难题。**

三、开始搭建

3.1 依赖Jar包
代码语言:javascript
复制
<?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中加入这几行即可:

代码语言:javascript
复制
<!-- 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依赖于其他组件,后面会一一列出:

代码语言:javascript
复制
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登录校验做了简单的控制:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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);
    }
}
3.7 过程中用到的实体

ResultModel:

代码语言:javascript
复制
package cn.pomit.springwork.security;

public class ResultModel {
	String code;
	String message;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ResultModel() {
	}

	public ResultModel(String messgae) {
		this.code = "0000";
		this.message = messgae;
	}
}
3.8 测试

我们可以定义一个web请求控制器SecurityRest来做简单测试,这里将忽略Springmvc的配置,配置MVC可以在SpringMvc4 配置方法中查看,SpringMvc5 配置方法中查看。

SecurityRest :

代码语言:javascript
复制
package cn.pomit.springwork.security.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springwork.security.ResultModel;

@RestController
@RequestMapping("/pub")
public class SecurityRest {

	@RequestMapping(value = "/code", method = { RequestMethod.GET })
	public ResultModel welCome(HttpServletRequest request) {
		String code = "1234";
		request.getSession().setAttribute("imgtoken", code);
		return new ResultModel("ok");
	}

	
}

详细完整代码,可以在Spring组件化构建中选择查看,并下载。

快速构建项目

Spring组件化构建

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring和Security整合详解
    • 一、官方主页
      • 二、概述
        • 三、开始搭建
          • 3.1 依赖Jar包
          • 3.2 web.xml配置Security
          • 3.3 Security的安全配置
          • 3.4 Security的校验逻辑
          • 3.5 额外安全信息处理
          • 3.6 安全控制处理器
          • 3.7 过程中用到的实体
          • 3.8 测试
        • 快速构建项目
        相关产品与服务
        验证码
        腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档