Spring Security系列一

Spring Security是一個功能強大且高度可定製的身份驗證和訪問控制框架。它是用於保護基於Spring的應用程序的實際標準。Spring Security是一個框架,致力於爲Java應用程序提供身份驗證和授權。與所有Spring項目一樣,Spring Security的真正強大之處在於可以輕鬆擴展以滿足自定義要求

新建一個springboot工程,導入Spring Security依賴

 <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

寫一個controller

@RestController
public class SecurityController {
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }
}

啓動項目
訪問http://localhost:8090/hello,頁面會跳轉到http://localhost:8090/login:
在這裏插入圖片描述
查看控制檯
在這裏插入圖片描述
生成一個uuid的密碼,默認用戶是user
將賬戶輸入結果:
在這裏插入圖片描述
自定義賬戶通過配置文件:
在這裏插入圖片描述
在這裏插入圖片描述
同樣能登錄成功

通過代碼設置賬戶,刪除配置文件的配置,編寫一個配置類

 @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Bean
        PasswordEncoder passwordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("yuzb")
                    .password("123").roles("admin")
                    .and().
                    withUser("yu")
                    .password("123").roles("user");
        }
}

配置了兩個角色的賬戶,一個admin一個user,多個賬戶用add拼接

自定義登錄頁面
在配置類添加

 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .permitAll()
                .and()
                .csrf().disable();
    }

web.ignoring() 用來配置忽略掉的 URL 地址,一般對於靜態文件,可以採用此操作。
在資源static目錄下新建一個登錄頁面文件Login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="/login.html" method="post">
    <div class="input">
        <label for="name">用戶名</label>
        <input type="text" name="username" id="name">
        <span class="spin"></span>
    </div>
    <div class="input">
        <label for="pass">密碼</label>
        <input type="password" name="password" id="pass">
        <span class="spin"></span>
    </div>
    <div class="button login">
        <button type="submit">
            <span>登錄</span>
            <i class="fa fa-check"></i>
        </button>
    </div>
</form>
</body>
</html>

再次訪問如下

在這裏插入圖片描述
登錄參數配置
默認登錄參數是

<div class="input">
        <label for="name">用戶名</label>
        <input type="text" name="username" id="name">
        <span class="spin"></span>
    </div>
    <div class="input">
        <label for="pass">密碼</label>
        <input type="password" name="password" id="pass">
        <span class="spin"></span>

在配置類修改

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .usernameParameter("name")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .csrf().disable();
    }

修改頁面參數

 <div class="input">
        <label for="name">用戶名</label>
        <input type="text" name="name" id="name">
        <span class="spin"></span>
    </div>
    <div class="input">
        <label for="pass">密碼</label>
        <input type="password" name="passwd" id="pass">
        <span class="spin"></span>
    </div>

登錄回調
在登錄成功之後,我們就要分情況處理了,大體上來說,無非就是分爲兩種情況:

  1. 前後端分離登錄

  2. 前後端不分登錄
    兩種情況的處理方式不一樣。先來看第二種前後端不分的登錄,前後端分離的登錄回調我。
    在 Spring Security 中,和登錄成功重定向 URL 相關的方法有兩個:

  3. defaultSuccessUrl

  4. successForwardUrl
    defaultSuccessUrl 和 successForwardUrl 只需要配置一個即可,具體配置哪個,則要看需求,兩個的區別如下:

  • defaultSuccessUrl 有一個重載的方法,我們先說一個參數的 defaultSuccessUrl 方法。如果我們在 defaultSuccessUrl 中指定登錄成功的跳轉頁面爲 /index,此時分兩種情況,如果你是直接在瀏覽器中輸入的登錄地址,登錄成功後,就直接跳轉到 /index,如果你是在瀏覽器中輸入了其他地址,例如 http://localhost:8080/hello,結果因爲沒有登錄,又重定向到登錄頁面,此時登錄成功後,就不會來到 /index ,而是來到 /hello 頁面。
  • defaultSuccessUrl 還有一個重載的方法,第二個參數如果不設置默認爲 false,也就是我們上面的的情況,如果手動設置第二個參數爲 true,則 defaultSuccessUrl 的效果和 successForwardUrl 一致。
  • successForwardUrl 表示不管你是從哪裏來的,登錄後一律跳轉到 successForwardUrl 指定的地址。例如 successForwardUrl 指定的地址爲 /index ,你在瀏覽器地址欄輸入 http://localhost:8080/hello,結果因爲沒有登錄,重定向到登錄頁面,當你登錄成功之後,就會服務端跳轉到 /index 頁面;或者你直接就在瀏覽器輸入了登錄頁面地址,登錄成功後也是來到 /index。
 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .usernameParameter("name")
                .passwordParameter("passwd")
                .defaultSuccessUrl("/index")
//                .successForwardUrl("/index")
                .permitAll()
                .and()
                .csrf().disable();
    }

登錄失敗回調
與登錄成功相似,登錄失敗也是有兩個方法:

  • failureForwardUrl
  • failureUrl
    這兩個方法在設置的時候也是設置一個即可。failureForwardUrl 是登錄失敗之後會發生服務端跳轉,failureUrl 則在登錄失敗之後,會發生重定向。

註銷登錄
註銷登錄的默認接口是 /logout

.and()
.logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))
.logoutSuccessUrl("/index")
.deleteCookies()
.clearAuthentication(true)
.invalidateHttpSession(true)
.permitAll()
.and()
  • 默認註銷的 URL 是 /logout,是一個 GET 請求,可以通過 logoutUrl 方法來修改默認的註銷 URL。
  • logoutRequestMatcher 方法不僅可以修改註銷 URL,還可以修改請求方式,實際項目中,這個方法和 logoutUrl 任意設置一個即可。
  • logoutSuccessUrl 表示註銷成功後要跳轉的頁面。
  • deleteCookies 用來清除 cookie。
  • clearAuthentication 和 invalidateHttpSession 分別表示清除認證信息和使 HttpSession 失效,默認可以不用配置,默認就會清除。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章