spring security他是自带一个页面的,如果我们没有页面的话,他会进行一个账号密码的校验,成功就会走成功的处理器,失败就会走失败的处理器
package com.lzy.security;
import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 将响应的内容类型设置为JSON
response.setContentType("application/json;charset=utf-8");
// 获取响应的输出流
ServletOutputStream out = response.getOutputStream();
//生成JWT,并且放置到请求头
// 创建一个包含异常消息的Result对象
Result result = Result.success("成功");
// 将Result对象转换为JSON字符串,并写入输出流
out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
// 刷新输出流
out.flush();
// 关闭输出流
out.close();
}
}
package com.lzy.security;
import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
// 当身份验证失败时调用此方法
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// 将响应的内容类型设置为JSON
response.setContentType("application/json;charset=utf-8");
// 获取响应的输出流
ServletOutputStream out = response.getOutputStream();
// 创建一个包含异常消息的Result对象
Result result = Result.fail(exception.getMessage());
// 将Result对象转换为JSON字符串,并写入输出流
out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
// 刷新输出流
out.flush();
// 关闭输出流
out.close();
}
}
package com.lzy.config;
import com.lzy.security.CaptchaFilter;
import com.lzy.security.LoginFailureHandler;
import com.lzy.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LoginFailureHandler loginFailureHandler;
@Autowired
LoginSuccessHandler loginSuccessHandler;
@Autowired
CaptchaFilter captchaFilter;
private static final String[] URL_WHITELIST = {
"/login",
"/logout",
"/captcha",
"/favicon.ico", // 防止 favicon 请求被拦截
};
protected void configure(HttpSecurity http) throws Exception {
//跨域配置
http.cors().and().csrf().disable()
//登录配置
.formLogin()
.successHandler(loginSuccessHandler).failureHandler(loginFailureHandler)
//禁用session
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//配置拦截规则
.and().authorizeRequests()
//白名单
.antMatchers(URL_WHITELIST).permitAll()
//其他请求都需要认证
.anyRequest().authenticated()
//异常处理器
//配置自定义的过滤器
.and().addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);
}
}
因为spring security是不带验证码过滤器的,所以得我们自己写,并且要写在账号密码过滤器前,失败就走失败处理器
package com.lzy.security;
import com.lzy.common.exception.CaptureException;
import com.lzy.util.Constants;
import com.lzy.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CaptchaFilter extends OncePerRequestFilter {
@Autowired
RedisUtil redisUtil;
@Autowired
LoginFailureHandler loginFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//判断是不是登录请求
String url = request.getRequestURI();
if (url.equals("/login") && request.getMethod().equals("POST")) {
//如果是登录请求,判断验证码是否为空
try {
//验证验证码
voildCaptcha(request, response, filterChain);
} catch (CaptureException e) {
//交给登录失败处理器
loginFailureHandler.onAuthenticationFailure(request, response, e);
}
}
filterChain.doFilter(request, response);
}
private void voildCaptcha(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
String captcha = request.getParameter("code");
String key = request.getParameter("token");
//判断验证码是否为空
if (captcha.isBlank() || key.isBlank()) {
throw new CaptureException("验证码不能为空");
}
//判断验证码是否正确
if (!redisUtil.hget(Constants.CAPTURE, key).equals(captcha)) {
throw new CaptureException("验证码错误");
}
//删除验证码
redisUtil.hdel(Constants.CAPTURE, key);
}
}
也是在刚才的securitycofig下面调用,代码就是刚才那个