#oauth with java

1 messages · Page 1 of 1 (latest)

sacred radish
stone smeltBOT
#

<@&987246399047479336> please have a look, thanks.

stone smeltBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

lost pike
#

most people just use spring for any backend/api topics. it does oauth out of the box

sacred radish
#

sick

#

can you drop the maven import

lost pike
sacred radish
#

appreciaet it

sacred radish
lost pike
#

actually, the link shows how to secure ur own website with oauth

#

not how to oauth login elsewhere

sacred radish
#

do you have a library to help with that

sacred radish
#

Yeah

#

I’m doing web requests and need to send authorization

limpid heart
#

At the bottom of the page you linked, they link you to libraries

sacred radish
#

The spring one? They said

limpid heart
#

Here are some for Java

sacred radish
#

Wait oh

#

Is the spring one for headers

#

@lost pike said that it was for server side accept oauth

limpid heart
#

Why don't you take a look at the documentation?

lost pike
#

spring can do both

#

spring can do anything for backend/api topics

quartz horizon
#

@sacred radish you don't want spring for your thing

#

you aren't making a website

#

you are making an app

sacred radish
quartz horizon
#

iirc

sacred radish
#

yeah i am

#

im just making requests and need a library to handle the OAuth headers

quartz horizon
#

Consumer keys for two-legged OAuth can be obtained by clicking on the Integration menu item on the left after logging in as an administrator. NOTE: only users with roles that have the Access Schoology API permission can obtain an API consumer key.

#

go to the two legged part

#

it seems you just need to make this auth header

#
Authorization: OAuth realm="Schoology API",
   oauth_consumer_key="dpf43f3p2l4k3l03",
   oauth_token="",
   oauth_nonce="kllo9940pd9333jh",
   oauth_timestamp="1200376800",
   oauth_signature_method="PLAINTEXT",
   oauth_version="1.0",
   oauth_signature="kd94hf93k423kf44%26"
#

which you can definitely do with just the HttpClient built into java

#

you don't need a special library

#
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.UUID;

public final class SchoolologyClient {
    private final HttpClient client;
    private final String oauthConsumerKey;
    private final String oauthConsumerSecret;

    public SchoolologyClient(
            String oauthConsumerKey,
            String oauthConsumerSecret
    ) {
        this.client = HttpClient.newHttpClient();
        this.oauthConsumerKey = oauthConsumerKey;
        this.oauthConsumerSecret = oauthConsumerSecret;
    }

    private HttpRequest.Builder baseRequest() {
        var authorization = "Authorization";
        return HttpRequest.newBuilder()
                .header(authorization, "OAuth realm=\"Schoology API\"")
                .header(authorization, "oauth_consumer_key=\"" +
                        URLEncoder.encode(this.oauthConsumerKey, StandardCharsets.UTF_8) +
                        "\""
                )
                .header(authorization, "oauth_token=\"\"")
                .header(authorization, "oauth_nonce=\"" + UUID.randomUUID() + "\"")
                .header(authorization, "oauth_timestamp=\"" + Instant.now().getEpochSecond() + "\"")
                .header(authorization, "oauth_signature_method=\"PLAINTEXT\"")
                .header(authorization, "oauth_version=\"1.0\"")
                .header(authorization, "oauth_signature=\"" +
                        URLEncoder.encode(this.oauthConsumerSecret, StandardCharsets.UTF_8) +
                        "\""
                );
    }
}

#

here is a start

sacred radish
quartz horizon
#

🤷‍♂️

sacred radish
#

for the secret though, do i need to do something special with the Oauth_signature

quartz horizon
#

doesn't look like it

#

idk give it a shot

stone smeltBOT
#

Closed the thread due to inactivity.

If your question was not resolved yet, feel free to just post a message to reopen it, or create a new thread. But try to improve the quality of your question to make it easier to help you 👍

sacred radish
#

helo

#

it should look something like this, all these headers need to be inside the auth header

#

wait you are doing that XD mb

#

im making a request to https://api.schoology.com/v1/users/5

#

its returning <html> <head><title>400 Bad Request</title></head> <body> <center><h1>400 Bad Request</h1></center> </body> </html>

sacred radish
quartz horizon
#

nope

#

can you inspect the request

#

also i think you should be making the request to some endpoint with those headers to get a token

#

thats how it works with other oauth things i've used before

#

make the request with those headers to /oauth/request_token

sacred radish
#

ok

sacred radish
#

but ill give it a shot

#

just did that, still getting badrequest

#

heres the code

todoResponse = client.send(
                    HttpRequest.newBuilder()
                            .GET()
                                .uri(URI.create("https://api.schoology.com/v1/oauth/request_token"))
                            .header(authorization, "OAuth realm=\"Schoology API\"")
                            .header(authorization, "oauth_consumer_key=\"" +
                                    /* URLEncoder.encode(getKey(), StandardCharsets.UTF_8) +
                                    "\""*/
                                    getKey() + "\""
                            )
                            .header(authorization, "oauth_token=\"\"")
                            .header(authorization, "oauth_nonce=\"" + UUID.randomUUID() + "\"")
                            .header(authorization, "oauth_timestamp=\"" + Instant.now().getEpochSecond() + "\"")
                            .header(authorization, "oauth_signature_method=\"PLAINTEXT\"")
                            .header(authorization, "oauth_version=\"1.0\"")
                            .header(authorization, "oauth_signature=\"" +
                                            URLEncoder.encode(getSecret(), StandardCharsets.UTF_8) +
                                            "\"")
                            .build(),
                    HttpResponse.BodyHandlers.ofString()
stone smeltBOT
# sacred radish heres the code ```java todoResponse = client.send( HttpRequ...

Detected code, here are some useful tools:

Formatted code
todoResponse = client.send(HttpRequest.newBuilder().GET().uri(URI.create("https://api.schoology.com/v1/oauth/request_token")).header(authorization, "OAuth realm=\"Schoology API\"").header(authorization, "oauth_consumer_key=\"" + /* URLEncoder.encode(getKey(), StandardCharsets.UTF_8) +
 "\""*/
getKey() + "\"").header(authorization, "oauth_token=\"\"").header(authorization, "oauth_nonce=\"" + UUID.randomUUID() + "\"").header(authorization, "oauth_timestamp=\"" + Instant.now().getEpochSecond() + "\"").header(authorization, "oauth_signature_method=\"PLAINTEXT\"").header(authorization, "oauth_version=\"1.0\"").header(authorization, "oauth_signature=\"" + URLEncoder.encode(getSecret(), StandardCharsets.UTF_8) + "\"").build(), HttpResponse.BodyHandlers.ofString()
sacred radish
#

that looks uglier...

#

Anyway I found a module that can maybe make this a bit easier

#

Called Scribe, I put it in my pom but when I put it in my project requirements it shows red even after running a maven command

quartz horizon
#

can you DM me an example api key?

#

key + secret or wtvr

#

i can give it a shot

sacred radish
#

my key and secret have my real name on it so im not usre

quartz horizon
#

is there a sandbox env i can try?

#

idk

sacred radish
#

ummmm

#

there could be i can do some digging

#

but it doesn't say anything about how to do any fo that

#

oh you can register and become an app developer

#

ok i just made an app developer account and I have creds for a test school

#

let me dm them to you

#

ok just sent them over @quartz horizon

sacred radish
#

ok i gave this a shot

#

how would i pass in params for a POST request? @quartz horizon

quartz horizon
#

1 sec

#

trying the oauth thing

#

@sacred radish what is the base url i should be using?

sacred radish
#

oh i got it to work

#

.header("Authorization", "OAuth realm=\"Schoology API\", " +
                                    "oauth_consumer_key=\"" + key + "\", " +
                                    "oauth_token=\"\", " +
                                    "oauth_nonce=\"" + UUID.randomUUID() + "\", " +
                                    "oauth_timestamp=\"" + Instant.now().getEpochSecond() + "\", " +
                                    "oauth_signature_method=\"PLAINTEXT\", " +
                                    "oauth_version=\"1.0\", " +
                                    //"oauth_signature=\"" + URLEncoder.encode(getSecret(), StandardCharsets.UTF_8) + "\"")
                                    "oauth_signature=\"" + secret + "%26\"")
#

you need to define the key and secret

#

but that works

quartz horizon
#

huh, cool

#

well to pass in params

#
.POST(HttpRequest.BodyPublishers.ofString(
                                    "{}"
                            ))
#

use a body publisher

#
.POST(HttpRequest.BodyPublishers.ofString(Json.writeString(thing)))
#

something like this

sacred radish
#

if i have a map of the stuff.i wnat to pass in

#

how would i do that

quartz horizon
#

what is the map

#

like what type are the elements

#

and keys

sacred radish
#

it will be most likely String, String

#

it may need to be an Object for the value as they could be integers

quartz horizon
#

how is this map getting to you?

sacred radish
#

i will create it most likely

quartz horizon
#

are you doing anything to it but just passing it in here?

#
JsonObject o = Json.objectBuilder()
   .put("thing", "abc")
   .put("other", 123)
   .build();

Map<String, Json> o2 = o;
#

JsonObject is just a map of String to Json so if you need the map part and Map<String, Object> would have worked...

sacred radish
#

oh ok

sacred radish
#

i will probs also do PUT and DELETE even though idk how to use either of them i just use POST and GET

#

I'm doing it like this;

    public static Json post(URI uri, Map<String, Object> params){

How would i insert all params from the params into a json?

#

oh wait i forgot about putAll(

#

oh but object is not json encodeable

#

wait how can I do this so putAll will work?

quartz horizon
#

thats what im confused about

#

why not just

#

public static Json post(URI uri, Json params)

#

object is not json encodeable
Yeah Object can be literally anything

quartz horizon
sacred radish
sacred radish
quartz horizon
#
    public static Json post(URI uri, Map<String, Json> params){
#

Json.of( on params should get you Json again

#

but if you want the object one

sacred radish
#

im not sure, but i may need to POST user objects

#

let me confirm that

#

no i wont it will just be a json map

quartz horizon
#
    public static Json post(URI uri, Map<String, Object> params){
        JsonObject.Builder jsonParamsBuilder = Json.objectBuilder();
        for (var entry : params.entrySet()) {
            Json value;
            if (entry.getValue() instanceof String s) {
                value = Json.of(s);
            }
            else if (entry.getValue() instanceof Integer i) {
                value = Json.of(i);
            }
            else if (entry.getValue() instanceof Long l) {
                value = Json.of(l);
            }
            else if (entry.getValue() instanceof Double d) {
                value = Json.of(d);
            }
            else if (entry.getValue() instanceof JsonEncodable encodable) {
                value = encodable.toJson();
            }
            else if (entry.getValue() == null) {
                value = Json.ofNull();
            }
            else {
                throw new IllegalArgumentException();
            }

            jsonParamsBuilder.put(entry.getKey(), value);
        }
        
        Json jsonParams = jsonParamsBuilder.build();

    }
sacred radish
#

ok thanks

quartz horizon
#

if you really need that contract

sacred radish
#

ok now in this func ```java
public static Json post(URI uri, Json params){


how would i do this part?

```java
                            .POST(HttpRequest.BodyPublishers.ofString(params))

#

would i have to call toString??

quartz horizon
#

Json.writeString

#

but actually toString on a JsonObject would work

#

(does the same thing)

sacred radish
#

ok sounds good

#

let me try posting andsee what happens

quartz horizon
#

lmk if that works

sacred radish
#
Json params = Json.objectBuilder().put("school_uid", "test0").put("user_first", "test1").put("user_last", "test2").put("primary_email", "test3").put("role_id", "test4").put("additional_buildings", "456").build();
            Json json = post("https://api.schoology.com/v1/users",params);
#

im getting Invalid json from the API

#
public static Json post(URI uri, Json params){
        HttpResponse<String> todoResponse;
        try {
            todoResponse = client.send(
                    HttpRequest.newBuilder()
                            .POST(HttpRequest.BodyPublishers.ofString(params.toString()))
                            .uri(uri)
                            .header("Authorization", "OAuth realm=\"Schoology API\", " +
                                    "oauth_consumer_key=\"" + key + "\", " +
                                    "oauth_token=\"\", " +
                                    "oauth_nonce=\"" + UUID.randomUUID() + "\", " +
                                    "oauth_timestamp=\"" + Instant.now().getEpochSecond() + "\", " +
                                    "oauth_signature_method=\"PLAINTEXT\", " +
                                    "oauth_version=\"1.0\", " +
                                    //"oauth_signature=\"" + URLEncoder.encode(getSecret(), StandardCharsets.UTF_8) + "\"")
                                    "oauth_signature=\"" + secret + "%26\"")
                            .header("Accept", "application/json")
                            //.header("Host", "api.schoology.com")
                            .header("Content-Type", "application/json")
                            .build(),
                    HttpResponse.BodyHandlers.ofString()
            );
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try{
            return Json.readString(todoResponse.body());
        } catch (Exception e){
            System.out.println("Invalid json");
            throw e;
        }
    }
#

I have a static method for a string versoin too

public static Json post(String uri, Json params){
        return post(URI.create(uri), params);
    }
#

maybe i should add double string

quartz horizon
sacred radish
#

good idea

#

we have this now

            Json params = Json.objectBuilder().put("\"school_uid\"", "\"test0\"").put("\"user_first\"", "\"test1\"").put("\"user_last\"", "\"test2\"").put("\"primary_email\"", "\"test3\"").put("\"role_id\"", "\"test4\"").put("\"additional_buildings\"", "\"456\"").build();

#

still nothing...

sacred radish
quartz horizon
#

No

#

You don't need to do that

#

Usually when I have trouble with an API request I first make it work in Postman or curl

#

Wait, yeah don't do "\"abc\"" just do "abc"

#

If you've been doing that the whole time that is probably the issue

sacred radish
sacred radish
#

ok im getting a 401