Spring Security框架進階、自定義登陸

 

1.Spring Security框架進階

1.1 Spring Security簡介

Spring Security是一個可以爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組能夠在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減小了爲企業系統安全控制編寫大量重複代碼的工做。css

1.2 Spring Security入門小Demo

1.2.1最簡單Demo

(1)建立工程spring-security-demo ,pom.xml內容html

<properties>java

<spring.version>4.2.4.RELEASE</spring.version>web

</properties>spring

<dependencies>數據庫

<dependency>express

<groupId>org.springframework</groupId>apache

<artifactId>spring-core</artifactId>編程

<version>${spring.version}</version>api

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-test</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-web</artifactId>

<version>4.1.0.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-config</artifactId>

<version>4.1.0.RELEASE</version>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.5</version>

<scope>provided</scope>

</dependency>

</dependencies>

<build>

  <plugins>

      <!-- java編譯插件 -->

  <plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.2</version>

<configuration>

<source>1.7</source>

<target>1.7</target>

<encoding>UTF-8</encoding>

</configuration>

  </plugin>      

      <plugin>

<groupId>org.apache.tomcat.maven</groupId>

<artifactId>tomcat7-maven-plugin</artifactId>

<configuration>

<!-- 指定端口 -->

<port>9090</port>

<!-- 請求路徑 -->

<path>/</path>

</configuration>

    </plugin>

   </plugins>  

    </build>

 

(2)建立web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

version="2.5">

    <context-param>

<param-name>contextConfigLocation</param-name>

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

 </context-param>

 <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>

</web-app>

 

(3)建立index.html  

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>首頁</title>

</head>

<body>

歡迎進入神奇的spring security世界~~~

</body>

</html>

 

(4)建立spring 配置文件spring-security.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans 
    xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
    
    <http pattern="/*.html" security="none"/>
    <http pattern="/css/**" security="none"/>
    <http pattern="/img/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/plugins/**" security="none"/>
    <http pattern="/seller/add.do" security="none"/>
    
    <!-- use-expressions:設置是否啓動SpEL表達式,默認值是true。 -->
    <http use-expressions="false">
        <!-- 
            配置SpringSecurity的攔截路徑(攔截規則) 
            * pattern:配置攔截規則。   /* 表明的是根路徑下的全部資源(不包含子路徑) /**表明的是根路徑下全部的資源(包含子路徑)
            * access:設置角色  角色命名 ROLE_角色名稱  如:  ROLE_USER  
        -->
        <intercept-url pattern="/**" access="ROLE_SELLER"/>
        
        <!-- 
        開啓表單驗證 
            username-parameter="username" 
            password-parameter="password" 
            login-page            :登陸頁面名稱  以  / 開始
            default-target-url    :登陸成功後跳轉的頁面
            login-processing-url:提交的路徑的設置 默認值"/login" 能夠修改
        -->
        <form-login login-page="/login.html" default-target-url="/admin/index.html" always-use-default-target="true" authentication-failure-url="/login.html"/>
        
        <!-- 不使用csrf的校驗 -->
        <csrf disabled="true"/>
        
        <!-- 配置框架頁面不攔截 -->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
        
        <!-- 註銷的配置 -->
        <logout logout-url="/logout" logout-success-url="/shoplogin.html" />
    </http>
    
    <!-- 配置認證管理器 -->
    <authentication-manager>
        <!-- 認證的提供者 -->
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>
        

    <!-- 配置自定義的認證類 -->
    <beans:bean id="userDetailsService" class="com.luli.code.service.UserDetailsServiceImpl">
        <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>


</beans:beans>

 

由於登陸頁會被反覆重定向。

login-page:指定登陸頁面。
authentication-failure-url:指定了身份驗證失敗時跳轉到的頁面。
default-target-url:指定了成功進行身份驗證和受權後默認呈現給用戶的頁面。

csrf disabled="true"  關閉csrf ,若是不加會出現錯誤

 

CSRF(Cross-site request forgery)跨站請求僞造,也被稱爲「One Click Attack」或者Session Riding,一般縮寫爲CSRF或者XSRF,是一種對網站的惡意利用。

 

IDEA啓動tomcat顯示build success但沒法繼續啓動的解決方法

 

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <configuration>
        <ignorePackaging>true</ignorePackaging>
        <!-- 指定端口 -->
        <port>9090</port>
        <!-- 請求路徑 -->
        <path>/</path>
    </configuration>
</plugin>

 

告訴Tomcat插件,當前不是使用war包裝。在pom.xml的tomcat plugin的configuration中加入<ignorePackaging>true</ignorePackaging>,即告訴tomcat啓動時忽略當前是否有war包,再次運行tomcat7:run命令,tomcat便可正常啓動。

 

 

access="ROLE_USER" access 必須是ROLE_開頭

此案例咱們沒有登陸頁,而是使用了系統自動生成的登錄頁,效果以下:

 

 

配置說明:

intercept-url 表示攔截頁面   

/*  表示的是該目錄下的資源,只包括本級目錄不包括下級目錄

/** 表示的是該目錄以及該目錄下全部級別子目錄的資源

form-login  爲開啓表單登錄

use-expressions 爲是否使用使用 Spring 表達式語言( SpEL ),默認爲true ,若是開啓,則攔截的配置應該寫成如下形式

login-processing-url=」/login2」 指定其餘登陸頁

username-parameter="" password-parameter="" 來改寫login的 用戶名和屬性名

<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

 

(5)構建登錄頁login.html:

 <!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>登錄</title>

</head>

<body>

 

--歡迎的登錄個人系統--

<form action="/login" method="post">

用戶名:<input name="username"><br>

密碼:<input name="password"><br>

<button>登錄</button>

</form>

</body>

</html>

 

(6)構建登錄失敗頁  login_error.html

 <!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>首頁</title>

</head>

<body>

用戶名或密碼錯誤~~~

</body>

</html>

(7)  UserDetailsServiceImpl.java文件

package com.luli.code.service;

import com.luli.code.pojo.Seller;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {

    private SellerService sellerService;

    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }
    /*自定義登陸驗證*/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        //查找數據庫
        Seller seller = sellerService.findOne(username);
        if(seller != null && ("1").equals(seller.getStatus())) {    
            return new User(username, seller.getPassword(), grantedAuthorities);    //判斷帳戶密碼
}else{ return null; } } }
相關文章
相關標籤/搜索