1. 程式人生 > 其它 >SpringBoot 支援json方式登入

SpringBoot 支援json方式登入

技術標籤:javaspringbootjson登入

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