HTTP 提供一个用于权限控制和认证的通用框架。最经常使用的 HTTP 认证方案是 HTTP Basic authentication。Http Basic 认证是一种用来容许网页浏览器或其余客户端程序在请求时提供用户名和口令形式的身份凭证的一种登陆验证方式。java
上面是Http Basic
的简介,它不是咱们今天的主题,咱们今天的主题是:HttpClient
三种 Http Basic Authentication
认证方式,是哪三种认证方式呢?接下来咱们去一探究竟,咱们从模拟 Http Basic 服务端开始。git
咱们使用 SpringBoot和Spring Security 简单的搭建一个具备 HTTP Basic Authentication 的服务。具体的搭建过程我就不陈述了,我在这里先贴出关键代码,便于你的理解,完整的代码已经上传到GitHub
上面,文章末尾有连接。程序员
@Component public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter printWriter = new PrintWriter(response.getOutputStream()); printWriter.write("Http Status 401: " + authException.getLocalizedMessage()); } @Override public void afterPropertiesSet() throws Exception { setRealmName("developlee"); super.afterPropertiesSet(); } }
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() // 开启httpBasic .httpBasic() // 设置 BasicAuthenticationFilter .authenticationEntryPoint(authenticationEntryPoint); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("jamal").password(passwordEncoder().encode("123456")).authorities("ROLE_USER"); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
@RestController public class WebController { @RequestMapping(path = "/hello") public String hello(){ return "验证经过"; } }
启动项目,访问 http://127.0.0.1:8080/hellogithub
至此,咱们的 Http Basic 服务端搭建便已经完成了spring
private String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://127.0.0.1:8080/hello"; private String DEFAULT_USER = "jamal"; private String DEFAULT_PASS = "123456"; @Test public void CredentialsProvider()throws Exception{ // 建立用户信息 CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); provider.setCredentials(AuthScope.ANY, credentials); // 建立客户端的时候进行身份验证 HttpClient client = HttpClientBuilder.create() .setDefaultCredentialsProvider(provider) .build(); HttpResponse response = client.execute( new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); int statusCode = response.getStatusLine() .getStatusCode(); Assert.assertEquals(statusCode,200); }
@Test public void PreemptiveBasicAuthentication()throws Exception{ // 先进行身份验证 HttpHost targetHost = new HttpHost("localhost", 8080, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); AuthCache authCache = new BasicAuthCache(); // 将身份验证放入缓存中 authCache.put(targetHost, new BasicScheme()); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute( new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(statusCode,200); }
@Test public void HttpBasicAuth()throws Exception{ HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); // 手动构建验证信息 String auth = DEFAULT_USER + ":" + DEFAULT_PASS; byte[] encodedAuth = Base64.encodeBase64( auth.getBytes(StandardCharsets.UTF_8)); String authHeader = "Basic " + new String(encodedAuth); // 将验证信息放入到 Header request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(statusCode,200); }
以上就是 HttpClient Http Basic 的三种验证方式,但愿对你有所帮助。浏览器
文章不足之处,望你们多多指点,共同窗习,共同进步
打个小广告,欢迎扫码关注微信公众号:「平头哥的技术博文」,一块儿进步吧。缓存