SpringBoot - 安全管理框架Spring Security使用詳解(7)-註銷登錄配置

默認情況下,Spring Security 提供了註銷接口是 /logout,訪問這個接口即可註銷當前登錄用戶並且自動跳轉到登錄頁。如果需要修改註銷接口,或者想在註銷時做一些業務邏輯,或者註銷後不是跳轉到登錄頁而是返回一段 JSON 提示,只需在一些簡單配置即可。

 

七、註銷登錄配置

1,樣例代碼

首先修改 Spring Security 配置,增加相關的自定義配置代碼:

  • 開啓並設置註銷登錄的 URL。
  • 在註銷是做一些數據清除工作。
  • 註銷後返回一段 JSON 提示,而是不是跳轉到登錄頁。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

@Configuration

public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    // 指定密碼的加密方式

    @SuppressWarnings("deprecation")

    @Bean

    PasswordEncoder passwordEncoder(){

        // 不對密碼進行加密

        return NoOpPasswordEncoder.getInstance();

    }

 

    // 配置用戶及其對應的角色

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()

                .withUser("root").password("123").roles("DBA")

                .and()

                .withUser("admin").password("123").roles("ADMIN")

                .and()

                .withUser("hangge").password("123").roles("USER");

    }

    // 配置 URL 訪問權限

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests() // 開啓 HttpSecurity 配置

            .antMatchers("/db/**").hasRole("DBA"// db/** 模式URL需DBA角色

            .antMatchers("/admin/**").hasRole("ADMIN"// admin/** 模式URL需ADMIN角色

            .antMatchers("/user/**").hasRole("USER"// user/** 模式URL需USER角色

            .anyRequest().authenticated() // 用戶訪問其它URL都必須認證後訪問(登錄後訪問)

            .and().formLogin().loginProcessingUrl("/login").permitAll() // 開啓表單登錄並配置登錄接口

            .and().logout() // 開啓註銷登錄的配置

            .logoutUrl("/logout"// 配置註銷登錄請求URL爲"/logout"(默認也就是 /logout)

            .clearAuthentication(true// 清除身份認證信息

            .invalidateHttpSession(true// 使 session 失效

            // 配置一個 LogoutHandler,開發者可以在這裏完成一些數據清除工做

            .addLogoutHandler(new LogoutHandler() {

                @Override

                public void logout(HttpServletRequest req,

                                   HttpServletResponse resp,

                                   Authentication auth) {

                    System.out.println("註銷登錄,開始清除Cookie。");

                }

            })

            // 配置一個 LogoutSuccessHandler,開發者可以在這裏處理註銷成功後的業務邏輯

            .logoutSuccessHandler(new LogoutSuccessHandler() {

                @Override

                public void onLogoutSuccess(HttpServletRequest req,

                                            HttpServletResponse resp,

                                            Authentication auth)

                        throws IOException, ServletException {

                    // 我們可以跳轉到登錄頁面

                    // resp.sendRedirect("/login");

 

                    // 也可以返回一段JSON提示

                    resp.setContentType("application/json;charset=utf-8");

                    PrintWriter out = resp.getWriter();

                    resp.setStatus(200);

                    Map<String, Object> map = new HashMap<>();

                    map.put("status"200);

                    map.put("msg""註銷成功!");

                    ObjectMapper om = new ObjectMapper();

                    out.write(om.writeValueAsString(map));

                    out.flush();

                    out.close();

                }

            })

            .and().csrf().disable(); // 關閉csrf

    }

}

 

2,運行測試 

(1)用戶登錄後,我們訪問 /logout 接口進行註銷。註銷後頁面上返回如下信息,而是不是跳轉到登錄頁面。

原文:SpringBoot - 安全管理框架Spring Security使用詳解7(註銷登錄配置)

 

(2)控制檯輸出如下:

原文:SpringBoot - 安全管理框架Spring Security使用詳解7(註銷登錄配置)

 

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