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);
    }
}

測試

成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章