先说说SpringSecurity如何实现前后端分离Ajax登录?
今天使用SpringBoot整合SpringSecurity中想使用Ajax替代SpringSecurit的Form表单提交,在这里我们的提交方式还是使用表单提交
http.formLogin().loginProcessingUrl("/authentication/form")
loginProcessingUrl方法表示你登录请求的地址,在这里SpringSecurity默认登录页面地址是/login ,填写了username与password 上送的地址就是loginProcessingUrl方法指定的地址,
如果你想使用Ajax登录+Token验证,或者是移动端不得不这样做的时候,那么你就不用管SpringSecurity的默认登录地址啦,只需要注意 在Ajax请求的时候 登录名必须是username字段
密码必须是 password字段 登录提交的地址就是loginProcessingUrl方法指定的路径/authentication/form
因为在SpringSecurity中处理账号密码登录的过滤器是UsernamePasswordAuthenticationFilter 而这个登录处理类里面写死了这两个字段的名称,如下图源码中所见:
public class UsernamePasswordAuthenticationFilter extendsAbstractAuthenticationProcessingFilter {//~ Static fields/initializers//=====================================================================================
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
我测试的前端登录代码如下:
$.ajax({
url:"http://127.0.0.1/authentication/form",
timeout : 20000,
type:"post",
dataType:"json",
data:{
username:"088358",password:"123"
},
success:function(data){
alert('ok')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("1 异步调用返回失败,XMLHttpResponse.readyState:"+XMLHttpRequest.readyState);
alert("2 异步调用返回失败,XMLHttpResponse.status:"+XMLHttpRequest.status);
alert("3 异步调用返回失败,textStatus:"+textStatus);
alert("4 异步调用返回失败,errorThrown:"+errorThrown);
}
})
后端在执行登录成功之后处理代码
后端在执行登录成功之后会回调AuthenticationSuccessHandler拦截器的onAuthenticationSuccess方法,我们只需要写一个类集成AuthenticationSuccessHandler就可以重写这个方法来生成token返回给前端了,Token如何生成,请看上一章jwtToken的使用 https://www.cnblogs.com/langjunnan/p/12464791.html ,这章不细说
@Componentpublic class MyAuthenticationSuccessHandler implementsAuthenticationSuccessHandler {
@Overridepublic voidonAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication)throwsIOException, ServletException {//登录成功之后
List functs = (List) authentication.getAuthorities();//当前功能列表
String loginName = authentication.getName();//登录名
Users obj = (Users) authentication.getPrincipal();//用户信息
String token = JwtUtil.createToken(loginName, functs, obj);//生成token
response.setHeader(JwtUtil.TOKEN_HEADER, JwtUtil.TOKEN_PREFIX +token);
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter pw=response.getWriter();
DTO dto= new DTO<>();
dto.setCode("000000");
dto.setMessage("认证通过");
String json=JsonUtil.set(dto);
System.out.println(json);
pw.println(json);//println 等于pw.flush()+pw.close();
}
}
代码是没有问题的,但是由于跨域的问题Ajax是调用不成功的,
SpringSecurity中的跨域问题
之前写项目都是自己定义一个过滤器来解决跨域问题,但是这次过滤器不好用了,只能把跨域资源配置到SpringSecurity中了
代码如下
http.cors().configurationSource(CorsConfigurationSource())//允许跨域访问
/*跨域原*/
privateCorsConfigurationSource CorsConfigurationSource() {
CorsConfigurationSource source= newUrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration= newCorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
corsConfiguration.addAllowedHeader("*");//header,允许哪些header,本案中使用的是token,此处可将*替换为token;
corsConfiguration.addAllowedMethod("*"); //允许的请求方法,PSOT、GET等
((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**",corsConfiguration); //配置允许跨域访问的url
returnsource;
}