Spring Security
Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
Git地址:
Gitee
项目地址:
品茗IT-同步发布
品茗IT 提供在线支持:
一键快速构建Spring项目工具
一键快速构建SpringBoot项目工具
一键快速构建SpringCloud项目工具
一站式Springboot项目生成
如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。
<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.0modelVersion>
<parent>
<groupId>cn.pomitgroupId>
<artifactId>SpringWorkartifactId>
<version>0.0.1-SNAPSHOTversion>
parent>
<artifactId>SecurityartifactId>
<packaging>jarpackaging>
<name>Securityname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-coreartifactId>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-configartifactId>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
<dependency>
<groupId>cn.pomitgroupId>
<artifactId>MybatisartifactId>
<version>${project.version}version>
dependency>
dependencies>
<build>
<finalName>SecurityfinalName>
build>
project>
父pom管理了所有依赖jar包的版本,地址:
https://www.pomit.cn/spring/SpringWork/pom.xml
Spring整合Security需要配置Security的安全控制策略,首先需要在web.xml中配置Spring Security的filter。
在web.xml中加入这几行即可:
<filter>
<filter-name>springSecurityFilterChainfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSecurityFilterChainfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
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 未授权处理器。
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个屁啊!
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中存在的验证码,然后把传过来的验证码都保存下来。
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组件化构建中选择并下载。