springSecurity登陸與退出json形式交互


一 前言

本篇的內容是springSecurity登陸與退出功能,交互形式使用json格式;學習本篇的基礎是知識追尋者之前發布過的文章

《springsecurity入門篇》

《springSecurity之java配置篇》

公眾號:知識追尋者

知識追尋者(Inheriting the spirit of open source, Spreading technology knowledge;)

二 登陸與退出

2.1 application.yml

配置賬號 密碼 和 擁有的角色;

spring:
  security:
    user:
      name: zszxz
      password: 123
      roles: USER,ADMIN

2.2 WebSecurityConfig

關於攔截的url授權在上篇文章已經提到過,不再贅述;下面 springSecurity 配置的重點內容是 表單 登陸成功后 會 轉到 successHandler; 登陸失敗 轉到 failureHandler; 退出登陸 轉到 outSuccessHandler; 三個 handler 返回的都是 json 數據, 這樣就已經實現了 josn進行 前后端交互 ,當然美中不足的是 登陸還是用了springSecurity 自帶的表單;我們的目的是登陸換成接口的形式,那么這個完全分離的json交互內容請看下篇文章了,不再本篇文章的討論范圍內;

/**
 * @Author lsc
 * <p> </p>
 */
@EnableWebSecurity// 開啟springSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    SuccessHandler successHandler;

    @Autowired
    FailureHandler failureHandler;

    @Autowired
    OutSuccessHandler outSuccessHandler;


    /* *
     * @Author lsc
     * <p> 授權</p>
     * @Param [http]
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()// 授權
                .antMatchers("/api/download/**").anonymous()// 匿名用戶權限
                .antMatchers("/api/**").hasRole("USER")//普通用戶權限
                .antMatchers("/api/admin/**").hasRole("ADMIN")// 管理員權限
                .and()
                .formLogin()// 登陸
                .loginProcessingUrl("/api/login")
                            .successHandler(successHandler)// 登陸成功后的處理動作
                            .failureHandler(failureHandler)// 登陸失敗后的處理動作
                            .permitAll() // 允許所有人訪問
                .and()
                .logout()
                .logoutSuccessHandler(outSuccessHandler)
                .and()
                .csrf().disable()// 關閉 csrf 否則post
                .httpBasic();// http請求方式 ,web 瀏覽器會彈出對話框

    }



}

2.3 handler

handler 這邊使用 fastjson 作為json處理;

SuccessHandler內容如下,其是實現 AuthenticationSuccessHandler 類;作用就是登陸成功后返回的內容

知識追尋者 這邊設置一些CORS 和 中文亂碼處理的響應頭;

/**
 * @Author lsc
 * <p> 登陸成功后處理 </p>
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 跨域處理
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允許的請求方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        // 允許的請求頭
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 設置響應頭
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // 返回值
        ResultPage result = ResultPage.sucess(CodeMsg.SUCESS, "登陸成功");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

FailureHandler 實現 AuthenticationFailureHandler類, 登陸失敗后的返回內容;

/**
 * @Author lsc
 * <p>登陸失敗調用 </p>
 */
@Component
public class FailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 返回值
        ResultPage result = ResultPage.error(CodeMsg.ACCOUNT_ERROR);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

OutSuccessHandler 實現 LogoutSuccessHandler ,即退出登陸后返回的內容;

/**
 * @Author lsc
 * <p> </p>
 */
@Component
public class OutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 設置響應頭
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // 返回值
        ResultPage result = ResultPage.sucess(CodeMsg.SUCESS,"退出登陸成功");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}

2.4 控制層

控制層主要是定義一個接口進行測試

/**
 * @Author lsc
 * <p> </p>
 */
@RestController
public class SysUserController {

    @GetMapping("api/test")
    public String  test(){
        return "普通用戶訪問";
    }

    @GetMapping("api/admin/test")
    public String  testAdmin(){
        return "管理員訪問";
    }
}

2.5 測試結果

登陸成功,返回josn 內容

NkKqqe.png

接口測試, 返回json 內容

NkMCM8.png

退出登陸,返回json 內容

NkMKMT.png

如果退出后繼續訪問 localhost:8080/api/test 會出現403 禁止登陸;當然如何處理 403 權限問題也是下篇內容

關注知識追尋者:
tLeP2D.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM