【转】HttpClient 三种 Http Basic Authentication 认证方式

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

 

posted @ 2019-12-26 17:12  将来的老大爷  阅读(1273)  评论(0编辑  收藏  举报

如果本页面列出的内容侵犯了您的权益,请告知。
知识共享许可协议
996.icu