spring security登錄、登出、認證異常返回值的自定義實現

在整個學習過程中,我最關心的內容有號幾點,其中一點是【前後端分離的情況下如何不跳轉頁面而是返回需要的返回值】。
下面就說一下學習結果,以xml配置位李。

登錄成功,不跳轉頁面,返回自定義返回值

在spring官方文檔5.0.12.RELEASE第6.2.3節,有這麼一段描述:

要進一步控制目標,可以使用authentication-success-handler-ref屬性作爲default-target-url的替代。 引用的bean應該是AuthenticationSuccessHandler的一個實例。 您可以在Core Filters一章以及命名空間附錄中找到更多相關信息,以及有關如何在身份驗證失敗時自定義流的信息。

剛開始的時候我沒有注意到這個內容,後來看了spring-security-5.0.xsd文件才找到這個配置。
在xsd文件中,對這個屬性是這樣描述的:

 <xs:attribute name="authentication-success-handler-ref" type="xs:token">
         <xs:annotation>
            <xs:documentation>
            引用應該用於處理a的AuthenticationSuccessHandler bean成功的認證請求。 不應與之配合使用default-target-url(或always-use-default-target-url)應始終作爲實現處理導航到後續目的地
                </xs:documentation>
         </xs:annotation>
      </xs:attribute>

所以實現一個AuthenticationSuccessHandler的實現類:

public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        System.out.println("===========登陸成功================");
        PrintWriter printWriter = response.getWriter();
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("result", "0");
        msgMap.put("msg", "登錄成功");
        printWriter.write(new Gson().toJson(msgMap));
        printWriter.flush();
        printWriter.close();
    }
}

配置xml:

        <security:http>
              <security:intercept-url  pattern="/**" access="isAuthenticated()"/>
              <security:form-login authentication-success-handler-ref="loginAuthenticationSuccessHandler"/>
              <security:logout delete-cookies="JSESSIONID" invalidate-session="true" success-handler-ref="myLogoutSuccessHandler"/>
              <security:csrf disabled="true"/>
       </security:http>
       ......
       <bean id="loginAuthenticationSuccessHandler" class="com.nyl.securitylearn.security.handler.LoginAuthenticationSuccessHandler"/>

測試結果:
loginsuc

登出成功,不跳轉頁面,返回自定義返回值

在spring官方文檔5.0.12.RELEASE第6.2.4 logout handling節,提到這個內容:

logout元素通過導航到特定URL添加了對註銷的支持。 默認的註銷URL是/logout,但您可以使用logout-url屬性將其設置爲其他內容。 有關其他可用屬性的更多信息,請參見命名空間附錄。

查找到對應的命名空間章節43.1.26 <logout>,其中關於配置的說明:


//這個說明 success-handler-ref
success-handler-ref May be used to supply an instance of LogoutSuccessHandler which will be invoked to control the navigation after logging out.

根據說明需要實現LogoutSuccessHandler接口。

實現一個LogoutSuccessHandler的實現類:

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        System.out.println("===========登出成功================");
        PrintWriter printWriter = response.getWriter();
        response.setHeader("Content-Type", "application/json;charset=utf8");
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("result", "0");
        msgMap.put("msg", "退出成功");
        printWriter.write(new Gson().toJson(msgMap));
        printWriter.flush();
        printWriter.close();
    }
}

配置xml:

<context:component-scan base-package="com.nyl.securitylearn"/>
       <security:http>
              <security:intercept-url  pattern="/**" access="isAuthenticated()"/>
              <security:form-login authentication-success-handler-ref="loginAuthenticationSuccessHandler"/>
              <security:logout delete-cookies="JSESSIONID" invalidate-session="true" success-handler-ref="myLogoutSuccessHandler"/>
              <security:csrf disabled="true"/>
       </security:http>

測試:
logoutsuc

未登錄時,如果調用接口,不報403或401錯,返回自定義結果

43.1.21 <form-login>節中,提到了這樣一個配置authentication-failure-handler-ref :

authentication-failure-handler-ref 可用作authentication-failure-url的替代方法,使您可以在身份驗證失敗後完全控制導航流。 該值應該是應用程序上下文中AuthenticationFailureHandler bean的名稱。

xsd中的說明:

引用應該用於處理失敗的AuthenticationFailureHandler bean驗證請求。 不應與authentication-failure-url結合使用, 因爲實現應始終處理導航到後續目的地

測試配置基本和登錄成功一致,不囉嗦了。

總結

這樣就實現了基本的前後端調用要求,避免了路徑跳轉。

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