很多SaaS API项目提供了HTTP访问的基本身份验证机制。因此,本文提供了如何在JAX-RS REST客户端实现基本的访问认证。有些HTTP客户端库提供了基本身份验证过滤器,使用这些库会更简单。
简单来说,基本的身份验证机制是在服务器端实现的身份验证机制,只需要客户端提供用户名和密码即可,但是它对于HTTP报头格式有一些特殊要求,如下所示:
基本身份验证机制的HTTP Header格式
Authorization: Basic
“Authorization”是报头的名字,它的值是这样,比如”Basic YXBpOmtleS03Y2IzODY4ZWI5MmM2ZzFlZmY3NzY1YWExZDhmNmE0OQ==”。
在值中,Basic是关键字,它不能使用BASE64编码,它紧跟空格,然后才是“用户名+冒号+密码”(即用户名:密码)的BASE64编码后的字符串。
在Java 8之前,要构建基本的身份验证,可以使用javax.xml.bind.DatatypeConverter工具类。比如:
String username = "myusername";
String password = "myPassword";
String usernameAndPassword = username + ":" + password;
String authorizationHeaderName = "Authorization";
String authorizationHeaderValue = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary( usernameAndPassword.getBytes() );
Java 8要构建基本的身份验证,可以使用java.util.Base64工具类。比如:
String username = "myusername";
String password = "myPassword";
String usernameAndPassword = username + ":" + password;
String authorizationHeaderName = "Authorization";
String authorizationHeaderValue = "Basic " + java.util.Base64.getEncoder().encodeToString( usernameAndPassword.getBytes() );
要使用JAX-RS REST客户端库构建的身份验证,可以这样:
import static org.junit.Assert.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.junit.Test;
public class BasicAuthenticationTest {
@Test
public void testBasicAuthentication() {
//Define basic authentication credential values
String username = "myusername";
String password = "myPassword";
String usernameAndPassword = username + ":" + password;
String authorizationHeaderName = "Authorization";
String authorizationHeaderValue = "Basic " + java.util.Base64.getEncoder().encodeToString( usernameAndPassword.getBytes() );
// Build the form for a post request
MultivaluedMap< String, String> formParameters = new MultivaluedHashMap();
formParameters.add( "field1", "fieldValue1" );
formParameters.add( "field2", "fieldValue2" );
// Perform a post request
String restResource = "https://restserver:8080/app-name/rest-api/";
Client client = ClientBuilder.newClient();
Response res = client.target( restResource )
.path( "login" ) // API Module Path
.request( "application/json" ) // Expected response mime type
.header( authorizationHeaderName, authorizationHeaderValue ) // The basic authentication header goes here
.post( Entity.form( formParameters ) ); // Perform a post with the form values
assertTrue( res.getStatus() == 200 );
}
}
版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/chszs/article/details/46725551