JavaWeb-SpringSecurity实现需求-判断请求是否以html结尾
系列博文
项目已上传至guthub 传送门
JavaWeb-SpringSecurity初认识 传送门
JavaWeb-SpringSecurity在数据库中查询登陆用户 传送门
JavaWeb-SpringSecurity自定义登陆页面 传送门
JavaWeb-SpringSecurity实现需求-判断请求是否以html结尾 传送门
JavaWeb-SpringSecurity自定义登陆配置 传送门
JavaWeb-SpringSecurity图片验证ImageCode 传送门
JavaWeb-SpringSecurity记住我功能 传送门
JavaWeb-SpringSecurity使用短信验证码登陆 传送门
需求
请求来了,判断请求是否以html结尾,是以html结尾则重定向到登陆页面,不是以html结尾就需要进行身份认证
首先我们在SecurityConfig.java中configure()方法中修改自定义登陆页面访问路径为/require,打开SpringSecurity对/require请求的身份认证
protected void configure(HttpSecurity http) throws Exception{ //表单验证(身份认证) http.formLogin() //自定义登陆页面 .loginPage("/require") //如果URL为loginPage,则用SpringSecurity中自带的过滤器去处理该请求 .loginProcessingUrl("/loginPage") .and() //请求授权 .authorizeRequests() //在访问我们的URL时,我们是不需要省份认证,可以立即访问 .antMatchers("/login.html","/require").permitAll() //所有请求都被拦截,跳转到(/login请求中) .anyRequest() //都需要我们身份认证 .authenticated() //SpringSecurity保护机制 .and().csrf().disable(); }
在controller层下创建SecurityController.java作为用户发起的请求
@RequestMapping("/require") public String require() { //判断之前的请求是否以html结尾 //如果是,重定向到登陆页面 //如果不是,我们就让他身份认证 return null; }
package com.Gary.GaryRESTful.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; //Web应用安全适配器 @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter{ //告诉SpringSecurity密码用什么加密的 @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } protected void configure(HttpSecurity http) throws Exception{ //表单验证(身份认证) http.formLogin() //自定义登陆页面 .loginPage("/require") //如果URL为loginPage,则用SpringSecurity中自带的过滤器去处理该请求 .loginProcessingUrl("/loginPage") .and() //请求授权 .authorizeRequests() //在访问我们的URL时,我们是不需要省份认证,可以立即访问 .antMatchers("/login.html","/require").permitAll() //所有请求都被拦截,跳转到(/login请求中) .anyRequest() //都需要我们身份认证 .authenticated() //SpringSecurity保护机制 .and().csrf().disable(); } }
package com.Gary.GaryRESTful.controller; import org.springframework.web.bind.annotation.RequestMapping; public class SecurityController { @RequestMapping("require") public String require() { //判断之前的请求是否以html结尾 //如果是,重定向到登陆页面 //如果不是,我们就让他身份认证 return null; } }