Basic Authenrication是 HTTP 用户代理提供用户名的一种方法 ,它是对 Web 资源实施访问控制的最简单技术,它不需要 Cookie、会话标识符和登录页面。HTTP Basic身份验证使用静态的标准HTTP标头,这意味着 不必在预期中进行握手。
当用户代理想要发送服务器身份验证凭据时,它可能使用授权标头。授权标头构造规则如下:
例如,如果用户代理使用“阿拉丁”作为用户名,使用“芝麻开门”作为密码,则标头的形成如下:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
下面,我们编写一个接口,和请求该接口的客户端代码
接口:
- package com.java2novice.restful;
-
- import java.io.IOException;
-
- import javax.ws.rs.GET;
- import javax.ws.rs.HeaderParam;
- import javax.ws.rs.Path;
- import javax.ws.rs.PathParam;
- import javax.ws.rs.Produces;
- import javax.ws.rs.core.MediaType;
- import sun.misc.BASE64Decoder;
-
- import com.java2novice.model.Order;
-
- @Path("/order-inventory")
- public class OrderInventoryService {
-
- @GET
- @Path("/order/{orderId}")
- @Produces(MediaType.APPLICATION_JSON)
- public Object getUserById(@PathParam("orderId") Integer orderId,
- @HeaderParam("authorization") String authString){
-
- if(!isUserAuthenticated(authString)){
- return "{\"error\":\"User not authenticated\"}";
- }
- Order ord = new Order();
- ord.setCustmer("Java2Novice");
- ord.setAddress("Bangalore");
- ord.setAmount("$2000");
- return ord;
- }
-
- private boolean isUserAuthenticated(String authString){
-
- String decodedAuth = "";
- // 标头格式为“Basic 5tyc0uiDat4”
- // 我们需要在将数据解码回原始字符串之前提取数据
- String[] authParts = authString.split("\\s+");
- String authInfo = authParts[1];
- // 将数据解码回原始字符串
- byte[] bytes = null;
- try {
- bytes = new BASE64Decoder().decodeBuffer(authInfo);
- } catch (IOException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- }
- decodedAuth = new String(bytes);
- System.out.println(decodedAuth);
-
-
- /**
- * 此处包含验证用户身份验证的逻辑。
- * 它可以使用 ldap,或令牌交换机制或您的
- * 自定义身份验证机制。
- */
- // 你的验证码放在这里......
-
- return true;
- }
- }
客户端代码:
- package com.java2novice.rest.client;
-
- import sun.misc.BASE64Encoder;
-
- import com.sun.jersey.api.client.Client;
- import com.sun.jersey.api.client.ClientResponse;
- import com.sun.jersey.api.client.WebResource;
-
- public class JersyGetClient {
-
- public static void main(String a[]){
-
- String url = "http://localhost:8080/RestfulWebServices/order-inventory/order/1016";
- String name = "java2novice";
- String password = "Simple4u!";
- String authString = name + ":" + password;
- String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
- System.out.println("Base64 encoded auth string: " + authStringEnc);
- Client restClient = Client.create();
- WebResource webResource = restClient.resource(url);
- ClientResponse resp = webResource.accept("application/json")
- .header("Authorization", "Basic " + authStringEnc)
- .get(ClientResponse.class);
- if(resp.getStatus() != 200){
- System.err.println("Unable to connect to the server");
- }
- String output = resp.getEntity(String.class);
- System.out.println("response: "+output);
- }
- }
除了Http Basic Authentication认证方法外,还有其他几种认证方式,详细请参考:
细说API – 认证、授权和凭证 - 知乎 (zhihu.com)
链接:具有 HTTP 基本身份验证的 Restful Web 服务 - Java Restful Web Services (java2novice.com)