Как аутентифицировать API с помощью OAuth1.0 с пользовательским заголовком с использованием Spring boot

#spring-boot #api #authentication #oauth #oauth-1.0a

#spring-boot #API #аутентификация #oauth #oauth-1.0a

Вопрос:

Я работаю над процессом авторизации OAuth1.0, и вот мой Java-код в Spring boot,

 package com.example.demo;

import com.mgiorda.oauth.OAuthConfig;
import com.mgiorda.oauth.OAuthConfigBuilder;
import com.mgiorda.oauth.OAuthSignature;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
//import com.example.demo.testsign;
import java.util.Collections;


@SpringBootApplication
@ComponentScan(basePackages = {"com.example.demo.controller"})
@Configuration
@EnableAutoConfiguration

public class TestapiApplication {
    public  static String testm() {

        OAuthConfig oauthConfig = new OAuthConfigBuilder("CONSUMER KEY", "CONSUM_SECRET_KEY")
                .setTokenKeys("ACCESS TOKEN", "SECRET TOKEN")
                .build();

        OAuthSignature signature = oauthConfig.buildSignature(com.mgiorda.oauth.HttpMethod.GET, url)
                .addQueryParam("aParam", "aValue")
                .addFormUrlEncodedParam("myParam", "anotherValue")
                .create();
        return signature.getAsHeader();
    }

    public static void main(String[] args) {
        String val = testm();
        //System.out.println(val);
        // request url
        String url = "htpps://khjfskdhf.com";

// create an instance of RestTemplate
        RestTemplate restTemplate = new RestTemplate();

// create headers
        HttpHeaders headers = new HttpHeaders();
// set `Content-Type` and `Accept` headers
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// example of custom header

        headers.set(HttpHeaders.AUTHORIZATION,val);
        System.out.println(headers);
// build the request
        HttpEntity request = new HttpEntity(headers);

// make an HTTP GET request with headers
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                request,
                String.class
        );

// check response
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Request Successful.");
            System.out.println(response.getBody());
        } else {
            System.out.println("Request Failed");
            System.out.println(response.getStatusCode());
        }
    }

}
  

Я создал заголовок, используя метод подписи, и передаю его своему основному методу для авторизации. Но я получил ошибку 404 Not Found, вот сообщение об ошибке,

 08:13:17.464 [main] DEBUG org.springframework.web.client.RestTemplate - Response 404 NOT_FOUND
Exception in thread "main" org.springframework.web.client.HttpClientErrorException$NotFound: 404 Not Found: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:113)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:184)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:583)
    at com.example.demo.TestapiApplication.main(TestapiApplication.java:61)
  

Может ли кто-нибудь сообщить мне, почему у меня это не работает. Я действительно изо всех сил пытаюсь закончить это. Есть предложения?

Спасибо, Прабха

Комментарии:

1. Является ли Oauth1 устаревшим? Как вы можете использовать импорт ‘com.mgiorda.oauth. OAuthConfig;’ если он устарел? Можете ли вы связать меня с зависимостью mvn, которая используется для этого, пожалуйста.

Ответ №1:

Я решил проблему, указав значения параметров URL и создав пользовательский метод запроса пения для заголовка.