详解Spring Security如何配置JSON登录

所属分类: 软件编程 / java 阅读数: 22
收藏 0 赞 0 分享

spring security用了也有一段时间了,弄过异步和多数据源登录,也看过一点源码,最近弄rest,然后顺便搭oauth2,前端用json来登录,没想到spring security默认居然不能获取request中的json数据,谷歌一波后只在stackoverflow找到一个回答比较靠谱,还是得要重写filter,于是在这里填一波坑。

准备工作

基本的spring security配置就不说了,网上一堆例子,只要弄到普通的表单登录和自定义UserDetailsService就可以。因为需要重写Filter,所以需要对spring security的工作流程有一定的了解,这里简单说一下spring security的原理。


spring security 是基于javax.servlet.Filter的,因此才能在spring mvc(DispatcherServlet基于Servlet)前起作用。

  1. UsernamePasswordAuthenticationFilter:实现Filter接口,负责拦截登录处理的url,帐号和密码会在这里获取,然后封装成Authentication交给AuthenticationManager进行认证工作
  2. Authentication:贯穿整个认证过程,封装了认证的用户名,密码和权限角色等信息,接口有一个boolean isAuthenticated()方法来决定该Authentication认证成功没;
  3. AuthenticationManager:认证管理器,但本身并不做认证工作,只是做个管理者的角色。例如默认实现ProviderManager会持有一个AuthenticationProvider数组,把认证工作交给这些AuthenticationProvider,直到有一个AuthenticationProvider完成了认证工作。
  4. AuthenticationProvider:认证提供者,默认实现,也是最常使用的是DaoAuthenticationProvider。我们在配置时一般重写一个UserDetailsService来从数据库获取正确的用户名密码,其实就是配置了DaoAuthenticationProvider的UserDetailsService属性,DaoAuthenticationProvider会做帐号和密码的比对,如果正常就返回给AuthenticationManager一个验证成功的Authentication

看UsernamePasswordAuthenticationFilter源码里的obtainUsername和obtainPassword方法只是简单地调用request.getParameter方法,因此如果用json发送用户名和密码会导致DaoAuthenticationProvider检查密码时为空,抛出BadCredentialsException。

/**
   * Enables subclasses to override the composition of the password, such as by
   * including additional values and a separator.
   * <p>
   * This might be used for example if a postcode/zipcode was required in addition to
   * the password. A delimiter such as a pipe (|) should be used to separate the
   * password and extended value(s). The <code>AuthenticationDao</code> will need to
   * generate the expected password in a corresponding manner.
   * </p>
   *
   * @param request so that request attributes can be retrieved
   *
   * @return the password that will be presented in the <code>Authentication</code>
   * request token to the <code>AuthenticationManager</code>
   */
  protected String obtainPassword(HttpServletRequest request) {
    return request.getParameter(passwordParameter);
  }

  /**
   * Enables subclasses to override the composition of the username, such as by
   * including additional values and a separator.
   *
   * @param request so that request attributes can be retrieved
   *
   * @return the username that will be presented in the <code>Authentication</code>
   * request token to the <code>AuthenticationManager</code>
   */
  protected String obtainUsername(HttpServletRequest request) {
    return request.getParameter(usernameParameter);
  }

重写UsernamePasswordAnthenticationFilter

上面UsernamePasswordAnthenticationFilter的obtainUsername和obtainPassword方法的注释已经说了,可以让子类来自定义用户名和密码的获取工作。但是我们不打算重写这两个方法,而是重写它们的调用者attemptAuthentication方法,因为json反序列化毕竟有一定消耗,不会反序列化两次,只需要在重写的attemptAuthentication方法中检查是否json登录,然后直接反序列化返回Authentication对象即可。这样我们没有破坏原有的获取流程,还是可以重用父类原有的attemptAuthentication方法来处理表单登录。

/**
 * AuthenticationFilter that supports rest login(json login) and form login.
 * @author chenhuanming
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    //attempt Authentication when Content-Type is json
    if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
        ||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){

      //use jackson to deserialize json
      ObjectMapper mapper = new ObjectMapper();
      UsernamePasswordAuthenticationToken authRequest = null;
      try (InputStream is = request.getInputStream()){
        AuthenticationBean authenticationBean = mapper.readValue(is,AuthenticationBean.class);
        authRequest = new UsernamePasswordAuthenticationToken(
            authenticationBean.getUsername(), authenticationBean.getPassword());
      }catch (IOException e) {
        e.printStackTrace();
        new UsernamePasswordAuthenticationToken(
            "", "");
      }finally {
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
      }
    }

    //transmit it to UsernamePasswordAuthenticationFilter
    else {
      return super.attemptAuthentication(request, response);
    }
  }
}

封装的AuthenticationBean类,用了lombok简化代码(lombok帮我们写getter和setter方法而已)

@Getter
@Setter
public class AuthenticationBean {
  private String username;
  private String password;
}

WebSecurityConfigurerAdapter配置

重写Filter不是问题,主要是怎么把这个Filter加到spring security的众多filter里面。

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .cors().and()
      .antMatcher("/**").authorizeRequests()
      .antMatchers("/", "/login**").permitAll()
      .anyRequest().authenticated()
      //这里必须要写formLogin(),不然原有的UsernamePasswordAuthenticationFilter不会出现,也就无法配置我们重新的UsernamePasswordAuthenticationFilter
      .and().formLogin().loginPage("/")
      .and().csrf().disable();

  //用重写的Filter替换掉原有的UsernamePasswordAuthenticationFilter
  http.addFilterAt(customAuthenticationFilter(),
  UsernamePasswordAuthenticationFilter.class);
}

//注册自定义的UsernamePasswordAuthenticationFilter
@Bean
CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
  CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
  filter.setAuthenticationSuccessHandler(new SuccessHandler());
  filter.setAuthenticationFailureHandler(new FailureHandler());
  filter.setFilterProcessesUrl("/login/self");

  //这句很关键,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己组装AuthenticationManager
  filter.setAuthenticationManager(authenticationManagerBean());
  return filter;
}

题外话,如果搭自己的oauth2的server,需要让spring security oauth2共享同一个AuthenticationManager(源码的解释是这样写可以暴露出这个AuthenticationManager,也就是注册到spring ioc)

@Override
@Bean // share AuthenticationManager for web and oauth
public AuthenticationManager authenticationManagerBean() throws Exception {
  return super.authenticationManagerBean();
}

至此,spring security就支持表单登录和异步json登录了。

参考来源

stackoverflow的问答

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java的面向对象编程基本概念学习笔记整理

这篇文章主要介绍了Java的面向对象编程基本概念学习笔记整理,包括类与方法以及多态等支持面向对象语言中的重要特点,需要的朋友可以参考下
收藏 0 赞 0 分享

Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法

这篇文章主要介绍了Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

基于Java实现杨辉三角 LeetCode Pascal's Triangle

这篇文章主要介绍了基于Java实现杨辉三角 LeetCode Pascal's Triangle的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java中Spring获取bean方法小结

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,如何在程序中获取Spring配置的bean呢?下面通过本文给大家介绍Java中Spring获取bean方法小结,对spring获取bean方法相关知识感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

如何计算Java对象占用了多少空间?

在Java中没有sizeof运算符,所以没办法知道一个对象到底占用了多大的空间,但是在分配对象的时候会有一些基本的规则,我们根据这些规则大致能判断出来对象大小,需要的朋友可以参考下
收藏 0 赞 0 分享

剖析Java中的事件处理与异常处理机制

这篇文章主要介绍了Java中的事件处理与异常处理机制,讲解Java是如何对事件或者异常作出响应以及定义异常的一些方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Java的Struts2框架的结构及其数据转移方式

这篇文章主要介绍了详解Java的Struts2框架的结构及其数据转移方式,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

Java封装好的mail包发送电子邮件的类

本文给大家分享了2个java封装好的mail包发送电子邮件的类,并附上使用方法,小伙伴们可以根据自己的需求自由选择。
收藏 0 赞 0 分享

在Java的Struts中判断是否调用AJAX及用拦截器对其优化

这篇文章主要介绍了在Java的Struts中判断是否调用AJAX及用拦截器对其优化的方法,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

java多线程Future和Callable类示例分享

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。今天我们就来研究下Future和Callab
收藏 0 赞 0 分享
查看更多