Spring security筆記3/4: 自定義登陸頁面

自定義登陸頁面

在以前的示例基礎上,自定義認證的返回。
對於來自瀏覽器的請求,將頁面重定向到自定義的登陸頁。
對於來自其餘客戶端的請求 (好比APP),已 Json 形式返回認證結果。html

實現步驟

1. 複製上一示例的源碼

重命名包名 case2 爲 case3java

重命名 Case2Application.java 爲 Case3Application.javaweb

2. 在 WebSecurityConfig 中配置登陸頁

在 config(HttpSecurity http) 方法中對 formLogin 選項進行配置。須要包含如下設置:算法

  • 放行自定義登陸頁 url,例如: /login.html;
  • 設置登陸跳轉頁 url, 例如: /login.html;
  • 禁用 csrf 保護。如不添加此項,則須要每次從 cookie 中獲取 csrftoken 的值並隨表單一同提交到服務端。

完整代碼以下:spring

package net.txt100.learn.springsecurity.base.case3.config;

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;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Title: WebSecurityConfig
 * Package: net.txt100.learn.springsecurity.base.case3.config
 * Creation date: 2019-08-11
 * Description:
 *
 * @author <a href="zgjt_tongl@thunis.com">Tonglei</a>
 * @since 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置密碼的保護策略,spring security 默認使用 bcrypt 加密算法。
        // 此處只要顯式聲明 BCryptPasswordEncoder Bean 便可
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        UsernamePasswordAuthenticationFilter up;

        http
            .csrf().disable() // 關閉 CSRF 保護功能,不然不支持 Post 請求
            .authorizeRequests() // 針對 HttpServletRequest 進行安全配置
                .antMatchers("/login.html").permitAll() // login.html 頁面無需登陸便可訪問
                .anyRequest().authenticated() // 對全部 Request 均需安全認證
            .and().formLogin()
                .loginPage("/login.html") // 每當須要登陸時瀏覽器跳轉到 login.html 頁面
                .loginProcessingUrl("/login") // 自定義登陸提交地址,默認地址是 /login, 默認處理器是 UsernamePasswordAuthenticationFilter
//                 .usernameParameter("/phone_number") // 自定義登陸用戶ID參數,默認是 username
//                 .passwordParameter("/check_code") // 自定義登陸口令參數,默認是 password
            .and().httpBasic(); // 定義如何驗證用戶,此項表明彈出瀏覽器認證窗口
    }
}

3. 建立 login.html 頁面

新建目錄 src/main/webapp,並在該目錄下建立文件 login.html。須要至少包含:瀏覽器

  • form 標籤,而且 action 賦值爲 WebSecurityConfig 中 loginProcessingUrl 配置地址 (默認: "/login");
  • 用戶名參數,與 WebSecurityConfig 中 usernameParameter 配置一致(默認:"username");
  • 密碼參數,與 WebSecurityConfig 中 passwordParameter 配置一致(默認:"password")。

4. 登陸測試

  1. 訪問 http://localhost:8080/user/all,能夠看到進入自定義的登陸界面安全

  2. 輸入正確用戶名密碼,能夠訪問到被保護資源cookie

總結

spring security 中,開發者能夠自定義登陸頁的app

  • 訪問地址
  • 認證地址
  • 用戶名參數
  • 密碼參數

最後不要忘記放開登陸頁的訪問權限。webapp

相關文章
相關標籤/搜索