1

Hello there I'm stuck on a oauth2 issue. I don't use spring. I have some JAX-RS web services made up using netbeans's included jersey jars. I have to secure this services using oauth 2 so that mobile client could use it without storing user credentials. I don't even know where to start as all examples I see use Spring... the ones that don't use spring use the Oltu library wich documentation doesn't convince me .Some oltu samples don't even work. Can anyone show me a tutorial that will help me build an authorization server from scratch using jersey and some library? any one even oltu ...

  • You can get the pattern from spring examples – haseeb Oct 05 '15 at 17:17
  • I'll post you an explanation, but first I need to know: do you comprehend the functionnement of OAuth, and its many parts (client, user, ressource server, etc) ? – Turtle May 03 '17 at 13:18
  • @user3252187 I posted you an example of what a test client could look like, based on the [oltu example](https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart) and my own code (that mainly comes from the internet). – Turtle May 03 '17 at 13:33

1 Answers1

0

My answer will be based on Oltu. I'll be using CLIENT_CREDENTIALS authent.

Getting the token should look like this:

// We initialize a client
OAuthClient lOAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse lOAuthResponse;

// We are creating a request that's already formatted following the Oauth specs
OAuthClientRequest lRequest = OAuthClientRequest
        .tokenLocation(TOKEN_SERVER_URI)
        .setGrantType(GrantType.CLIENT_CREDENTIALS)
        .setClientId(CLIENT_ID)
        .setClientSecret(CLIENT_SECRET)
        .setScope("admin")
        .buildBodyMessage();

//This will submit the request
String code =  lOAuthClient.accessToken(lRequest, OAuthJSONAccessTokenResponse.class).getAccessToken();
System.out.println("Token obtained:" + token);

Now we can get our ressource using our token:

HttpURLConnection resourceConn = (HttpURLConnection) (new URL(RESSOURCE_SERVER_URI).openConnection());
resourceConn.addRequestProperty("Authorization", "Bearer " + token);

InputStream resource = resourceConn.getInputStream();

// Do whatever you want to do with the contents of resource at this point.
BufferedReader r = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
String line = null;
while ((line = r.readLine()) != null)
    System.out.println(line);
Turtle
  • 1,626
  • 16
  • 26