基于Http Basic Authentication的接口

Basic Authenrication是 HTTP 用户代理提供用户名的一种方法 ,它是对 Web 资源实施访问控制的最简单技术,它不需要 Cookie、会话标识符和登录页面。HTTP Basic身份验证使用静态的标准HTTP标头,这意味着 不必在预期中进行握手。

当用户代理想要发送服务器身份验证凭据时,它可能使用授权标头。授权标头构造规则如下:

  • 用户名和密码组合成一个字符串“用户名:密码”
  • 使用Base64编码对生成的字符串进行编码
  • 将授权方法和空格(即“基本”)放在编码字符串之前。

例如,如果用户代理使用“阿拉丁”作为用户名,使用“芝麻开门”作为密码,则标头的形成如下:

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)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值