Http Basic 簡介
HTTP 提供一個用於權限控制和認證的通用框架。最常用的 HTTP 認證方案是 HTTP Basic authentication。Http Basic 認證是一種用來允許網頁瀏覽器或其他客戶端程序在請求時提供用戶名和口令形式的身份憑證的一種登錄驗證方式。
優點
基本認證的一個優點是基本上所有流行的網頁瀏覽器都支持基本認證。基本認證很少在可公開訪問的互聯網網站上使用,有時候會在小的私有系統中使用(如路由器網頁管理接口)。后來的機制HTTP摘要認證是為替代基本認證而開發的,允許密鑰以相對安全的方式在不安全的通道上傳輸。
程序員和系統管理員有時會在可信網絡環境中使用基本認證,使用Telnet或其他明文網絡協議工具手動地測試Web服務器。這是一個麻煩的過程,但是網絡上傳輸的內容是人可讀的,以便進行診斷。
缺點
雖然基本認證非常容易實現,但該方案創建在以下的假設的基礎上,即:客戶端和服務器主機之間的連接是安全可信的。特別是,如果沒有使用SSL/TLS這樣的傳輸層安全的協議,那么以明文傳輸的密鑰和口令很容易被攔截。該方案也同樣沒有對服務器返回的信息提供保護。
現存的瀏覽器保存認證信息直到標簽頁或瀏覽器被關閉,或者用戶清除歷史記錄。HTTP沒有為服務器提供一種方法指示客戶端丟棄這些被緩存的密鑰。這意味着服務器端在用戶不關閉瀏覽器的情況下,並沒有一種有效的方法來讓用戶注銷
上面是Http Basic的簡介,它不是我們今天的主題,我們今天的主題是:HttpClient 三種 Http Basic Authentication認證方式,是哪三種認證方式呢?接下來我們去一探究竟,我們從模擬 Http Basic 服務端開始。
Http Basic 服務端
我們使用 SpringBoot和Spring Security 簡單的搭建一個具有 HTTP Basic Authentication 的服務。具體的搭建過程我就不陳述了,我在這里先貼出關鍵代碼,便於你的理解,完整的代碼已經上傳到GitHub上面,文章末尾有鏈接。
配置 BasicAuthenticationEntryPoint
1 @Component 2 public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { 3 @Override 4 public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { 5 response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName()); 6 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 7 PrintWriter printWriter = new PrintWriter(response.getOutputStream()); 8 printWriter.write("Http Status 401: " + authException.getLocalizedMessage()); 9 } 10 11 @Override 12 public void afterPropertiesSet() throws Exception { 13 setRealmName("developlee"); 14 super.afterPropertiesSet(); 15 } 16 }
配置 WebSecurityConfigurer
1 @Configuration 2 @EnableWebSecurity 3 public class SecurityConfig extends WebSecurityConfigurerAdapter { 4 @Autowired 5 private MyBasicAuthenticationEntryPoint authenticationEntryPoint; 6 7 @Override 8 protected void configure(HttpSecurity http) throws Exception { 9 http.authorizeRequests() 10 .antMatchers("/login").permitAll() 11 .anyRequest().authenticated() 12 .and() 13 // 開啟httpBasic 14 .httpBasic() 15 // 設置 BasicAuthenticationFilter 16 .authenticationEntryPoint(authenticationEntryPoint); 17 } 18 19 @Override 20 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 21 auth.inMemoryAuthentication().withUser("jamal").password(passwordEncoder().encode("123456")).authorities("ROLE_USER"); 22 } 23 24 @Bean 25 protected PasswordEncoder passwordEncoder() { 26 return new BCryptPasswordEncoder(); 27 } 28 }
編寫 Controller
1 @RestController 2 public class WebController { 3 4 @RequestMapping(path = "/hello") 5 public String hello(){ 6 return "驗證通過"; 7 } 8 }
啟動項目,訪問 http://127.0.0.1:8080/hello
至此,我們的 Http Basic 服務端搭建便已經完成了
HttpClient 三種 Http Basic 驗證方式
標准模式
1 private String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://127.0.0.1:8080/hello"; 2 3 private String DEFAULT_USER = "jamal"; 4 5 private String DEFAULT_PASS = "123456"; 6 7 @Test 8 public void CredentialsProvider()throws Exception{ 9 // 創建用戶信息 10 CredentialsProvider provider = new BasicCredentialsProvider(); 11 UsernamePasswordCredentials credentials 12 = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); 13 provider.setCredentials(AuthScope.ANY, credentials); 14 15 // 創建客戶端的時候進行身份驗證 16 HttpClient client = HttpClientBuilder.create() 17 .setDefaultCredentialsProvider(provider) 18 .build(); 19 20 HttpResponse response = client.execute( 21 new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); 22 int statusCode = response.getStatusLine() 23 .getStatusCode(); 24 Assert.assertEquals(statusCode,200); 25 }
搶先模式
1 @Test 2 public void PreemptiveBasicAuthentication()throws Exception{ 3 // 先進行身份驗證 4 HttpHost targetHost = new HttpHost("localhost", 8080, "http"); 5 CredentialsProvider credsProvider = new BasicCredentialsProvider(); 6 credsProvider.setCredentials(AuthScope.ANY, 7 new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); 8 9 AuthCache authCache = new BasicAuthCache(); 10 // 將身份驗證放入緩存中 11 authCache.put(targetHost, new BasicScheme()); 12 13 HttpClientContext context = HttpClientContext.create(); 14 context.setCredentialsProvider(credsProvider); 15 context.setAuthCache(authCache); 16 HttpClient client = HttpClientBuilder.create().build(); 17 HttpResponse response = client.execute( 18 new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context); 19 20 int statusCode = response.getStatusLine().getStatusCode(); 21 Assert.assertEquals(statusCode,200); 22 }
原生 Http Basic 模式
1 @Test 2 public void HttpBasicAuth()throws Exception{ 3 HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); 4 // 手動構建驗證信息 5 String auth = DEFAULT_USER + ":" + DEFAULT_PASS; 6 byte[] encodedAuth = Base64.encodeBase64( 7 auth.getBytes(StandardCharsets.UTF_8)); 8 String authHeader = "Basic " + new String(encodedAuth); 9 // 將驗證信息放入到 Header 10 request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); 11 12 HttpClient client = HttpClientBuilder.create().build(); 13 HttpResponse response = client.execute(request); 14 15 int statusCode = response.getStatusLine().getStatusCode(); 16 Assert.assertEquals(statusCode,200); 17 }
以上就是 HttpClient Http Basic 的三種驗證方式,希望對你有所幫助。
源碼:https://github.com/BinaryBall/spring-boot-learn/tree/master/httpclient-auth
————————————————
版權聲明:本文為CSDN博主「平頭哥的技術博文」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/z694644032/article/details/100532526