在以前的示例基础上,自定义认证的返回。
对于来自浏览器的请求,将页面重定向到自定义的登陆页。
对于来自其余客户端的请求 (好比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