最近整理一个二手后台管理项目,整体大体可分为 : Springmvc + mybatis + tiles + easyui + security 这几个模块,再用maven做管理。刚拿到手里面东西实在太多,所以老大让重新整一个,只挑出骨架。不可否认,架构整体规划得还是很好的,尤其是前端界面用tiles+easyui ,开发很高效!其实,之前虽然听说过security,但做过的项目都没用过security,所以也算是一个新手!整合过程还是很烧脑的。

1、首先是springmvc部分,也是框架的最核心骨架部分。springmvc也是基于servlet框架完成的,所以我们都可以从web.xml入手,然后顺藤摸瓜,整理出整个架构。web.xml中主要部分是放置spring的各种配置:

[java] view plaincopy
  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>
  4. /WEB-INF/spring/appServlet/servlet-context.xml
  5. </param-value>
  6. </context-param>

[html] view plaincopy
  1. <servlet>
  2. <servlet-name>appServlet</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <init-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
  7. </init-param>
  8. <load-on-startup>1</load-on-startup>
  9. <async-supported>true</async-supported>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>appServlet</servlet-name>
  13. <url-pattern>/</url-pattern>
  14. </servlet-mapping>

这两部分指定了配置文件地址和web请求地址拦截规则。需要注意的是,然后配置文件里就是常用的注解、数据源、之类的,不一而足。

2、然后是security,本文实现了自定义的用户信息登录认证,主要部分:spring的security主要注意几个地方:

1)web.xml中配置security必须的过滤器,注意名字必须是springSecurityFilterChain,这是内置的过滤器;然后将过滤规则设置为/*,表示对所有请求都拦截。

2)  关于security的配置文件必须在<context-param>中加入,因为ContextLoaderListener在加载的时候就会去加载security相关的东西,而此时springmvc(servlet)模块还没有初始化。

二者配置如下:

[java] view plaincopy
  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>
  4. /WEB-INF/spring/appServlet/servlet-context.xml
  5. </param-value>
  6. </context-param>
  7. <!-- Creates the Spring Container shared by all Servlets and Filters -->
  8. <listener>
  9. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  10. </listener>
  11. <!-- 用户权限模块 -->
  12. <filter>
  13. <filter-name>springSecurityFilterChain</filter-name>
  14. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  15. </filter>
  16. <filter-mapping>
  17. <filter-name>springSecurityFilterChain</filter-name>
  18. <url-pattern>/*</url-pattern>
  19. </filter-mapping>

本文中security配置文件再servlet-context.xml中被引入,形如:

[java] view plaincopy
  1. <beans:import resource="spring-security.xml"/>

3)spring-security.xml配置文件:

现在来看这个xml文件:

首先 <http>标签部分声明了访问拦截规则,这是security的关键。在这部分,我们先声明了一些不需要验证的资源和访问路径;然后是地址拦截规则部分:该部分拦截路径是/**,**表示可以跨目录结构,因此此处拦截该站点所有请求(除之前声明security=“none”的以外),然后拦截规则access="isAuthenticated()",这是SecurityExpressionRoot中的判断是否认证过的方法之一,跟hasRole()类似,官方描述是Returns true if the user is not anonymous ,也就是用户认证后返回true。

[java] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"
  3. xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:security="http://www.springframework.org/schema/security"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  7. http://www.springframework.org/schema/security
  8. http://www.springframework.org/schema/security/spring-security-3.2.xsd">
  9. <!-- For Web security -->
  10. <http pattern="/js/**" security="none"/>
  11. <http pattern="/images/**" security="none"/>
  12. <http pattern="/mgmt/**" security="none"/>
  13. <http pattern="/image_sys/**" security="none"/>
  14. <http pattern="/style/**" security="none"/>
  15. <http pattern="/view/login.jsp" security="none"/>
  16. <http pattern="/view/login/forgotPassword.jsp" security="none"/>
  17. <http pattern="/securityCodeImage.html" security="none"/>
  18. <http pattern="/checkSecurityCode.html" security="none"/>
  19. <http pattern="/admin/validateMobile.html" security="none"/>
  20. <http pattern="/verifycode/sendVerifyCode.html" security="none"/>
  21. <http pattern="/admin/resetPassword.html" security="none"/>
  22. <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint" access-denied-page="/view/403.jsp">
  23. <intercept-url pattern="/**" access="isAuthenticated()" />
  24. <remember-me />
  25. <!--  <expression-handler ref="webSecurityExpressionHandler"/> -->
  26. <custom-filter ref="loginFilter"  position="FORM_LOGIN_FILTER" />
  27. <logout logout-url="/j_spring_security_logout" logout-success-url="/view/login.jsp" delete-cookies="JSESSIONID"/>
  28. </http>
  29. <!-- 未登录的切入点 -->
  30. <beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  31. <beans:property name="loginFormUrl" value="/view/login.jsp"></beans:property>
  32. </beans:bean>
  33. <!-- 登录体系loginFilter -->
  34. <beans:bean id="loginFilter"
  35. class="com.security.AdminUsernamePasswordAuthenticationFilter">
  36. <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
  37. <beans:property name="authenticationSuccessHandler" ref="myAuthenticationSuccessHandler"></beans:property>
  38. <beans:property name="authenticationFailureHandler" ref="myAuthenticationFailureHandler"></beans:property>
  39. <beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
  40. </beans:bean>
  41. <!-- 验证失败显示页面 -->
  42. <beans:bean id="myAuthenticationFailureHandler"
  43. class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  44. <beans:property name="defaultFailureUrl" value="/view/login.jsp?error=true" />
  45. </beans:bean>
  46. <!-- 验证成功默认显示页面  -->
  47. <beans:bean id="myAuthenticationSuccessHandler"
  48. class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  49. <beans:property name="alwaysUseDefaultTargetUrl" value="true" />
  50. <!--此处可以请求登录首页的action地址  -->
  51. <beans:property name="defaultTargetUrl" value="/index/homepage" />
  52. </beans:bean>
  53. <!-- authentication体系 -->
  54. <authentication-manager alias="authenticationManager" erase-credentials="false">
  55. <authentication-provider ref="authenticationProvider" />
  56. </authentication-manager>
  57. <beans:bean id="authenticationProvider"
  58. class="com.security.AdminAuthenticationProvider">
  59. <beans:property name="userDetailsService" ref="userDetailsService" />
  60. </beans:bean>
  61. <beans:bean id="userDetailsService"
  62. class="com.security.AdminUserDetailsService">
  63. <beans:property name="adminService" ref="adminServiceImpl"></beans:property>
  64. </beans:bean>
[java] view plaincopy
  1. </beans:beans>

然后声明了自定义的用户登录的拦截器loginFilter,用于在登录时实现security认证。spring的登录认证模块执行顺序为:

1、UsernamePasswordAuthenticationFilter的attemptAuthentication()方法,此部分可以做用户名密码的判断,正确后继续执行;

2、接下来调用AuthenticationManager的authenticate()方法(中途具体怎么调用此处不深究),一个Mannager对应了多个authenticationProvider,其实最终是通过调用provider的authenticate()方法来进行认证的,只要provider的supports方法返回true即可声明该provider或可进行认证,最后将被manager调用。在authenticate()方法中,调用UserDetails的loadUserByUserName()方法来加载登录用户信息,包括权限信息,最后封装成AbstractAuthenticationToken,这个对象就是security模块认证后的用户完整信息。

自定义认证主要类如下:
[java] view plaincopy
  1. /**
  2. * 用户登录验证步骤一:attemptAutentication()
  3. */
  4. public class AdminUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  5. public static final String VALIDATE_CODE = "validateCode";
  6. public static final String USERNAME = "j_username";
  7. public static final String PASSWORD = "j_password";
  8. public static final String EMPLOYEENO = "j_employeeNo";
  9. @Resource
  10. private AdminService adminService;
  11. @Override
  12. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  13. throws AuthenticationException {
  14. if (!request.getMethod().equals("POST")) {
  15. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  16. }
  17. // 判断用户信息
  18. // UsernamePasswordAuthenticationToken实现 Authentication
  19. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
  20. adminModel.getAdminId(), password);
  21. // 允许子类设置详细属性
  22. setDetails(request, authRequest);
  23. // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
  24. return this.getAuthenticationManager().authenticate(authRequest);
  25. }
  26. @Override
  27. protected String obtainUsername(HttpServletRequest request) {
  28. Object obj = request.getParameter(USERNAME);
  29. return null == obj ? "" : obj.toString();
  30. }
  31. @Override
  32. protected String obtainPassword(HttpServletRequest request) {
  33. Object obj = request.getParameter(PASSWORD);
  34. return null == obj ? "" : obj.toString();
  35. }
  36. }
[java] view plaincopy
  1. /**
  2. * <span style="font-family: Arial, Helvetica, sans-serif;">用户登录验证步骤二:</span><span style="font-family: Arial, Helvetica, sans-serif;">authenticate</span><span style="font-family: Arial, Helvetica, sans-serif;">()</span><span style="font-family: Arial, Helvetica, sans-serif;">
  3. </span> */
  4. public class AdminAuthenticationProvider implements AuthenticationProvider {
  5. protected Logger logger = LoggerFactory.getLogger(this.getClass());
  6. private UserDetailsService userDetailsService = null;
  7. public AdminAuthenticationProvider() {
  8. super();
  9. }
  10. /**
  11. * @param userDetailsService
  12. */
  13. public AdminAuthenticationProvider(UserDetailsService userDetailsService) {
  14. super();
  15. this.userDetailsService = userDetailsService;
  16. }
  17. public UserDetailsService getUserDetailsService() {
  18. return userDetailsService;
  19. }
  20. public void setUserDetailsService(UserDetailsService userDetailsService) {
  21. this.userDetailsService = userDetailsService;
  22. }
  23. /**
  24. * provider的authenticate()方法,用于登录验证
  25. */
  26. @SuppressWarnings("unchecked")
  27. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  28. // 1. Check username and password
  29. try {
  30. doLogin(authentication);
  31. } catch (Exception e) {
  32. if (e instanceof AuthenticationException) {
  33. throw (AuthenticationException) e;
  34. }
  35. logger.error("failure to doLogin", e);
  36. }
  37. // 2. Get UserDetails
  38. UserDetails userDetails = null;
  39. try {
  40. userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
  41. } catch (Exception e) {
  42. if (e instanceof AuthenticationException) {
  43. throw (AuthenticationException) e;
  44. }
  45. logger.error("failure to get user detail", e);
  46. }
[java] view plaincopy
  1. // 3. Check and get all of admin roles and contexts.
  2. Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) userDetails.getAuthorities();
  3. if (authorities != null && !authorities.isEmpty()) {
  4. AdminAuthenticationToken token = new AdminAuthenticationToken(authentication.getName(),
  5. authentication.getCredentials(), authorities);
  6. token.setDetails(userDetails);
  7. return token;
  8. }
  9. throw new BadCredentialsException("没有分配权限");
  10. }
  11. protected void doLogin(Authentication authentication) throws AuthenticationException {
  12. }
  13. @Override
  14. public boolean supports(Class<?> authentication) {
  15. // TODO Auto-generated method stub
  16. return true;
  17. }
[java] view plaincopy
  1. /**用户详细信息获取
  2. */
  3. public class AdminUserDetailsService implements UserDetailsService {
  4. private Logger logger = LoggerFactory.getLogger(AdminUserDetailsService.class);
  5. private AdminService adminService;
  6. @Override
  7. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  8. AdminUserDetails userDetails = new AdminUserDetails();
  9. userDetails.setAdminId(username);
  10. ///加载用户基本信息
  11. AdminModel adminModel = adminService.getAdminByAdminId(username);
  12. try {
  13. PropertyUtils.copyProperties(userDetails, adminModel);
  14. } catch (IllegalAccessException e) {
  15. logger.error("用户信息复制到userDetails出错",e);
  16. } catch (InvocationTargetException e) {
  17. logger.error("用户信息复制到userDetails出错",e);
  18. } catch (NoSuchMethodException e) {
  19. logger.error("用户信息复制到userDetails出错",e);
  20. }
  21. //加载权限信息
  22. List<AdminRoleGrantedAuthority> authorities = this.adminService.getAuthorityByUserId(username);
  23. if (authorities == null || authorities.size() == 0) {如果为普通用户
  24. if (isCommonUserRequest()) {
  25. AdminRoleGrantedAuthority authority =
  26. new AdminRoleGrantedAuthority(AdminRoleGrantedAuthority.ADMIN_ROLE_TYPE_COMMON_USER);
  27. userDetails.getAuthorities().add(authority);
  28. } else {
  29. logger.warn("person authorities is empty, personId is [{}]", username);
  30. }
  31. }
  32. //加载用户权限
  33. userDetails.getAuthorities().addAll(authorities);
  34. ///这个就是权限系统最后的用户信息
  35. return userDetails;
  36. }
  37. private boolean isCommonUserRequest() {
  38. // TODO Auto-generated method stub
  39. return true;
  40. }
  41. public AdminService getAdminService() {
  42. return adminService;
  43. }
  44. public void setAdminService(AdminService adminService) {
  45. this.adminService = adminService;
  46. }
  47. }
[java] view plaincopy
  1. public class AdminAuthenticationToken extends AbstractAuthenticationToken {
  2. /**
  3. *
  4. */
  5. private static final long serialVersionUID = 5976309306377973996L;
  6. private final Object principal;
  7. private Object credentials;
  8. public AdminAuthenticationToken(Object principal, Object credentials) {
  9. super(null);
  10. this.principal = principal;
  11. this.credentials = credentials;
  12. setAuthenticated(false);
  13. }
  14. c AdminAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
  15. super(authorities);
  16. this.principal = principal;
  17. this.credentials = credentials;
  18. super.setAuthenticated(true); //注意,这里设置为true了! must use super, as we override
  19. }
  20. public Object getCredentials() {
  21. return this.credentials;
  22. }
  23. public Object getPrincipal() {
  24. return this.principal;
  25. }
  26. public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
  27. if (isAuthenticated) {
  28. throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
  29. }
  30. super.setAuthenticated(false);
  31. }
  32. @Override
  33. public void eraseCredentials() {
  34. super.eraseCredentials();
  35. credentials = null;
  36. }
  37. }

到这里基本就完成了spring security的设置,

4)最后就是jsp页面部分,页面主要是表单的action地址必须为:path+/j_spring_security_check,其中path是项目路径,然后登录的时候就可以使用security模块了!

至于文章中可能涉及到的一些bean或者service,这里就不贴代码了,毕竟项目较为完善,涉及东西太多,另外每个项目业务逻辑也不一样。

在整个框架整合过程中,遇到了很多奇怪的问题,很多是因为版本不一致引起的,建议用maven进行jar等依赖包的统一管理。

下面是spring security3.2的reference 手册:http://docs.spring.io/spring-security/site/docs/3.2.9.RELEASE/reference/htmlsingle/

SpringMVC + security模块 框架整合详解相关推荐

  1. Spring和Security整合详解

    Spring和Security整合详解 一.官方主页 Spring Security 二.概述 Spring 是一个非常流行和成功的 Java 应用开发框架.Spring Security 基于 Sp ...

  2. Spring和Ehcache整合详解

    Spring和Ehcache整合详解 一.官方主页 Spring Cache 二.概述 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点. Spring 提供了对缓存功能的抽象: ...

  3. java定时任务框架elasticjob详解

    这篇文章主要介绍了java定时任务框架elasticjob详解,Elastic-Job是ddframe中dd-job的作业模块中分离出来的分布式弹性作业框架.该项目基于成熟的开源产品Quartz和Zo ...

  4. springboot+jsp中文乱码_【spring 国际化】springMVC、springboot国际化处理详解

    在web开发中我们常常会遇到国际化语言处理问题,那么如何来做到国际化呢? 你能get的知识点? 使用springgmvc与thymeleaf进行国际化处理. 使用springgmvc与jsp进行国际化 ...

  5. Spring+SpringMVC+MyBatis+Maven框架整合

    本文记录了Spring+SpringMVC+MyBatis+Maven框架整合的记录,主要记录以下几点  一.Maven需要引入的jar包  二.Spring与SpringMVC的配置分离  三.Sp ...

  6. layUI前端框架使用详解_layUI前端框架视频教程

    百度云网盘下载 ayUI前端框架使用详解_layUI前端框架视频教程 课程目录: 1前言 2为什么要用layUI框架 3layer组件的引用方法 4layer组件的使用方法详解 5用layer组件快速 ...

  7. python中selenium模块驱动谷歌详解

    python中selenium模块驱动谷歌详解 Selenium的介绍.配置和调用 Selenium(浏览器自动化测试框架) 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中 ...

  8. php tp框架,浅谈PHP之ThinkPHP框架使用详解

    Thinkphp框架其精髓就在于实现了MVC思想,其中M为模板.V为视图.C为控制器,模板一般是公共使用类,在涉及数据库时,一般会跟数据表同名,视图会和控制器类里的方法进行名字的一一对应. 下载及配置 ...

  9. java框架魔乐_16 魔乐科技 SpringBoot框架开发详解

    资源内容: 16 魔乐科技 SpringBoot框架开发详解|____springboot开发代码.rar|____第一章:SpringBoot入门          |____2. SpringBo ...

  10. layUI前端框架使用详解_layUI前端框架视频教程完整版

    layUI前端框架使用详解_layUI前端框架视频教程 课程目录: 1前言 2为什么要用layUI框架 3layer组件的引用方法 4layer组件的使用方法详解 5用layer组件快速开发一个表单验 ...

最新文章

  1. 传感器的未来: 10年后我们将会生活在一个极端透明的世界
  2. 全国大学生智能车竞赛线上高校组合申请通知
  3. 坐标系转换(镜像与对换)
  4. [UE4]射击和直线追踪
  5. php 算年龄,PHP计算年龄、
  6. STL之Map和MFC之CMap比较学习
  7. 数据分析系统数据库选型
  8. Centos7换yum源
  9. Linux系统中Oracle数据库使用SELECT语句检索数据(1)实例应用
  10. 看DLI服务4核心如何提升云服务自动化运维
  11. 八年级信息技术认识计算机网络,初二信息技术课名称:认识计算机网络.doc
  12. c#如何根据字符串长度获得宽度
  13. #PYTHON#数据模型
  14. Could not find method jackOptions() for arguments
  15. 三年经验前端开发面试总结
  16. 卷积神经网络(CNN)卷积核与滤波器理解
  17. php解析今日头条视频下载,今日头条视频的地址解析下载
  18. Electron加密打包文件
  19. STM32F103C8T6基础开发教程(HAL库)—点亮第一颗LED灯
  20. C语言函数: 字符串函数及模拟实现strtok()、strstr()、strerror()

热门文章

  1. 阶段3 2.Spring_01.Spring框架简介_03.spring概述
  2. 阶段3 1.Mybatis_06.使用Mybatis完成DAO层的开发_9 typeAliases标签和package标签
  3. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_09 序列化流_2_对象的序列化流_ObjectOutputStream...
  4. 源码:Java集合源码之:哈希表(二)
  5. 异序二分查找 二分查找方程根 二分查找重复元素最后一个
  6. C#并发编程实例讲解-概述(01)
  7. 错题分析--ASP.NET
  8. java日期互转:LocalDateTime、String、Instant、Date
  9. -ia utopia 里的乌托邦
  10. leetcode笔记--7 Find the Difference