一、Security Configure配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
.addFilterBefore(smsCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加短信验证码校验过滤器
.formLogin() // 表单登录
// http.httpBasic() // HTTP Basic
.loginPage("/authentication/require") // 登录跳转 URL, 进行验证或者登陆页 跳转
.loginProcessingUrl("/login") // 处理表单登录 URL
.successHandler(authenticationSucessHandler) // 处理登录成功
.failureHandler(authenticationFailureHandler) // 处理登录失败
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库
.tokenValiditySeconds(3600) // remember 过期时间,单为秒
.userDetailsService(userDetailService) // 处理自动登录逻辑
.and()
.authorizeRequests() // 授权配置
.antMatchers("/authentication/require", "/login.html", "/code/image",
"/code/sms", "/session/invalid", "/css/*", "/js/*", "/login1.html", "/statics/**").permitAll() // 登录跳转 URL 无需认证 (含登录页的静态资源,css/*和js/*是默认的初始资源src/main/resources/resources下的,/statics/**是配置了freemarker 并且设了 registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/"); 后的静态资源位置)
.anyRequest() // 所有请求
.authenticated() // 都需要认证
.and()
.sessionManagement() // 添加 Session管理器
.invalidSessionUrl("/session/invalid") // Session失效后跳转到这个链接
.and()
.csrf().disable()// 关闭 CSRF攻击防御关了
.apply(smsAuthenticationConfig); // 将短信验证码认证配置加到 Spring Security 中
}
二、1)不配置模板和controller,验证页面用@RestController(默认开启@ResponseBody),默认的security重定向路径在 src/main/resources/resources (两层resources )/authentication/require -----> login.html
2)配置了freemarker,并且验证页用@Controller,把重定向的路径开放在 antMathers,并且返回页面的前缀,就会跳转到重定向路径的页面。/authentication/require -----> login1.html(开放的请求路径,返回login1)--->freemarker template-loader-path下的login1页面(后缀由freemarker配置决定)
package com.sf.controller;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author MrBird
*/
@Controller
public class BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();//Spring Security提供的用于缓存请求的对象
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
/*if (true) {
throw new ValidateCodeException("aaaa11");//@RestControllerAdvice hanlder自动处理
}*/
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
//redirectStrategy.sendRedirect(request, response, "/login.html")//初始RestController直接重定向html
redirectStrategy.sendRedirect(request, response, "/login1.html");//controller重定向下面controller的 @GetMapping("login1.html"),并且 配置了freemarker的classpath,用的@Controller,到classpath下面找对应名称的页面
}
return "访问的资源需要身份认证!";
}
@GetMapping("session/invalid")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String sessionInvalid(){
return "session已失效,请重新认证";
}
@GetMapping("login1.html")
public String rediret(){
return "login1";
//在freemarker的template-loader-path: classpath:/templates 下面找 login1+配置的后缀 文件
}
}
三、Freemarker配置
pom.xml
<!--模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.yml
spring:
freemarker:
suffix: .html
request-context-attribute: request
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径(取决上面的suffix后缀)
template-loader-path: classpath:/templates
四、Spring 配置静态页面搜索路径,少了这个,静态页面显示404,或者refused to apply,哪怕上面配置把静态页"/statics/**"
面加入到不拦截数值(因为不知道定位)里面也无效。
package com.sf.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc配置
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 添加静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
}
}