专栏首页品茗ITSpring和Security整合详解

Spring和Security整合详解

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包

<?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);
    }
}

3.7 过程中用到的实体

ResultModel:

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 :

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组件化构建

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • SpringCloud微服务实战系列(二十)Ouath2在真实场景中的应用之客户端接入(第二种写法)

    在《SpringCloud微服务实战系列(十七)Ouath2在真实场景中的应用之资源服务器》]中

    品茗IT
  • Spring整合Oauth2单机版认证授权详情

    OAuth 2.0 规范定义了一个授权(delegation)协议,对于使用Web的应用程序和API在网络上传递授权决策非常有用。OAuth被用在各钟各样的应用...

    品茗IT
  • SpringCloud技术指南系列(十二)API网关之Gateway使用

    API网关是一个更为智能的应用服务器,它的定义类似于面向对象设计模式中的Facade模式,它的存在就像是整个微服务架构系统的门面一样,所有的外部客户端访问都需要...

    品茗IT
  • SpringCloud微服务实战系列(二十)Ouath2在真实场景中的应用之客户端接入(第二种写法)

    在《SpringCloud微服务实战系列(十七)Ouath2在真实场景中的应用之资源服务器》]中

    品茗IT
  • Spring整合Oauth2单机版认证授权详情

    OAuth 2.0 规范定义了一个授权(delegation)协议,对于使用Web的应用程序和API在网络上传递授权决策非常有用。OAuth被用在各钟各样的应用...

    品茗IT
  • 基于Spring Cloud Oauth2 JWT搭建微服务的安全认证中心

    Oauth协议为用户资源的授权提供了一个安全的、开放而又建议的标准。oauth的授权不会是第三方初级到用户的账号信息(如用户名与密码),及第三方无需使用用户的用...

    小东啊
  • Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十五):Spring Security 版本

    到目前为止,我们使用的权限认证框架是 Shiro,虽然 Shiro 也足够好用并且简单,但对于 Spring 官方主推的安全框架 Spring Security...

    朝雨忆轻尘
  • SpringCloud技术指南系列(十二)API网关之Gateway使用

    API网关是一个更为智能的应用服务器,它的定义类似于面向对象设计模式中的Facade模式,它的存在就像是整个微服务架构系统的门面一样,所有的外部客户端访问都需要...

    品茗IT
  • SSH框架之Spring第四篇

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    海仔
  • RabbitMQ系列之极速入门与实战教程

    消息队列(Message Queue,简称MQ),其本质是个队列,FIFO(First In First OUT,先入先出),MQ主要用于不同线程之间的线程通信...

    SmileNicky

扫码关注云+社区

领取腾讯云代金券