基於Spring的安全管理框架Spring Security


一、什么是Spring Security?

   Spring Security是基於Spring的安全框架.它提供全面的安全性解決方案,同時在Web請求級別和調用級別確認和授權.在Spring Framework基礎上,Spring Security充分利用了依賴注入(DI)和面向切面編程(AOP)功能,為應用系統提供聲明式的安全訪問控制功能,建曬了為企業安全控制編寫大量重復代碼的工作,是一個輕量級的安全框架,並且很好集成Spring MVC

二、Spring Security的核心功能有哪些?

  1、認證(Authentication):指的是驗證某個用戶是否為系統中的合法主體,也就是說用戶能否訪問該系統。

  2、授權(Authorization):指的是驗證某個用戶是否有權限執行某個操作

三、Spring Security基於哪些技術實現?

    Filter,Servlet,AOP實現

眾所周知想要對Web資源進行保護,最好的辦法莫過於Filter,要想對方法調用進行保護,最好的辦法莫過於AOP。所以SpringSecurity在我們進行用戶認證以及授予權限的時候,通過各種各樣的攔截器來控制權限的訪問,從而實現安全。

Spring Security功能的實現主要是由一系列過濾器鏈相互配合完成

 

   1springSecurityFilterChain中各個過濾器怎么創建的只需了解即可。不要太過關注。

   2重點記憶UsernamePasswordAuthenticationFilter,ExceptionTranslationFilter, FilterSecurityInterceptor這三個過濾器的作用及源碼分析。

   3重點記憶認證中Authentication,AuthenticationManager,ProviderManager, AuthenticationProvider,UserDetailsService,UserDetails這些類的作用及源碼分析。

  4重點記憶授權中FilterInvoction,SecurityMetadataSource,AccessDecisionManager的作用。

四、框架的核心組件

      SecurityContextHolder提供對SecurityContext的訪問

      SecurityContext持有Authentication對象和其他可能需要的信息

      AuthenticationManager其中可以包含多個AuthenticationProvider

      ProviderManager對象AuthenticationManager接口的實現類

      AuthenticationProvider主要用來進行認證操作的類 調用其中的authenticate()方法去進行認證操作

      Authentication:Spring Security方式的認證主體

      GrantedAuthority:對認證主題的應用層面的授權,含當前用戶的權限信息,通常使用角色表示

      UserDetails構建Authentication對象必須的信息,可以自定義,可能需要訪問DB得到

     UserDetailsService通過username構建UserDetails對象,通過loadUserByUsername根據userName獲取UserDetail對象

五、SpringSecurity的工作流程

     

六、認證流程

 

七、授權流程

 

八、springsecurity入門示例

     1、構建maven項目,引入springsecurity相關依賴。   

pom.xml配置文件主要部分:

<properties>
  <spring.version>4.2.0.RELEASE</spring.version>
</properties>
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
</dependencies>

2、配置web.xml。

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring-security.xml</param-value>
</context-param>

<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

3、書寫AdminController.java類。

@Controller
public class AdminController {
    @RequestMapping(value = {"/","/welcome**"},method = RequestMethod.GET)
    public ModelAndView welcome(){
        ModelAndView welcome = new ModelAndView();
        welcome.addObject("title","Welcome");
        welcome.addObject("message","This is a Security Page");
        welcome.setViewName("hello");
        return welcome;
    }
    @RequestMapping(value = {"/","/admin**"},method = RequestMethod.GET)
    public ModelAndView admin(){
        ModelAndView welcome = new ModelAndView();
        welcome.addObject("title","admin");
        welcome.addObject("message","This is Admin page");
        welcome.setViewName("admin");
        return welcome;
    }

4、配置spring-mvc.xml

<context:component-scan base-package="web.*"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

5、配置spring-security.xml

<security:http auto-config="true">
   <security:intercept-url pattern="/admin**" access="hasAnyRole('ROLE_USER')"/>
</security:http>
<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="admin" authorities="ROLE_USER" password="123456"/>
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>

注意:<intercept-url pattern="/admin**" access="hasRole('ROLE_USER')"/>這句配置中,4.0以后版本都使用hasRole('ROLE_USER')取代原來的ROLE_USER。

6、准備頁面。

admin.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@page session="true" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   <h2>title:${title}</h2>
   <h2>message:${message}</h2>
   <c:if test="${pageContext.request.userPrincipal.name != null }">
       <h2>welcome you ,${pageContext.request.userPrincipal.name}</h2>
       <a href="<c:url value='/j_spring_security_logout'/>">Logout</a>
   </c:if>
</body>
</html>

hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
     <h2>title:${title }</h2>
     <h2>message:${message }</h2>
</body>
</html>

7、啟動tomcat,訪問項目http://localhost:8080/springsecurity/admin

初次訪問http://localhost:8080/springsecurity/admin提示登錄,這是springsecurity為我們提供的默認的登錄頁面

 

用戶名或者密碼錯誤,登錄失敗

 

 

 

 

登錄成功,跳轉歡迎頁面

   

 

 

 

 


免責聲明!

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



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