溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

手把手帶你入門(mén) Spring Security的具體流程

發(fā)布時(shí)間:2020-10-06 15:34:14 來(lái)源:腳本之家 閱讀:172 作者:江南一點(diǎn)雨 欄目:開(kāi)發(fā)技術(shù)

Spring Security 是 Spring 家族中的一個(gè)安全管理框架,實(shí)際上,在 Spring Boot 出現(xiàn)之前,Spring Security 就已經(jīng)發(fā)展了多年了,但是使用的并不多,安全管理這個(gè)領(lǐng)域,一直是 Shiro 的天下。

相對(duì)于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比較麻煩的操作,所以,Spring Security 雖然功能比 Shiro 強(qiáng)大,但是使用反而沒(méi)有 Shiro 多(Shiro 雖然功能沒(méi)有 Spring Security 多,但是對(duì)于大部分項(xiàng)目而言,Shiro 也夠用了)。

自從有了 Spring Boot 之后,Spring Boot 對(duì)于 Spring Security 提供了 自動(dòng)化配置方案,可以零配置使用 Spring Security。

因此,一般來(lái)說(shuō),常見(jiàn)的安全管理技術(shù)棧的組合是這樣的:

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

注意,這只是一個(gè)推薦的組合而已,如果單純從技術(shù)上來(lái)說(shuō),無(wú)論怎么組合,都是可以運(yùn)行的。

我們來(lái)看下具體使用。

1.項(xiàng)目創(chuàng)建

在 Spring Boot 中使用 Spring Security 非常容易,引入依賴(lài)即可:

手把手帶你入門(mén) Spring Security的具體流程

pom.xml 中的 Spring Security 依賴(lài):

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
</dependency>

只要加入依賴(lài),項(xiàng)目的所有接口都會(huì)被自動(dòng)保護(hù)起來(lái)。

2.初次體驗(yàn)

我們創(chuàng)建一個(gè) HelloController:

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

訪問(wèn) /hello ,需要登錄之后才能訪問(wèn)。

手把手帶你入門(mén) Spring Security的具體流程

當(dāng)用戶(hù)從瀏覽器發(fā)送請(qǐng)求訪問(wèn) /hello 接口時(shí),服務(wù)端會(huì)返回 302 響應(yīng)碼,讓客戶(hù)端重定向到 /login 頁(yè)面,用戶(hù)在 /login 頁(yè)面登錄,登陸成功之后,就會(huì)自動(dòng)跳轉(zhuǎn)到 /hello 接口。

另外,也可以使用 POSTMAN 來(lái)發(fā)送請(qǐng)求,使用 POSTMAN 發(fā)送請(qǐng)求時(shí),可以將用戶(hù)信息放在請(qǐng)求頭中(這樣可以避免重定向到登錄頁(yè)面):

手把手帶你入門(mén) Spring Security的具體流程

通過(guò)以上兩種不同的登錄方式,可以看出,Spring Security 支持兩種不同的認(rèn)證方式:

  • 可以通過(guò) form 表單來(lái)認(rèn)證
  • 可以通過(guò) HttpBasic 來(lái)認(rèn)證

3.用戶(hù)名配置

默認(rèn)情況下,登錄的用戶(hù)名是 user ,密碼則是項(xiàng)目啟動(dòng)時(shí)隨機(jī)生成的字符串,可以從啟動(dòng)的控制臺(tái)日志中看到默認(rèn)密碼:

手把手帶你入門(mén) Spring Security的具體流程

這個(gè)隨機(jī)生成的密碼,每次啟動(dòng)時(shí)都會(huì)變。對(duì)登錄的用戶(hù)名/密碼進(jìn)行配置,有三種不同的方式:

  • 在 application.properties 中進(jìn)行配置
  • 通過(guò) Java 代碼配置在內(nèi)存中
  • 通過(guò) Java 從數(shù)據(jù)庫(kù)中加載

前兩種比較簡(jiǎn)單,第三種代碼量略大,本文就先來(lái)看看前兩種,第三種后面再單獨(dú)寫(xiě)文章介紹,也可以參考我的微人事項(xiàng)目。

3.1 配置文件配置用戶(hù)名/密碼

可以直接在 application.properties 文件中配置用戶(hù)的基本信息:

spring.security.user.name=javaboy
spring.security.user.password=123

配置完成后,重啟項(xiàng)目,就可以使用這里配置的用戶(hù)名/密碼登錄了。

3.2 Java 配置用戶(hù)名/密碼

也可以在 Java 代碼中配置用戶(hù)名密碼,首先需要我們創(chuàng)建一個(gè) Spring Security 的配置類(lèi),集成自 WebSecurityConfigurerAdapter 類(lèi),如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  //下面這兩行配置表示在內(nèi)存中配置了兩個(gè)用戶(hù)
  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();
 }
}

這里我們?cè)?configure 方法中配置了兩個(gè)用戶(hù),用戶(hù)的密碼都是加密之后的字符串(明文是 123),從 Spring5 開(kāi)始,強(qiáng)制要求密碼要加密,如果非不想加密,可以使用一個(gè)過(guò)期的 PasswordEncoder 的實(shí)例 NoOpPasswordEncoder,但是不建議這么做,畢竟不安全。

Spring Security 中提供了 BCryptPasswordEncoder 密碼編碼工具,可以非常方便的實(shí)現(xiàn)密碼的加密加鹽,相同明文加密出來(lái)的結(jié)果總是不同,這樣就不需要用戶(hù)去額外保存的字段了,這一點(diǎn)比 Shiro 要方便很多。

4.登錄配置

對(duì)于登錄接口,登錄成功后的響應(yīng),登錄失敗后的響應(yīng),我們都可以在 WebSecurityConfigurerAdapter 的實(shí)現(xiàn)類(lèi)中進(jìn)行配置。例如下面這樣:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 @Autowired
 VerifyCodeFilter verifyCodeFilter;
 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
  http
  .authorizeRequests()//開(kāi)啟登錄配置
  .antMatchers("/hello").hasRole("admin")//表示訪問(wèn) /hello 這個(gè)接口,需要具備 admin 這個(gè)角色
  .anyRequest().authenticated()//表示剩余的其他接口,登錄之后就能訪問(wèn)
  .and()
  .formLogin()
  //定義登錄頁(yè)面,未登錄時(shí),訪問(wèn)一個(gè)需要登錄之后才能訪問(wèn)的接口,會(huì)自動(dòng)跳轉(zhuǎn)到該頁(yè)面
  .loginPage("/login_p")
  //登錄處理接口
  .loginProcessingUrl("/doLogin")
  //定義登錄時(shí),用戶(hù)名的 key,默認(rèn)為 username
  .usernameParameter("uname")
  //定義登錄時(shí),用戶(hù)密碼的 key,默認(rèn)為 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()//和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過(guò)
   .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 方法中,配置登錄成功的回調(diào),如果是前后端分離開(kāi)發(fā)的話(huà),登錄成功后返回 JSON 即可,同理,failureHandler 方法中配置登錄失敗的回調(diào),logoutSuccessHandler 中則配置注銷(xiāo)成功的回調(diào)。

5.忽略攔截

如果某一個(gè)請(qǐng)求地址不需要攔截的話(huà),有兩種方式實(shí)現(xiàn):

  • 設(shè)置該地址匿名訪問(wèn)
  • 直接過(guò)濾掉該地址,即該地址不走 Spring Security 過(guò)濾器鏈

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

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

Spring Security 另外一個(gè)強(qiáng)大之處就是它可以結(jié)合 OAuth3 ,玩出更多的花樣出來(lái),這些我們?cè)诤竺娴奈恼轮性俸痛蠹壹?xì)細(xì)介紹。

到此這篇關(guān)于手把手帶你入門(mén) Spring Security的文章就介紹到這了,更多相關(guān)入門(mén) Spring Security內(nèi)容請(qǐng)搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI