springboot-springSecurity 之 http Basic认证 (四)
生活随笔
收集整理的這篇文章主要介紹了
springboot-springSecurity 之 http Basic认证 (四)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
引言:
HTTP基礎認證(BA)是一種簡單的認證機制。當一個web客戶端需要保護任何web資源的時候,服務器會發送一個帶有401狀態碼(未授權)的HTTP回應,還有類似WWW-Authenticate: Basic realm=”realm here” 的 WWW-Authenticate HTTP頭。而瀏覽器這時候就會彈出一個登錄對話框,提示輸入用戶名和密碼。
1. 修改配置
在spring?boot項目中實現Spring Security進行http Basic認證非常簡單,只需在配置文件中增加?.httpBasic();直接配置即可使用
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UrlUserService urlUserService;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers(DATA_COLLECT_RAW_URL).permitAll().antMatchers("/login").permitAll().antMatchers("/logout").permitAll().antMatchers("/images/**").permitAll().antMatchers("/js/**").permitAll().antMatchers("/css/**").permitAll().antMatchers("/fonts/**").permitAll().antMatchers("/").permitAll().anyRequest().authenticated().and().sessionManagement().and().logout().and().httpBasic();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() {//此處為密碼使用md5 進行加密@Overridepublic String encode(CharSequence rawPassword) {return MD5Util.encode((String) rawPassword);}@Overridepublic boolean matches(CharSequence rawPassword, String encodedPassword) {return encodedPassword.equals(MD5Util.encode((String) rawPassword));}});} }- 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
- 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
2. 登錄方式的變化
http Basic 實際上就是將我門的用戶名和密碼連接起來然后 使用base64進行加密,將加密后的密文放在http 的header 中進行驗證。
帳號密碼加密如下 (假設賬號密碼都為admin)admin:admin base64 加密后為 YWRtaW46YWRtaW4= 加密后的串放入 header 時應在拼結為 Basic YWRtaW46YWRtaW4= 注意:Basic 與密碼串之間為一個空格postMan 請求如下:
3.在controller 中獲取請求參數
由于登錄是security 進行驗證的,驗證成功后會跳轉到 “/login“ api,所以我門要定義自己login api
@AuthenticationPrincipal 注解是為了從security 中獲取登錄后的user 信息。?
登錄成功后返回用戶信息。?
當登出后也會進入”/login” api ,登出成功返回null
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
關于security 的Http Basic 驗證到此就告一段落了。敬請期待。
總結
以上是生活随笔為你收集整理的springboot-springSecurity 之 http Basic认证 (四)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring security CSRF
- 下一篇: RESTful Web 服务 - 介绍