SpringBoot 支持json方式登录

  • UsernamePasswordAuthenticationFilter负责处理登录逻辑,我们可以通过继承该方法,重写登录逻辑
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String contentType = request.getContentType();
        if (contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            Map<String, String> map;
            try {
                map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                throw new AuthenticationServiceException("系统异常,请稍后重试!");
            }
            String username = map.get(getUsernameParameter());
            username = (username != null) ? username : "";
            username = username.trim();
            String password = map.get(getPasswordParameter());
            password = (password != null) ? password : "";
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return getAuthenticationManager().authenticate(authRequest);
        } else {
            // 不是json格式,则调用原方法进行处理
            return super.attemptAuthentication(request, response);
        }
    }
}
  • 在 WebSecurity 的配置类中添加如下代码
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .csrf().disable()
                // 添加过滤器
                .addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }

	// 处理登录成功和失败的响应
    LoginFilter loginFilter() throws Exception {
        LoginFilter filter = new LoginFilter();
        filter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            User user = (User)authentication.getPrincipal();
            Map<String, Object> map = new HashMap<>();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            map.put("msg", "登录成功");
            user.setPassword(null);
            map.put("obj", user);
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        });
        filter.setAuthenticationFailureHandler((request, response, exception) -> {
            Map<String, String> map = new HashMap<>();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            if (exception instanceof LockedException) {
                map.put("msg", "账户被锁定");
            } else if (exception instanceof AccountExpiredException) {
                map.put("msg", "账户已过期");
            } else if (exception instanceof BadCredentialsException) {
                map.put("msg", "用户或密码错误");
            } else if (exception instanceof DisabledException) {
                map.put("msg", "账户被禁用");
            } else if (exception instanceof UsernameNotFoundException) {
                map.put("msg", "该账户不存在");
            } else {
                map.put("msg", exception.getMessage());
            }
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        });
        // authenticationManagerBean() 是 WebSecurityConfigurerAdapter 中的方法
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setUsernameParameter("name");
        filter.setPasswordParameter("passwd");
        filter.setFilterProcessesUrl("/login");
        return filter;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值