My linux world » Java – OAuth2 Client

Java - OAuth2 Client


Dependencies

If you use maven, add this to your pom.xml file :

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.2</version>
</dependency>
 
<dependency>
	<groupId>org.json</groupId>
	<artifactId>json</artifactId>
	<version>20160810</version>
</dependency>

Now let’s get access_token

package net.rabahi.oauth2.client;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
 
public class OAuth2Client {
 
	private String serverUrl = null;
 
 
	public OAuth2Client(String serverUrl) {
		this.serverUrl = serverUrl;
	}
 
	public String getAccessToken(String login, String password, String clientId) throws ClientProtocolException, IOException {		
		HttpPost httpPost = new HttpPost(serverUrl+"/oauth/token");
 
		// add header :		
		byte[] encoded = Base64.encodeBase64("clientPassword:secret".getBytes("UTF-8"));
		httpPost.setHeader("Authorization","Basic " + new String(encoded));
		httpPost.setHeader("Accept", "application/json");
 
		// add post parameters :
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("grant_type", "password"));
		urlParameters.add(new BasicNameValuePair("username", login));
		urlParameters.add(new BasicNameValuePair("password", password));
		urlParameters.add(new BasicNameValuePair("client_id", clientId));
 
		httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
 
		// send post :
		HttpClient httpClient = HttpClientBuilder.create().build();		
		HttpResponse response = httpClient.execute(httpPost);
 
		// get response :
		System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
 
		String accessToken=null;
 
		if(response.getStatusLine().getStatusCode() == 200) {		
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent()));
 
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}
 
			// convert String to Json :
			JSONObject json = new JSONObject(result.toString());
			// get access_token :
			accessToken = (String) json.get("access_token");
		}
 
		return accessToken;
 
	}
 
	public static void main(String[] args) throws Exception, Exception {
		String url = "http://localhost:8080/oauth-server";
 
		OAuth2Client oAuth2Client = new OAuth2Client(url);
		oAuth2Client.getAccessToken("user1", "user1Password", "clientPassword");
	}
 
}

Note : The parameters that “clientPassword:secret” are encoded to base64. They allow user to authenticate.

In the side of the OAuth server; the config file must have this :

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  (...)
 
@Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
         .jdbc(dataSource)          
               .withClient("clientPassword")
               .secret("secret")
               .authorizedGrantTypes("password","authorization_code", "refresh_token")
               .scopes("foo","read","write")
               .accessTokenValiditySeconds(3600) // 1 hour
               .refreshTokenValiditySeconds(2592000) // 30 days
    }
 
  (...)
}

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub