1. 程式人生 > >springSecurity之http Basic認證

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 {

    @Autowired
    private UrlUserService urlUserService;

    @Override
    protected 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();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

 auth.userDetailsService(urlUserService).passwordEncoder(new PasswordEncoder() {//此處為密碼使用md5 進行加密

            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String) rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(MD5Util.encode((String) rawPassword));
            }
        });
    }
}

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
 

@RequestMapping(value = "/login")
    @ResponseBody
    //使用者名稱密碼是用base64 加密 原文為 admin:admin 即 使用者名稱:密碼  內容是放在request.getHeader 的 "authorization" 中
    public Object login(@AuthenticationPrincipal User loginedUser, @RequestParam(name = "logout", required = false) String logout) {
        if (logout != null) {
            return null;
        }
        if (loginedUser != null) {
            return loginedUser;
        }
        return null;
    }