手把手帶你入門 Spring Security!

Spring Security 是 Spring 家族中的一個安全管理框架,實際上,在 Spring Boot 出現以前,Spring Security 就已經發展了多年了,可是使用的並很少,安全管理這個領域,一直是 Shiro 的天下。java

相對於 Shiro,在 SSM/SSH 中整合 Spring Security 都是比較麻煩的操做,因此,Spring Security 雖然功能比 Shiro 強大,可是使用反而沒有 Shiro 多(Shiro 雖然功能沒有 Spring Security 多,可是對於大部分項目而言,Shiro 也夠用了)。web

自從有了 Spring Boot 以後,Spring Boot 對於 Spring Security 提供了 自動化配置方案,能夠零配置使用 Spring Security。spring

所以,通常來講,常見的安全管理技術棧的組合是這樣的:數據庫

  • SSM + Shiro
  • Spring Boot/Spring Cloud + Spring Security

注意,這只是一個推薦的組合而已,若是單純從技術上來講,不管怎麼組合,都是能夠運行的。json

咱們來看下具體使用。後端

1.項目建立

在 Spring Boot 中使用 Spring Security 很是容易,引入依賴便可:瀏覽器

pom.xml 中的 Spring Security 依賴:安全

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
複製代碼

只要加入依賴,項目的全部接口都會被自動保護起來。app

2.初次體驗

咱們建立一個 HelloController:框架

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}
複製代碼

訪問 /hello ,須要登陸以後才能訪問。

當用戶從瀏覽器發送請求訪問 /hello 接口時,服務端會返回 302 響應碼,讓客戶端重定向到 /login 頁面,用戶在 /login 頁面登陸,登錄成功以後,就會自動跳轉到 /hello 接口。

另外,也可使用 POSTMAN 來發送請求,使用 POSTMAN 發送請求時,能夠將用戶信息放在請求頭中(這樣能夠避免重定向到登陸頁面):

經過以上兩種不一樣的登陸方式,能夠看出,Spring Security 支持兩種不一樣的認證方式:

  • 能夠經過 form 表單來認證
  • 能夠經過 HttpBasic 來認證

3.用戶名配置

默認狀況下,登陸的用戶名是 user ,密碼則是項目啓動時隨機生成的字符串,能夠從啓動的控制檯日誌中看到默認密碼:

這個隨機生成的密碼,每次啓動時都會變。對登陸的用戶名/密碼進行配置,有三種不一樣的方式:

  • 在 application.properties 中進行配置
  • 經過 Java 代碼配置在內存中
  • 經過 Java 從數據庫中加載

前兩種比較簡單,第三種代碼量略大,本文就先來看看前兩種,第三種後面再單獨寫文章介紹,也能夠參考個人微人事項目

3.1 配置文件配置用戶名/密碼

能夠直接在 application.properties 文件中配置用戶的基本信息:

spring.security.user.name=javaboy
spring.security.user.password=123
複製代碼

配置完成後,重啓項目,就可使用這裏配置的用戶名/密碼登陸了。

3.2 Java 配置用戶名/密碼

也能夠在 Java 代碼中配置用戶名密碼,首先須要咱們建立一個 Spring Security 的配置類,集成自 WebSecurityConfigurerAdapter 類,以下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //下面這兩行配置表示在內存中配置了兩個用戶
        auth.inMemoryAuthentication()
                .withUser("javaboy").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")
                .and()
                .withUser("lisi").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");
    }
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
複製代碼

這裏咱們在 configure 方法中配置了兩個用戶,用戶的密碼都是加密以後的字符串(明文是 123),從 Spring5 開始,強制要求密碼要加密,若是非不想加密,可使用一個過時的 PasswordEncoder 的實例 NoOpPasswordEncoder,可是不建議這麼作,畢竟不安全。

Spring Security 中提供了 BCryptPasswordEncoder 密碼編碼工具,能夠很是方便的實現密碼的加密加鹽,相同明文加密出來的結果老是不一樣,這樣就不須要用戶去額外保存的字段了,這一點比 Shiro 要方便不少。

4.登陸配置

對於登陸接口,登陸成功後的響應,登陸失敗後的響應,咱們均可以在 WebSecurityConfigurerAdapter 的實現類中進行配置。例以下面這樣:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    VerifyCodeFilter verifyCodeFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http
        .authorizeRequests()//開啓登陸配置
        .antMatchers("/hello").hasRole("admin")//表示訪問 /hello 這個接口,須要具有 admin 這個角色
        .anyRequest().authenticated()//表示剩餘的其餘接口,登陸以後就能訪問
        .and()
        .formLogin()
        //定義登陸頁面,未登陸時,訪問一個須要登陸以後才能訪問的接口,會自動跳轉到該頁面
        .loginPage("/login_p")
        //登陸處理接口
        .loginProcessingUrl("/doLogin")
        //定義登陸時,用戶名的 key,默認爲 username
        .usernameParameter("uname")
        //定義登陸時,用戶密碼的 key,默認爲 password
        .passwordParameter("passwd")
        //登陸成功的處理器
        .successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("success");
                    out.flush();
                }
            })
            .failureHandler(new AuthenticationFailureHandler() {
                @Override
                public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("fail");
                    out.flush();
                }
            })
            .permitAll()//和表單登陸相關的接口通通都直接經過
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("logout success");
                    out.flush();
                }
            })
            .permitAll()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }
}
複製代碼

咱們能夠在 successHandler 方法中,配置登陸成功的回調,若是是先後端分離開發的話,登陸成功後返回 JSON 便可,同理,failureHandler 方法中配置登陸失敗的回調,logoutSuccessHandler 中則配置註銷成功的回調。

5.忽略攔截

若是某一個請求地址不須要攔截的話,有兩種方式實現:

  • 設置該地址匿名訪問
  • 直接過濾掉該地址,即該地址不走 Spring Security 過濾器鏈

推薦使用第二種方案,配置以下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vercode");
    }
}
複製代碼

Spring Security 另一個強大之處就是它能夠結合 OAuth2 ,玩出更多的花樣出來,這些咱們在後面的文章中再和你們細細介紹。

本文就先說到這裏,有問題歡迎留言討論。

關注公衆號【江南一點雨】,專一於 Spring Boot+微服務以及先後端分離等全棧技術,按期視頻教程分享,關注後回覆 Java ,領取鬆哥爲你精心準備的 Java 乾貨!

相關文章
相關標籤/搜索