在以前的示例基礎上,自定義認證的返回。
對於來自瀏覽器的請求,將頁面重定向到自定義的登陸頁。
對於來自其餘客戶端的請求 (好比APP),已 Json 形式返回認證結果。html
重命名包名 case2 爲 case3java
重命名 Case2Application.java 爲 Case3Application.javaweb
在 config(HttpSecurity http) 方法中對 formLogin 選項進行配置。須要包含如下設置:算法
完整代碼以下: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(); // 定義如何驗證用戶,此項表明彈出瀏覽器認證窗口 } }
新建目錄 src/main/webapp,並在該目錄下建立文件 login.html。須要至少包含:瀏覽器
訪問 http://localhost:8080/user/all,能夠看到進入自定義的登陸界面安全
輸入正確用戶名密碼,能夠訪問到被保護資源cookie
spring security 中,開發者能夠自定義登陸頁的app
最後不要忘記放開登陸頁的訪問權限。webapp