Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java OAuth 401未经授权_Java_Rest_Oauth - Fatal编程技术网

Java OAuth 401未经授权

Java OAuth 401未经授权,java,rest,oauth,Java,Rest,Oauth,所以我还在学习,但是我从下面的代码中得到了一个未经授权的错误401。我知道OAuth头的工作原理与postman中的工作原理相同,所以我假设POST请求/Auth头有问题?有什么想法吗 //set timestamp Long timestamp = System.currentTimeMillis()/1000; //set nonce ***** call from main system****************************

所以我还在学习,但是我从下面的代码中得到了一个未经授权的错误401。我知道OAuth头的工作原理与postman中的工作原理相同,所以我假设POST请求/Auth头有问题?有什么想法吗

//set timestamp
            Long timestamp = System.currentTimeMillis()/1000;
            //set nonce ***** call from main system*************************************************************
            String aString = randomAlphaNumeric(11);
            // other stuff
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
            HttpHeaders headers = new HttpHeaders();
            String url = "aURL";
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
           // String auth = Base64.getEncoder().encodeToString(credentials.getBytes());
            List<NameValuePair> oauthHeaders = new ArrayList<>(9);
            oauthHeaders.add(new BasicNameValuePair("oauth_consumer_key", "aKey"));
            oauthHeaders.add(new BasicNameValuePair("oauth_nonce", aString));
            oauthHeaders.add(new BasicNameValuePair("oauth_timestamp", String.valueOf(timestamp)));
            oauthHeaders.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
            oauthHeaders.add(new BasicNameValuePair("oauth_version", "1.0"));
            //generate signature
            //encode
            String encodedURL = encode(oauthHeaders.toString());
            System.out.println("encoded URL:" +encodedURL);
            //form base string
            String baseString = "POST&"+encode(url).toString()+encodedURL;
            System.out.println("Base String:  "+baseString);
            //form signature
            byte[] byteHMAC = null;
            try {

                Mac mac = Mac.getInstance("HmacSHA1");
                SecretKeySpec spec;
                if (null == secretKey) {
                    String signingKey = encode(secretKey) + '&';
                    spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
                } else {
                    String signingKey = encode(secretKey) + '&' + encode(secretKey);
                    spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
                }
                mac.init(spec);
                byteHMAC = mac.doFinal(baseString.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            String signature = new BASE64Encoder().encode(byteHMAC);
            System.out.println("oauth signature:    "+signature);


            //set signature to params
            oauthHeaders.add(new BasicNameValuePair("oauth_signature", signature));
            String test = "OAuth "+oauthHeaders.toString();
            headers.set("Authorization", test);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("Name",name.toString());
            map.add("Region",region.toString());


            HttpEntity<MultiValueMap<String, String>> requestEntity= new HttpEntity<MultiValueMap<String, String>>(headers, map);
            System.out.println(requestEntity);
            ResponseEntity<String> response= restTemplate.exchange(url ,HttpMethod.POST, requestEntity, String.class);
            System.out.println(response.toString());
            HttpStatus status = response.getStatusCode();
            status.toString();
            if(status.equals("200")){
                Notification.show("Employer" + name +" added successfully");
            }
            else{
                Notification.show("Unsuccessful, error: "+status);
            }


        }
//设置时间戳
长时间戳=System.currentTimeMillis()/1000;
//从主系统设置nonce****调用*************************************************************
字符串aString=随机字母数字(11);
//其他东西
RestTemplate RestTemplate=新RestTemplate();
restemplate.getMessageConverters().add(新的StringHttpMessageConverter());
HttpHeaders=新的HttpHeaders();
字符串url=“aURL”;
headers.setContentType(MediaType.APPLICATION\u FORM\u URLENCODED);
//字符串auth=Base64.getEncoder().encodeToString(credentials.getBytes());
List oauthHeaders=新的ArrayList(9);
添加(新的BasicNameValuePair(“oauth_consumer_key”,“aKey”);
添加(新的BasicNameValuePair(“oauth_nonce”,aString));
添加(新的BasicNameValuePair(“oauth_timestamp”,String.valueOf(timestamp));
添加(新的BasicNameValuePair(“oauth_签名_方法”、“HMAC-SHA1”);
添加(新的BasicNameValuePair(“oauth_版本”,“1.0”);
//生成签名
//编码
字符串encodedURL=encode(oauthHeaders.toString());
System.out.println(“编码URL:+encodedURL”);
//表单基字符串
String baseString=“POST&”+encode(url).toString()+encodedURL;
System.out.println(“基字符串:“+baseString”);
//格式签名
byte[]byteHMAC=null;
试一试{
Mac Mac=Mac.getInstance(“HmacSHA1”);
秘密密钥规范;
if(null==secretKey){
字符串签名键=编码(secretKey)+'&';
spec=new SecretKeySpec(signingKey.getBytes(),“HmacSHA1”);
}否则{
字符串签名键=encode(secretKey)+'&'+encode(secretKey);
spec=new SecretKeySpec(signingKey.getBytes(),“HmacSHA1”);
}
mac.init(spec);
byteHMAC=mac.doFinal(baseString.getBytes());
}捕获(例外e){
e、 printStackTrace();
}
字符串签名=新BASE64Encoder().encode(byteHMAC);
System.out.println(“oauth签名:”+签名);
//将签名设置为params
添加(新的BasicNameValuePair(“oauth_签名”,signature));
String test=“OAuth”+oauthHeaders.toString();
标题。设置(“授权”,测试);
MultiValueMap=新链接的MultiValueMap();
add(“Name”,Name.toString());
add(“Region”,Region.toString());
HttpEntity requestEntity=新的HttpEntity(头,映射);
System.out.println(请求实体);
ResponseEntity response=restemplate.exchange(url,HttpMethod.POST,requestEntity,String.class);
System.out.println(response.toString());
HttpStatus status=response.getStatusCode();
status.toString();
如果(状态等于(“200”)){
通知。显示(“业主”+名称+“添加成功”);
}
否则{
通知。显示(“未成功,错误:+状态”);
}
}
出于明显的原因删除了URL和使用者密钥/签名

以下系统输出也可能有所帮助:

编码参数: %5 OAuth_使用者_密钥%3密钥%2C%20oauth_当前值%3DWZU8H1B5JA6%2C%20oauth_时间戳%3D1511621759%2C%20oauth_签名方法%3DHMAC-SHA1%2C%20oauth_版本%3D1.0%5D

基本字符串:POST&https%3A%2F%2Fapi.test.payrun.io%2fellower%5oauth_consumer_key%3aKey%2C%20oauth_nonce%3DWZU8H1B5JA6%2C%20oauth_时间戳%3D1511621759%2C%20oauth_签名方法%3DHMAC-SHA1%2C%20oauth_版本%3D1.0%5D


oauth签名:dlrjgszgritzz+LzMbgnIfbOqU=

oauth_签名的值是错误的。您正在使用
asignature
作为
oauth\u签名
的值,但您必须为您的请求计算正确的值,并将其设置为
oauth\u签名
。如果
oauth_签名
的值错误,服务器将拒绝您的请求。有关详细信息,请参见(OAuth 1.0协议)中的“”。

对于希望实现此功能的任何人,请参见下面完整的OAuth生成器示例:):

公共类oAuthGenerator{
私有字符串httpMethod;
私有字符串参数;
私有字符串url;
//百分比编码所需
私有静态最终字符串ENC=“ASCII”;
//暂时需要
私有静态最终字符串ALPHA_NUMERIC_String=“abcdefghijklmnopqrstuvxyz123456789abcdefghijklmnopqrstuvxyz”;
//由Payrun.io提供
私有静态最终字符串secretKey=“aSecretKey”;
//由Payrun.io提供
私有静态最终字符串consumerKey=“aConsumerKey”;
私有列表验证列表;
//用于设置签名基字符串值的构造函数。
//@参数url需要进行百分比编码
//@Param params需要进行百分比编码,这是在@Method generateOAuth()完成的
公共oAuthGenerator(字符串httpMethod,字符串url)引发异常{
veriList=newarraylist();
veriList.add(“POST”);
veriList.add(“GET”);
veriList.add(“PUT”);
添加(“删除”);
if(veriList.contains(httpMethod)){
this.httpMethod=httpMethod+“&”;}
this.url=URLEncoder.encode(url,ENC)+“和”;
}
//用于生成OAuth授权标头的方法
//@方法randomAlphaNumeric()使用实例v调用内部方法
public class oAuthGenerator {
private String httpMethod;
    private String params;
    private String url;
    //Required for percent encoding
    private static final String ENC = "ASCII";
    //Required for nonce
    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    //As provided by Payrun.io
    private static final String secretKey = "aSecretKey";
    //As provided by Payrun.io
    private static final String consumerKey ="aConsumerKey";
    private List veriList;

    //Constructor for setting signature base string values.
    //@Param url needs to be percent encoded
    //@Param params needs to be percent encoded, this is done @Method generateOAuth()
    public oAuthGenerator(String httpMethod,String url )throws Exception {
        veriList= new ArrayList<String>();
        veriList.add("POST");
        veriList.add("GET");
        veriList.add("PUT");
        veriList.add("DELETE");

        if (veriList.contains(httpMethod)){
        this.httpMethod = httpMethod+"&";}
            this.url = URLEncoder.encode(url,ENC)+"&";
    }

    //A method used to generate the OAuth Authorization header
    //@Method randomAlphaNumeric() calls internal method using instance variable ALPHA_NUMERIC_STRING
    //@Method getSignature() returns String HMACSHA1 > Base64 encoded value of httpMethod,url,params
    public String generateOAuth()throws Exception{
        //Set timestamp as seconds from 01-01-1970
        Timestamp timestamp = new Timestamp(System.currentTimeMillis()/1000);
        Long aTimestamp = timestamp.getTime();
        //Set nonce which is a 10 digit random, non repeating alpha-numeric value
        String aNonce = randomAlphaNumeric(10);
        //Normalize and form param string
        String normalizedParams = "oauth_consumer_key="+consumerKey+"&"+"oauth_nonce="+aNonce+"&"+"oauth_signature_method="+"HMAC-SHA1"+"&"+"oauth_timestamp="+ aTimestamp.toString()+"&"+"oauth_version="+"1.0";
        //Percent encoded params
        params = URLEncoder.encode(normalizedParams,ENC);
        //Set signature variable
        String signature = getSignature();
        //place into required format
        String oAuthResult = "OAuth "+"oauth_version="+"\"1.0\""+","+"oauth_consumer_key="+"\"" + consumerKey + "\""+","+"oauth_signature_method="+"\"HMAC-SHA1\""+","+"oauth_timestamp="+"\""+aTimestamp+"\""+","+"oauth_nonce="+"\""+aNonce+"\""+","+"oauth_signature="+"\""+signature+"\"";
        return oAuthResult;
    }
    // A method designed to return a hashed and base64 encoded value.
    //@Param aString holds HMAC-SHA1 and Base 64 encoded value of variables httpMethod,url,params
    //@Param result holds percent encoded value of aString
    private String getSignature()
            throws Exception {
        //form base string
        StringBuilder base = new StringBuilder();
        base.append(httpMethod);
        base.append(url);
        base.append(params);
        //Set SecretKey of variable secretKey using HMAC-SHA1 algorithm
        SecretKey signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        // Compute the hmac on input data bytes, then encode to Base64
        String aString = Base64.getEncoder().encodeToString(mac.doFinal(base.toString().getBytes(ENC))).trim();
        //Percent encoded the Base64 value
        String result = URLEncoder.encode(aString, ENC);
        return new String(result);

    }

    //Required for nonce, returns a random alpha numeric value by using variable ALPHA_NUMERIC_STRING
    private static String randomAlphaNumeric(int count) {
        StringBuilder builder = new StringBuilder();
        while (count-- != 0) {
            int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
            builder.append(ALPHA_NUMERIC_STRING.charAt(character));
        }
        return builder.toString();
    }
}