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字段作為主鍵.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM