Search code examples
javaoauth-2.0okhttp

Is it possible to do a OAuth2 request with okHttp client with plain Java


I try to use a api with OAuth2. With Postman it works. But now I try to write this in Java. I don't have spring boot, it is a simple Maven project The only example I found was this

Example okhttp

But it seems it only works with base authentication.

My question is, is it possible to do a Oauth2 with okhttp? Or is it the wrong library?


Solution

  • So my solution was to generate post request to get the token

     private static void postCall() throws IOException {
    
        // Create a new HTTP client        
        OkHttpClient client = new OkHttpClient()
                .newBuilder()           
                .build();
    
        // Create the request body
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.Companion.create("password=yourPassword&grant_type=password&client_id=yoirClientId&username=yourUserName",mediaType);
        
        // Build the request object, with method, headers
        Request request = new Request.Builder()
                .url("https://your-address-to-get-the-token/openid-connect/token")
                .method("POST", body)               
                .build();
                
        // Perform the request, this potentially throws an IOException
        Response response = client.newCall(request).execute();
        // Read the body of the response into a hashmap
        Map<String, Object> responseMap = new ObjectMapper().readValue(response.body().byteStream(), HashMap.class);
        // Read the value of the "access_token" key from the hashmap
        String accessToken = (String) responseMap.get("access_token");
        //System.out.println(responseMap.toString());
        // Return the access_token value
        System.out.println("accessToken " + accessToken);
    
         request = new Request.Builder()
                .url("https://your-endpoint-rest-call")
                .method("GET", null)
                .addHeader("Authorization", "Bearer " + accessToken)
                .build();
    
         response = client.newCall(request).execute();
         System.out.println("Response" + response.body().string());
    
    
    }