1. 程式人生 > >[Spring Security] 表單登入通過配置自定義登入頁面,以及自定義認證成功/失敗處理機制

[Spring Security] 表單登入通過配置自定義登入頁面,以及自定義認證成功/失敗處理機制

1.目錄結構

2.配置自定義登入頁

通過配置SecurityProperties,MyProperties,SecurityCoreConfig來讀取resources資料夾下application.properties中相關配置項。

SecurityProperties:

package com.security.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author ShotMoon
 */
@Data
@ConfigurationProperties(prefix = "shotmoon.security")//讀取application.properties中以"shotmoon.security"開頭的配置項,並寫入myProperties物件中
public class SecurityProperties {
    
    //注意,物件名myProperties要跟application.properties中shotmoon.security(即prefix)後面相同
    private MyProperties myProperties = new MyProperties();

}

MyProperties:

package com.security.properties;

import lombok.Data;

/**
 * @author ShotMoon
 */
@Data
public class MyProperties {
    //注意,屬性名loginPage跟application.properties相應配置名務必保持一致
    private String loginPage = "/default-login.html";
}

SecurityCoreConfig:

package com.security;

import com.security.properties.SecurityProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author ShotMoon
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityCoreConfig {

}

application.properties:

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/security?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=qwe123

security.basic.enabled=false

spring.session.store-type=none

//對應MyProperties中相關同名屬性
shotmoon.security.myProperties.loginPage = /myLoginPage.html

配置後,初次訪問服務會自動跳轉到我們配置的自定義登入頁(隨便寫的,略醜)


3.自定義認證成功/失敗處理

Spring Security預設的認證處理方式有時候並不能滿足我們的需求,尤其當下前後端分離開發已成趨勢的情況下,認證完成後返回html的形式並不利於我們分離開發,下面我們研究下如何用Spring Security自帶的AuthenticationSuccessHandler,AuthenticationFailureHandler來解決這個問題。

MyAuthenticationSuccessHandler:

package com.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ShotMoon
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        logger.info("登入成功");

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(authentication));//將java物件轉成json字串寫入response,Authtication引數中包含我們的認證資訊  
    }
}

AuthenticationFailureHandler:

package com.security.authentication;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        logger.info("登陸失敗");

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(exception));//將異常寫入response中,顯示在頁面上
    }
}

然後在SecurityConfig中進行配置使其生效:

SecurityConfig:

package com.security.config;

import com.security.authentication.MyAuthenticationFailureHandler;
import com.security.authentication.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ShotMoon
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    /**
     * @description :
     * @param : [http]
     * @return : void
     * @date : 2018/5/13 13:41
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form")
                .successHandler(myAuthenticationSuccessHandler)//配置successHandler
                .failureHandler(myAuthenticationFailureHandler)//配置failureHandler
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/loginPage.html",
                        "/myLoginPage.html",
                        "/authentication/require"

                ).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
    }
}

完成,看下效果:

登陸成功,顯示認證資訊:


登陸失敗,顯示異常資訊:


這樣我們就可以自定義認證完成處理機制了,快試試吧。

相關推薦

[Spring Security] 登入通過配置定義登入頁面以及定義認證成功/失敗處理機制

1.目錄結構2.配置自定義登入頁通過配置SecurityProperties,MyProperties,SecurityCoreConfig來讀取resources資料夾下application.properties中相關配置項。SecurityProperties:pack

Spring Security登入認證

Spring Security是一個強有力並且高度定製化的認證和訪問控制框架,致力於為Java應用程式提供認證和授權。 特性: 1、為認證和授權提供綜合性和擴充套件性支援。 2、免受session定位、點選劫持、跨站點請求偽裝等攻擊。 3、Servelt API整合。 4、與Spring MV

Spring Security 登入

1. 簡介 本文將重點介紹使用Spring Security登入。 本文將構建在之前簡單的Spring MVC示例之上,因為這是設定Web應用程式和登入機制的必不可少的。 2. Maven 依賴 要將Maven依賴項新增到專案中,請參閱Spring Security with Maven一文。 標準

js實現提交後不重新重新整理當前頁面並停留在當前頁面

參考文章:http://www.cnblogs.com/limeiky/p/5599705.html 在填寫表單的時候,如果有某項為空或者不合法,在使用者點選提交後,頁面應當無法跳轉並且頁面內容不會重新整理;只有當用戶填寫內容滿足要求後,點選提交按鈕頁面才會跳轉到指定連結處

spring mvc:練習:驗證(javaConfig配置和註解)

libs pri tor sch pre ted 我們 binding sun 使用Spring表單標簽, 表單驗證使用 JSR303 的驗證註解,hibernate-validators,提供了使用MessageSource和訪問靜態資源(如CSS,JavaScript,

Spring Security Oauth2 登入案例實現和執行流程剖析

線上演示 演示地址:http://139.196.87.48:9002/kitty 使用者名稱:admin 密碼:admin Spring Security Oauth2 OAuth是一個關於授權的開放網路標準,在全世界得到的廣泛的應用,目前是2.0的版本。OAuth2在“客戶端”與“服務提供商”之間

spring boot中spring security實現登入傳統模式(一)

單點登入是什麼? 一個系統中可能會引用別的很多系統。單點登入就是解決,一次登入,就可以訪問所有的系統。 每次瀏覽器向一個域名傳送http請求,會去查詢域名的cookie資訊拼接到http的header中傳送到伺服器。 cookie不能跨域。這個域是瀏覽器請求的域名,哪怕他們都是訪問一

Spring MVC 控制器實現驗證使用者登入驗證

轉自:http://blog.csdn.net/happyunbound/article/details/8236106 web.xml: <?xmlversion="1.0"encoding="UTF-8"?> <

Spring MVC-(Form)標簽-選按鈕(RadioButton)示例(轉載實踐)

springmvc tro void cnblogs subscribe bin 應用 mat efi 以下內容翻譯自:https://www.tutorialspoint.com/springmvc/springmvc_radiobutton.htm 說明:示例基於Sp

Spring MVC-(Form)標簽-下拉框(Dropdown)示例(轉載實踐)

getcount pap number ima mvc框架 ati 讓我 lec 第一個 以下內容翻譯自:https://www.tutorialspoint.com/springmvc/springmvc_dropdown.htm 說明:示例基於Spring MVC 4

Spring MVC筆記(三) Spring MVC處理

名稱 command -i mat ppi post doctype form hello 創建動態WEB工程 FormHandling,並添加SpringMVC相關jar包(同Hello world示例一致),添加DispatcherServlet配置,如下: web.

spring boot 驗證

1.2 取值 not p s 技術分享 tro otn alt 技術   1 設置某個字段的取值範圍   1.1 取值範圍驗證:@Min,@Max   ① 實例類的屬性添加註解@Min         ② Controller中傳入參數使用@Valid註解

Confluence 6 管理員聯系的後臺配置界面

enc TP tps -i jpg 分享圖片 fig ont ima 管理員聯系表單的後臺配置界面截圖和配置。 對輸入的數據進行編輯和選擇是否啟用發送電子郵件給管理員 https://www.cwiki.us/display/CONFLUENCEWI

Spring Security】七、RememberMe配置

rop 基於 fig mep alias tom 保存 統一 source 一、概述 RememberMe 是指用戶在網站上能夠在 Session 之間記住登錄用戶的身份的憑證,通俗的來說就是用戶登陸成功認證一次之後在制定的一定時間內可以不用再輸入用戶名和密碼進行自動登錄

[Spring MVC] 提交日期轉換問題,比如可能導致封裝實體類時400錯誤

new tac med tab mat -m bin Edito ack   三種格式的InitBinder @InitBinder//https://stackoverflow.com/questions/20616319/the-request-sent-by-the

Spring Boot 驗證篇

Spring Boot 表單驗證篇 摘要: 原創出處:www.bysocket.com 泥瓦匠BYSocket 希望轉載,保留摘要,謝謝! “初學者的心充滿各種可能性,老手的卻不多” 本文提綱 1 spring-boot-starter-validation 依賴概述 1.1 spr

Android WebView載入HTML通過javascript提交

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Spring Mvc上傳404錯誤

404錯誤是找不到檔案 500是邏輯錯誤 以下是我的表單提交 <form action="${pageContext.request.contextPath }/FirstController.6b" method="post" enctype="multipart/for

bootstrapValidator驗證 驗證通過但無法提交form的原因

bootstrapValidator驗證時,使用submit提交表單,驗證通過,頁面沒有錯誤資訊。但submit按鈕未沒有提交。原因 : submit標籤的name或id屬性值為submit。$('#common-form').bootstrapValidator({    

Confluence 6 管理員聯絡的後臺配置介面

管理員聯絡表單的後臺配置介面截圖和配置。 對輸入的資料進行編輯和選擇是否啟用傳送電子郵件給管理員 https://www.cwiki.us/display/CONFLUENCEWIKI/Configuring+the+Administrator+Contact+Page