SpringBoot整合SpringSecurity前后端分离实现JSON登录

在前后端分离项目中,通常是通过json格式数据传递信息,但是SpingSecurity中默认获取登录账号密码方式为通过表单提交的key/value形式过去,具体官方源码处理方式如下:

public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}

		String username = obtainUsername(request);
		String password = obtainPassword(request);

		if (username == null) {
			username = "";
		}

		if (password == null) {
			password = "";
		}

		username = username.trim();

		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				username, password);

		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);

		return this.getAuthenticationManager().authenticate(authRequest);
	}

但是如果要处理json数据进行登录,我们可以重写UsernamePasswordAuthenticationFilter类中attemptAuthentication方法实现

创建自定义过滤器LoginAuthenticationFilter
public class LoginAuthenticationFilter 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());
        }
        //如果是application/json类型,做如下处理
        if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            //以json形式处理数据
            String username = null;
            String password = null;

            try {
            	//将请求中的数据转为map
                Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                username = map.get("username");
                password = map.get("password");
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (username == null) {
                username = "";
            }
            if (password == null) {
                password = "";
            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);

            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        }
        //否则使用官方默认处理方式
        return super.attemptAuthentication(request, response);
    }
}
编写SpringSecurity配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  	@Bean
    LoginAuthenticationFilter loginAuthenticationFilter() throws Exception {
        LoginAuthenticationFilter filter = new LoginAuthenticationFilter();
        filter.setFilterProcessesUrl("/doLogin");
        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                Hr hr = (Hr) authentication.getPrincipal();
                hr.setPassword(null);
                RespResult result = RespResult.ok("登录成功", hr);
                String msg = new ObjectMapper().writeValueAsString(result);
                writer.write(msg);
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                RespResult result = RespResult.error("登录失败");;
                if (e instanceof BadCredentialsException) {
                    result.setMsg("用户名或密码错误,请检查");
                }else if(e instanceof LockedException){
                    result.setMsg("账户被锁定,请联系管理员");
                }else if(e instanceof CredentialsExpiredException){
                    result.setMsg("密码已过期,请联系管理员");
                }else if(e instanceof AccountExpiredException){
                    result.setMsg("账户已过期,请联系管理员");
                }else if(e instanceof DisabledException){
                    result.setMsg("账户被禁用,请联系管理员");
                }
                String msg = new ObjectMapper().writeValueAsString(result);
                writer.write(msg);
                writer.flush();
                writer.close();
            }
        });
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        RespResult result = RespResult.ok("注销退出成功");
                        String msg = new ObjectMapper().writeValueAsString(result);
                        writer.write(msg);
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable();

        http.addFilterAt(loginAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
    }
}
测试

成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值