zoukankan      html  css  js  c++  java
  • spring security4.1.3配置以及踩过的坑

    https://blog.csdn.net/honghailiang888/article/details/53520557

    spring security完全可以作为一个专门的专题来说,有一个专题写的不错http://www.iteye.com/blogs/subjects/spring_security,我这里主要是针对4.1.3进行配置说明

    一、所需的库文件

    1.  
      //spring-security
    2.  
      compile 'org.springframework.security:spring-security-web:4.1.3.RELEASE'
    3.  
      compile 'org.springframework.security:spring-security-config:4.1.3.RELEASE'
    4.  
      compile 'org.springframework.security:spring-security-taglibs:4.1.3.RELEASE'

    二、web配置

    从4以后security就只吃java配置了,具体可以看下《spring in action第四版》,我这里还是使用xml配置

    过滤器配置,security是基于过滤器的,web.xml

    1.  
      <!-- Spring-security -->
    2.  
      <filter>
    3.  
      <filter-name>springSecurityFilterChain</filter-name>
    4.  
      <filter-class>
    5.  
      org.springframework.web.filter.DelegatingFilterProxy
    6.  
      </filter-class>
    7.  
      </filter>
    8.  
      <filter-mapping>
    9.  
      <filter-name>springSecurityFilterChain</filter-name>
    10.  
      <url-pattern>/*</url-pattern>
    11.  
      </filter-mapping>

    需要注意的是,如果配置了sitemesh装饰器,如果在装饰器页面中用到了security,比如标签,那么security过滤器需要配置在sitemesh之前,否则装饰器页中的<sec:authorize>标签可能不起作用

    1.  
      <!-- Spring-security -->
    2.  
      <filter>
    3.  
      <filter-name>springSecurityFilterChain</filter-name>
    4.  
      <filter-class>
    5.  
      org.springframework.web.filter.DelegatingFilterProxy
    6.  
      </filter-class>
    7.  
      </filter>
    8.  
      <filter-mapping>
    9.  
      <filter-name>springSecurityFilterChain</filter-name>
    10.  
      <url-pattern>/*</url-pattern>
    11.  
      </filter-mapping>
    12.  
       
    13.  
      <!--sitemesh装饰器放在spring security过来器的后面,以免装饰器页中的security不起作用-->
    14.  
      <filter>
    15.  
      <filter-name>sitemesh</filter-name>
    16.  
      <filter-class>
    17.  
      org.sitemesh.config.ConfigurableSiteMeshFilter
    18.  
      </filter-class>
    19.  
      <init-param>
    20.  
      <param-name>ignore</param-name>
    21.  
      <param-value>true</param-value>
    22.  
      </init-param>
    23.  
      <init-param>
    24.  
      <param-name>encoding</param-name>
    25.  
      <param-value>UTF-8</param-value>
    26.  
      </init-param>
    27.  
      </filter>
    28.  
      <filter-mapping>
    29.  
      <filter-name>sitemesh</filter-name>
    30.  
      <url-pattern>/*</url-pattern>
    31.  
      </filter-mapping>

    装饰器页面中的使用

    1.  
      <sec:authorize access="!hasRole('ROLE_USER')">
    2.  
      <li>你好,欢迎来到Mango!<a href="<c:url value='/login'/>" class="current">登录</a></li>
    3.  
      </sec:authorize>
    4.  
      <sec:authorize access="hasRole('ROLE_USER')">
    5.  
      <li><sec:authentication property="principal.username"/>欢迎光临Mango!<a href="<c:url value='/logout'/>" class="current">退出</a></li>
    6.  
      </sec:authorize>

    三、security配置文件配置

    applicationContext-security.xml

    1.  
      <?xml version="1.0" encoding="UTF-8"?>
    2.  
       
    3.  
      <beans:beans xmlns="http://www.springframework.org/schema/security"
    4.  
      xmlns:beans="http://www.springframework.org/schema/beans"
    5.  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6.  
      xsi:schemaLocation="http://www.springframework.org/schema/beans
    7.  
      http://www.springframework.org/schema/beans/spring-beans.xsd
    8.  
      http://www.springframework.org/schema/security
    9.  
      http://www.springframework.org/schema/security/spring-security.xsd">
    10.  
       
    11.  
      <http auto-config="true" use-expressions="true" >
    12.  
      <form-login
    13.  
      login-page="/login"
    14.  
      authentication-failure-url="/login?error"
    15.  
      login-processing-url="/login"
    16.  
      always-use-default-target="false"
    17.  
      authentication-success-handler-ref="myAuthenticationSuccessHandler" />
    18.  
      <!-- 认证成功用自定义类myAuthenticationSuccessHandler处理 -->
    19.  
       
    20.  
      <logout logout-url="/logout"
    21.  
      logout-success-url="/"
    22.  
      invalidate-session="true"
    23.  
      delete-cookies="JSESSIONID"/>
    24.  
       
    25.  
      <csrf disabled="true" />
    26.  
      <intercept-url pattern="/order/*" access="hasRole('ROLE_USER')"/>
    27.  
      </http>
    28.  
       
    29.  
      <!-- 使用自定义类myUserDetailsService从数据库获取用户信息 -->
    30.  
      <authentication-manager>
    31.  
      <authentication-provider user-service-ref="myUserDetailsService">
    32.  
      <!-- 加密 -->
    33.  
      <password-encoder hash="md5">
    34.  
      </password-encoder>
    35.  
      </authentication-provider>
    36.  
      </authentication-manager>
    37.  
       
    38.  
      </beans:beans>

    这里配置了自定义登录界面/login,还需要配置控制器条撞到login.jsp页面,如果字段使用默认值为username和password,当然也可以用 form-login标签中的属性username-parameter="username"password-parameter="password"进行设置,这里的值要和登录页面中的字段一致。login.jsp

    1.  
      <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
    2.  
      <%@ include file="../includes/taglibs.jsp"%>
    3.  
      <!DOCTYPE html>
    4.  
      <html>
    5.  
      <head>
    6.  
      <title>Mango-Login</title>
    7.  
      <meta name="menu" content="home" />
    8.  
      </head>
    9.  
       
    10.  
      <body>
    11.  
       
    12.  
      <h1>请登录!</h1>
    13.  
       
    14.  
      <div style="text-align:center">
    15.  
      <form action="<c:url value='/login' />" method="post">
    16.  
      <c:if test="${not empty error}">
    17.  
      <p style="color:red">${error}</p>
    18.  
      </c:if>
    19.  
      <table>
    20.  
      <tr>
    21.  
      <td>用户名:</td>
    22.  
      <td><input type="text" name="username"/></td>
    23.  
      </tr>
    24.  
      <tr>
    25.  
      <td>密码:</td>
    26.  
      <td><input type="password" name="password"/></td>
    27.  
      </tr>
    28.  
      <tr>
    29.  
      <td colspan="2" align="center">
    30.  
      <input type="submit" value="登录"/>
    31.  
      <input type="reset" value="重置"/>
    32.  
      </td>
    33.  
      </tr>
    34.  
      </table>
    35.  
      </form>
    36.  
      </div>
    37.  
       
    38.  
      </body>
    39.  
      </html>

    其中,form action的值要和配置文件中login-process-url的值一致,提交后UsernamePasswordAuthenticationFilter才能对其进行授权认证。
    另外认证是采用的自定义myUserDetailsService获取用户信息方式,由于该项目中集成的是Hibernate,所以自己定义了,security系统中是支持jdbc进行获取的

    1.  
      package com.mango.jtt.springSecurity;
    2.  
       
    3.  
      import org.springframework.beans.factory.annotation.Autowired;
    4.  
      import org.springframework.security.core.authority.AuthorityUtils;
    5.  
      import org.springframework.security.core.userdetails.User;
    6.  
      import org.springframework.security.core.userdetails.UserDetails;
    7.  
      import org.springframework.security.core.userdetails.UserDetailsService;
    8.  
      import org.springframework.security.core.userdetails.UsernameNotFoundException;
    9.  
      import org.springframework.stereotype.Service;
    10.  
       
    11.  
      import com.mango.jtt.po.MangoUser;
    12.  
      import com.mango.jtt.service.IUserService;
    13.  
       
    14.  
      /**
    15.  
      * 从数据库中获取信息的自定义类
    16.  
      *
    17.  
      * @author HHL
    18.  
      *
    19.  
      */
    20.  
      @Service
    21.  
      public class MyUserDetailsService implements UserDetailsService {
    22.  
       
    23.  
      @Autowired
    24.  
      private IUserService userService;
    25.  
       
    26.  
      /**
    27.  
      * 获取用户信息,设置角色
    28.  
      */
    29.  
      @Override
    30.  
      public UserDetails loadUserByUsername(String username)
    31.  
      throws UsernameNotFoundException {
    32.  
      // 获取用户信息
    33.  
      MangoUser mangoUser = userService.getUserByName(username);
    34.  
      if (mangoUser != null) {
    35.  
      // 设置角色
    36.  
      return new User(mangoUser.getUserName(), mangoUser.getPassword(),
    37.  
      AuthorityUtils.createAuthorityList(mangoUser.getRole()));
    38.  
      }
    39.  
       
    40.  
      throw new UsernameNotFoundException("User '" + username
    41.  
      + "' not found.");
    42.  
      }
    43.  
       
    44.  
      }


    认证成功之后也是自定义了处理类myAuthenticationSuccessHandler,该处理类继承了SavedRequestAwareAuthenticationSuccessHandler,实现了保存请求信息的操作,如果不配置,默认的也是交给SavedRequestAwareAuthenticationSuccessHandler处理,因为在解析security配置文件时,如果没有配置会将此设置为默认值。

    1.  
      package com.mango.jtt.springSecurity;
    2.  
       
    3.  
      import java.io.IOException;
    4.  
       
    5.  
      import javax.servlet.ServletException;
    6.  
      import javax.servlet.http.HttpServletRequest;
    7.  
      import javax.servlet.http.HttpServletResponse;
    8.  
       
    9.  
      import org.springframework.beans.factory.annotation.Autowired;
    10.  
      import org.springframework.security.core.Authentication;
    11.  
      import org.springframework.security.core.userdetails.UserDetails;
    12.  
      import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
    13.  
      import org.springframework.stereotype.Component;
    14.  
       
    15.  
      import com.mango.jtt.po.MangoUser;
    16.  
      import com.mango.jtt.service.IUserService;
    17.  
       
    18.  
      /**
    19.  
      * 登录后操作
    20.  
      *
    21.  
      * @author HHL
    22.  
      * @date
    23.  
      *
    24.  
      */
    25.  
      @Component
    26.  
      public class MyAuthenticationSuccessHandler extends
    27.  
      SavedRequestAwareAuthenticationSuccessHandler {
    28.  
       
    29.  
      @Autowired
    30.  
      private IUserService userService;
    31.  
       
    32.  
      @Override
    33.  
      public void onAuthenticationSuccess(HttpServletRequest request,
    34.  
      HttpServletResponse response, Authentication authentication)
    35.  
      throws IOException, ServletException {
    36.  
       
    37.  
      // 认证成功后,获取用户信息并添加到session中
    38.  
      UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    39.  
      MangoUser user = userService.getUserByName(userDetails.getUsername());
    40.  
      request.getSession().setAttribute("user", user);
    41.  
       
    42.  
      super.onAuthenticationSuccess(request, response, authentication);
    43.  
       
    44.  
      }
    45.  
       
    46.  
       
    47.  
      }


    认证失败则回到登录页,只不过多了error,配置为authentication-failure-url="/login?error" 控制类会对其进行处理

    1.  
      /**
    2.  
      *
    3.  
      */
    4.  
      package com.mango.jtt.controller;
    5.  
       
    6.  
      import org.springframework.stereotype.Controller;
    7.  
      import org.springframework.ui.Model;
    8.  
      import org.springframework.web.bind.annotation.RequestMapping;
    9.  
      import org.springframework.web.bind.annotation.RequestParam;
    10.  
       
    11.  
      /**
    12.  
      * @author HHL
    13.  
      *
    14.  
      * @date 2016年12月8日
    15.  
      *
    16.  
      * 用户控制类
    17.  
      */
    18.  
      @Controller
    19.  
      public class UserController {
    20.  
       
    21.  
      /**
    22.  
      * 显示登录页面用,主要是显示错误信息
    23.  
      *
    24.  
      * @param model
    25.  
      * @param error
    26.  
      * @return
    27.  
      */
    28.  
      @RequestMapping("/login")
    29.  
      public String login(Model model,
    30.  
      @RequestParam(value = "error", required = false) String error) {
    31.  
      if (error != null) {
    32.  
      model.addAttribute("error", "用户名或密码错误");
    33.  
      }
    34.  
      return "login";
    35.  
      }
    36.  
      }

    另外,从spring security3.2开始,默认就会启用csrf保护,本次将csrf保护功能禁用<csrf disabled="true" />,防止页面中没有配置crsf而报错“Could not verify the provided CSRF token because your session was not found.”,如果启用csrf功能的话需要将login和logout以及上传功能等都需要进行相应的设置,因此这里先禁用csrf保护功能具体可参考spring-security4.1.3官方文档

    四,后面会对认证过程,以及如何认证的进行详细说明。

    完整代码:http://download.csdn.net/detail/honghailiang888/9705858

    或 https://github.com/honghailiang/SpringMango

    Spring安全权限管理(Spring Security)

     

    1.spring Security简要介绍

    Spring Security以前叫做acegi,是后来才成为Spring的一个子项目,也是目前最为流行的一个安全权限管理框架,它与Spring紧密结合在一起。

    Spring Security关注的重点是在企业应用安全层为您提供服务,你将发现业务问题领域存在着各式各样的需求。银行系统跟电子商务应用就有很大的不同。电子商务系统与企业销售自动化工具又有很大不同。这些客户化需求让应用安全显得有趣,富有挑战性而且物有所值。Spring Security为基于J2EE的企业应用软件提供了一套全面的安全解决方案。

    2.为Spring Security配置过滤器和其他参数

    要使用Spring Security,首先就是在web.xml中为它配置过滤器, 其次因为我的spring配置文件是放在WEB-INF下的,因此还要配置上下文的参数,最后添加spring的监听器:

    [xhtml] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app version="2.5" xmlns="http://<a href="http://lib.csdn.net/base/17" class='replace_word' title="Java EE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.sun.com/xml/ns/javaee"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
    5.     <!-- 配置上下文参数,指定spring配置文件的位置 -->  
    6.     <context-param>  
    7.         <param-name>contextConfigLocation</param-name>  
    8.         <param-value>/WEB-INF/spring-*.xml</param-value>  
    9.     </context-param>  
    10.     <!-- spring security必须的过滤器,保证在访问所有的页面时都必须通过认证 -->  
    11.     <filter>  
    12.         <filter-name>springSecurityFilterChain</filter-name>  
    13.         <filter-class>  
    14.             org.springframework.web.filter.DelegatingFilterProxy  
    15.         </filter-class>  
    16.     </filter>  
    17.     <filter-mapping>  
    18.         <filter-name>springSecurityFilterChain</filter-name>  
    19.         <url-pattern>/*</url-pattern>  
    20.     </filter-mapping>  
    21.     <listener>  
    22.         <listener-class>  
    23.             org.springframework.web.context.ContextLoaderListener  
    24.         </listener-class>  
    25.     </listener>  
    26.     <welcome-file-list>  
    27.         <welcome-file>index.jsp</welcome-file>  
    28.     </welcome-file-list>  
    29.     <login-config>  
    30.         <auth-method>BASIC</auth-method>  
    31.     </login-config>  
    32. </web-app>  

    3.配置security(spring-security.xml)

    [xhtml] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <!-- 这里必须使用security的命名空间,提供了beans这个假名 -->  
    3. <beans:beans xmlns="http://www.springframework.org/schema/security"  
    4.     xmlns:beans="http://www.springframework.org/schema/beans"  
    5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
    7.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">  
    8.   
    9.     <!-- Spring Security采用就近原则,有多个约束时,从上至下只要找到第一条满足就返回,因此因该将最严格的约束放在最前面,而将最宽松的约束放在最后面.auto-config属性可以让spring security为我们自动配置几种常用的权限控制机制,包括form,anonymous, rememberMe等。当然你也可以手工配置。-->  
    10.     <http auto-config="true">  
    11.         <!-- 我们利用intercept-url来判断用户需要具有何种权限才能访问对应的url资源,可以在pattern中指定一个特定的url资源,也可以使用通配符指定一组类似的url资源。例子中定义的两个intercepter-url,第一个用来控制对/security/**的访问,第二个使用了通配符/**,说明它将控制对系统中所有url资源的访问。 -->  
    12.         <intercept-url pattern="/security/**" access="ROLE_ADMIN" />  
    13.         <intercept-url pattern="/**" access="ROLE_ADMIN,ROLE_USER" />  
    14.         <intercept-url pattern="/login.jsp*" filters="none" />  
    15.         <logout logout-url="/logout.jsp"  
    16.             logout-success-url="/j_spring_security_check" />  
    17.     </http>  
    18.   
    19.     <!-- 使用内存权限管理的配置信息, 在tomcat启动时,会加载这个文件并一直保存在内存中,知道应用程序重启,所以也叫内存权限管理  
    20.         <authentication-provider>  
    21.         <user-service>  
    22.         <user name="admin" password="tomcat" authorities="ROLE_ADMIN"/>  
    23.         <user name="liky" password="redhat" authorities="ROLE_USER"/>       
    24.         </user-service>  
    25.         </authentication-provider>  
    26.     -->  
    27.     <!-- 使用<a href="http://lib.csdn.net/base/14" class='replace_word' title="MySQL知识库" target='_blank' style='color:#df3434; font-weight:bold;'>数据库</a>作为权限管理的来源,data-source-ref指定了数据源,所指定的数据源必须包含users, authorities表,并符合security的定义规范 -->  
    28.     <authentication-provider>  
    29.         <jdbc-user-service data-source-ref="dataSource" />  
    30.     </authentication-provider>  
    31.   
    32. </beans:beans>  

    4.数据源的配置(spring-common.xml)

    [c-sharp] view plain copy
     
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
    5.   
    6.     <!-- 定义数据源 -->  
    7.     <bean id="dataSource"  
    8.         class="org.apache.commons.dbcp.BasicDataSource">  
    9.         <property name="driverClassName"  
    10.             value="com.<a href="http://lib.csdn.net/base/14" class='replace_word' title="MySQL知识库" target='_blank' style='color:#df3434; font-weight:bold;'>MySQL</a>.jdbc.Driver">  
    11.         </property>  
    12.         <property name="url" value="jdbc:mysql://localhost:3306/csu"></property>  
    13.         <property name="username" value="root"></property>  
    14.         <property name="password" value="redhat"></property>  
    15.         <property name="maxActive" value="100"></property>  
    16.         <property name="maxIdle" value="30"></property>  
    17.         <property name="maxWait" value="300"></property>  
    18.         <property name="defaultAutoCommit" value="true"></property>  
    19.     </bean>     
    20. </beans>  

    5.项目的目录结构

    6. 数据库脚本

    [xhtml] view plain copy
     
    1. /-- 注意这里的脚本是MYSQL的,因此在你演示这个实例的时候,要加入MySQL的驱动包 --/  
    2.    
    3. create table users  
    4. (  
    5. username varchar(50) primary key,  
    6. password varchar(50),  
    7. enabled tinyint(1)  
    8. );  
    9.   
    10. create table authorities  
    11. (  
    12. id int auto_increment primary key,  
    13. username varchar(50),  
    14. authority varchar(50),  
    15. constraint fk_authorities_users foreign key(username) references users(username)  
    16. );  
    17.   
    18. create unique index ix_auth_username on authorities (username,authority);  

    7.部署和配置的要点说明

    这是一个Spring Security的数据库认证实例,要注意以下几点:
    (1)请自行加入Spring必须的包,Spring security的包和MySQL的驱动包,当然你也可以换成其他的数据库,但是你要相应的修改spring-common.xml中的dataSource部分
    (2)数据库中的两个表users,authorites必须完全按照脚本所示来定义,也就是说表的名字不能修改.
    (3)users表必须包含username,password,enabled字段,这三个字段是绝对不能少的,也不能修改类型.另外enabled一定要为1才能登录
    (4)authorities表必须包含username字段,这个字段引用users的username作为外键,authority字段就是角色的名字,角色名字必须满足ROLE_XXX的格式(例如:ROLE_ADMIN,ROLE_USER,ROLE_MAMAGER)
    (5)如果一个用户有多个角色,不要将多个角色放在一起用逗号隔开.而是每个角色定义一条记录(例如:abu有ROLE_ADMIN,ROLE_USER两个角色,那么应该定义两条记录: 一条为abu, ROLE_USER,另一条为abu, ROLE_ADMIN.而不是只有一条:abu, ROLE_ADMIN,ROLE_USER)
    (6)你可以给authorities表添加一个id字段作为主键.

  • 相关阅读:
    hdwiki 学习笔记 01
    hdwiki model目录下的函数类
    hdwiki 的模板和标签
    Linux下CPU内存占用过高思路分析
    Linux下后台运行jar包
    Arrays.asList集合类的集合转换方法的坑!!!(不支持的操作异常:UnsupportedOperationException)
    Linux下定时备份mysql数据库
    解决Navicat远程连接数据库出现错误:1130-host ... is not allowed to connect to this MySql server
    深入JVM学习
    JUC的等待唤醒机制(wait/notify await/singal)之生产者和消费者问题
  • 原文地址:https://www.cnblogs.com/cfas/p/9395918.html
Copyright © 2011-2022 走看看