Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
Git地址:
品茗IT:提供在线快速构建Spring项目工具。
**如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以<a
href="https://jq.qq.com/?_wv=1027&k=52sgH1J"
target="_blank">
加入我们的java学习圈,点击即可加入
</a>
,共同学习,节约学习时间,减少很多在学习中遇到的难题。**
<?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
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>
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对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。
这里我们要讲一下:
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);
}
}
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;
}
}
我们可以定义一个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组件化构建中选择查看,并下载。