重写登录成功和登录失败处理器
common下新建security包,再新建两个类,LoginSuccessHandler和LoginFailureHandler
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=UTF-8");
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
String username="user";
String token = JwtUtils.genJwtToken(username);
outputStream.write(JSONUtil.toJsonStr(R.ok("登录成功").put("authorization",token)).getBytes());
outputStream.flush();
outputStream.close();
}
}
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=UTF-8");
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
String message=e.getMessage();
if(e instanceof BadCredentialsException){
message="用户名或者密码错误!";
}
outputStream.write(JSONUtil.toJsonStr(R.error(message)).getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
}
}
SecurityConfig注入这两个类对象,然后设置到自定义配置里面去
前端安装qs依赖,用于url参数,把对象转成url字符串
<script setup>
import {ref} from "vue"
import requestUtil from '@/util/request'
import store from '@/store'
import {ElMessage} from 'element-plus'
import qs from 'qs'
const loginRef=ref(null);
const loginForm=ref({
username:"",
password:""
})
const loginRules = {
username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
password: [{ required: true, trigger: "blur", message: "请输入您的密码" }]
};
const handleLogin=()=>{
loginRef.value.validate(async (valid)=>{
if(valid){
try{
let result=await requestUtil.post("login?"+qs.stringify(loginForm.value))
let data=result.data;
if(data.code==200){
const token = data.authorization;
store.commit('SET_TOKEN',token);
}else{
ElMessage.error(data.msg)
}
}catch(err){
console.log("error:"+error);
ElMessage.error("服务器出错,请联系管理员!")
}
}else{
console.log("验证失败")
}
})
}
</script>