当前位置:   article > 正文

Spring Security使用JSON格式登录_spring security json

spring security json

本文内容来自王松老师的《深入浅出Spring Security》,自己在学习的时候为了加深理解顺手抄录的,有时候还会写一些自己的想法。

        Spring Security中默认的登录参数传递的格式是key/value形式,也是表单登录格式。在实际项目中我们可能会通过Json格式来登录来传递参数,这就需要我们自定义登录过滤器来实现。

        其实登录参数的提取是在UsernamePasswordAuthenticationFilter中完成的。如果我们要使用Json格式登录,我们只需要模仿UsernamePasswordAuthenticationFilter过滤器定义自己的过滤器,在将自定义的过滤器放到UsernamePasswordAuthenticationFilter所在的文职即可。

        我们自定义一个LoginFilter:

  1. /**
  2. * @author tlh
  3. * @date 2022/11/23 21:27
  4. */
  5. public class LoginFilter extends UsernamePasswordAuthenticationFilter {
  6. @Override
  7. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  8. //仅支持POST方法
  9. if (!"POST".equals(request.getMethod())) {
  10. throw new AuthenticationServiceException("当前认证不支持:" + request.getMethod());
  11. }
  12. if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE)) {
  13. try {
  14. Map<String, String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
  15. String userename = userInfo.get(getUsernameParameter());
  16. String password = userInfo.get(getPasswordParameter());
  17. UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userename, password);
  18. setDetails(request, token);
  19. return this.getAuthenticationManager().authenticate(token);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. return super.attemptAuthentication(request, response);
  25. }
  26. }
  • 首先确保进入该过滤器的请求为POST
  • 根据content-type来判断参数是Json的还是key/value格式的,如果是Json格式的就自己处理,如果不是就调用父类的attemptAuthentication方法来处理即可
  • 如果还是Json格式的数据,则利用jackson提供的ObjectMapper工具将输入流转为Map对象,然后在Map对象里面提取出用户名和密码,接着构造UsernamePasswordAuthenticationToken对象,然后调用AuthenticationManager的authenticate方法来执行认证操作

        其实LoginFilter中,从请求中提取出Json参数之后的逻辑和父类UsernamePasswordAuthenticationFilter中的认证逻辑是一样的,如下是UsernamePasswordAuthenticationFilter获取用户名和密码然后认证的逻辑:

  1. @Override
  2. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  3. throws AuthenticationException {
  4. if (this.postOnly && !request.getMethod().equals("POST")) {
  5. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  6. }
  7. String username = obtainUsername(request);
  8. username = (username != null) ? username.trim() : "";
  9. String password = obtainPassword(request);
  10. password = (password != null) ? password : "";
  11. UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
  12. password);
  13. // Allow subclasses to set the "details" property
  14. setDetails(request, authRequest);
  15. return this.getAuthenticationManager().authenticate(authRequest);
  16. }

        LoginFilter定义完之后,接下来我们将其添加到Spring Security过滤器链中去:

  1. /**
  2. * @author tlh
  3. * @date 2022/11/21 21:50
  4. */
  5. @Configuration
  6. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  7. @Override
  8. protected void configure(AuthenticationManagerBuilder auth)
  9. throws Exception {
  10. auth.inMemoryAuthentication().withUser("javagirl")
  11. .password("{noop}123")
  12. .roles("admin");
  13. }
  14. @Bean
  15. @Override
  16. public AuthenticationManager authenticationManagerBean() throws Exception {
  17. return super.authenticationManagerBean();
  18. }
  19. @Bean
  20. LoginFilter loginFilter() throws Exception {
  21. LoginFilter loginFilter = new LoginFilter();
  22. loginFilter.setAuthenticationManager(authenticationManagerBean());
  23. loginFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
  24. response.setContentType("application/json;charset=utf-8");
  25. response.getWriter().write(new ObjectMapper().writeValueAsString(authentication));
  26. });
  27. return loginFilter;
  28. }
  29. @Override
  30. protected void configure(HttpSecurity http) throws Exception {
  31. http.authorizeRequests()
  32. .anyRequest().authenticated()
  33. .and()
  34. .formLogin()
  35. .and()
  36. .csrf().disable();
  37. //表示提起掉原来的UsernamePasswordAuthenticationFilter的位置
  38. http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
  39. }
  40. @Override
  41. public void configure(WebSecurity web) throws Exception {
  42. web.ignoring()
  43. .antMatchers("/login.html", "/css/**", "/js/**", "/images/**");
  44. }
  45. }
  •  首先重写configure(AuthenticationManagerBuilder auth)方法来定义一个用户
  • 重写父类的authenticationManagerBean()方法来提供一个AuthenticationManager实例,一会将会配置给LoginFilter
  • 配置LoginFilter实例,同时将AuthenticationManager的实例设置给LoginFilter,然后配置登录成功回调。当然这里也可以设置失败回调
  • 最后在HttpSecurity中,调用addFilterAt方法将LoginFilter过滤器添加到UsernamePasswordAuthenticationFilter过滤器所在的位置

        配置完成后,重启项目,此时我们就可以用Json格式的数据来登录系统了:

        有小伙伴应该会注意到,当我们想要获得一个AuthenticationManager的实例时有两种方法:

  •  重写父类的authenticationManager方法,如下:
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
  • 从写父类的authenticationManagerBean方法,如下:
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

表面上两种方法获取的实例都可以在这里运行,但是实际上是有区别的。第一种方法authenticationManager获取到时全局的AuthenticationManager实例,第二种方法获取到的是局部的AuthenticationManager实例。而LoginFilter作为Spring Security过滤器中的一环,显然该配置局部的AuthenticationManager的实例。应为,如果将全局的AuthenticationManager的实例配置给LoginFilter,则局部的AuthenticationManager实例所对应的用户就会失效。

        实际上,如果我们想要配置一个AuthenticationManager实例,大部分情况下都是通过重写authenticationManagerBean方法来获取。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/68901
推荐阅读
相关标签
  

闽ICP备14008679号