{"id":1667,"date":"2016-10-06T15:43:03","date_gmt":"2016-10-06T13:43:03","guid":{"rendered":"http:\/\/blog.rabahi.net\/?page_id=1667"},"modified":"2017-05-11T11:30:41","modified_gmt":"2017-05-11T09:30:41","slug":"java-oauth2-client","status":"publish","type":"page","link":"https:\/\/blog.rabahi.net\/?page_id=1667","title":{"rendered":"Java &#8211; OAuth2 Client"},"content":{"rendered":"<h1>Dependencies<\/h1>\n<p>If you use maven, add this to your pom.xml file : <\/p>\n<pre lang=\"xml\">\r\n<dependency>\r\n\t<groupId>org.apache.httpcomponents<\/groupId>\r\n\t<artifactId>httpclient<\/artifactId>\r\n\t<version>4.5.2<\/version>\r\n<\/dependency>\r\n\r\n<dependency>\r\n\t<groupId>org.json<\/groupId>\r\n\t<artifactId>json<\/artifactId>\r\n\t<version>20160810<\/version>\r\n<\/dependency>\r\n<\/pre>\n<h2>Now let&#8217;s get access_token<\/h2>\n<pre lang=\"java\">\r\npackage net.rabahi.oauth2.client;\r\n\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStreamReader;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport org.apache.commons.codec.binary.Base64;\r\nimport org.apache.http.HttpResponse;\r\nimport org.apache.http.NameValuePair;\r\nimport org.apache.http.client.ClientProtocolException;\r\nimport org.apache.http.client.HttpClient;\r\nimport org.apache.http.client.entity.UrlEncodedFormEntity;\r\nimport org.apache.http.client.methods.HttpPost;\r\nimport org.apache.http.impl.client.HttpClientBuilder;\r\nimport org.apache.http.message.BasicNameValuePair;\r\nimport org.json.JSONObject;\r\n\r\npublic class OAuth2Client {\r\n\r\n\tprivate String serverUrl = null;\r\n\r\n\r\n\tpublic OAuth2Client(String serverUrl) {\r\n\t\tthis.serverUrl = serverUrl;\r\n\t}\r\n\r\n\tpublic String getAccessToken(String login, String password, String clientId) throws ClientProtocolException, IOException {\t\t\r\n\t\tHttpPost httpPost = new HttpPost(serverUrl+\"\/oauth\/token\");\r\n\r\n\t\t\/\/ add header :\t\t\r\n\t\tbyte[] encoded = Base64.encodeBase64(\"clientPassword:secret\".getBytes(\"UTF-8\"));\r\n\t\thttpPost.setHeader(\"Authorization\",\"Basic \" + new String(encoded));\r\n\t\thttpPost.setHeader(\"Accept\", \"application\/json\");\r\n\r\n\t\t\/\/ add post parameters :\r\n\t\tList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();\r\n\t\turlParameters.add(new BasicNameValuePair(\"grant_type\", \"password\"));\r\n\t\turlParameters.add(new BasicNameValuePair(\"username\", login));\r\n\t\turlParameters.add(new BasicNameValuePair(\"password\", password));\r\n\t\turlParameters.add(new BasicNameValuePair(\"client_id\", clientId));\r\n\r\n\t\thttpPost.setEntity(new UrlEncodedFormEntity(urlParameters));\r\n\r\n\t\t\/\/ send post :\r\n\t\tHttpClient httpClient = HttpClientBuilder.create().build();\t\t\r\n\t\tHttpResponse response = httpClient.execute(httpPost);\r\n\r\n\t\t\/\/ get response :\r\n\t\tSystem.out.println(\"Response Code : \" + response.getStatusLine().getStatusCode());\r\n\r\n\t\tString accessToken=null;\r\n\r\n\t\tif(response.getStatusLine().getStatusCode() == 200) {\t\t\r\n\t\t\tBufferedReader bufferedReader = new BufferedReader(\r\n\t\t\t\t\tnew InputStreamReader(response.getEntity().getContent()));\r\n\r\n\t\t\tStringBuffer result = new StringBuffer();\r\n\t\t\tString line = \"\";\r\n\t\t\twhile ((line = bufferedReader.readLine()) != null) {\r\n\t\t\t\tresult.append(line);\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ convert String to Json :\r\n\t\t\tJSONObject json = new JSONObject(result.toString());\r\n\t\t\t\/\/ get access_token :\r\n\t\t\taccessToken = (String) json.get(\"access_token\");\r\n\t\t}\r\n\r\n\t\treturn accessToken;\r\n\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) throws Exception, Exception {\r\n\t\tString url = \"http:\/\/localhost:8080\/oauth-server\";\r\n\t\t\r\n\t\tOAuth2Client oAuth2Client = new OAuth2Client(url);\r\n\t\toAuth2Client.getAccessToken(\"user1\", \"user1Password\", \"clientPassword\");\r\n\t}\r\n\r\n}\r\n\r\n<\/pre>\n<p>Note : The parameters that &#8220;clientPassword:secret&#8221; are encoded to base64. They allow user to authenticate.<\/p>\n<p>In the side of the OAuth server; the config file must have this :<\/p>\n<pre lang=\"java\">\r\n@Configuration\r\n@EnableAuthorizationServer\r\npublic class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {\r\n  (...)\r\n \r\n@Override\r\n    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {\r\n         .jdbc(dataSource)          \r\n               .withClient(\"clientPassword\")\r\n               .secret(\"secret\")\r\n               .authorizedGrantTypes(\"password\",\"authorization_code\", \"refresh_token\")\r\n               .scopes(\"foo\",\"read\",\"write\")\r\n               .accessTokenValiditySeconds(3600) \/\/ 1 hour\r\n               .refreshTokenValiditySeconds(2592000) \/\/ 30 days\r\n    }\r\n \r\n  (...)\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Dependencies If you use maven, add this to your pom.xml file : org.apache.httpcomponents httpclient 4.5.2 org.json json 20160810 Now let&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1538,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1667","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1667","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1667"}],"version-history":[{"count":6,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1667\/revisions"}],"predecessor-version":[{"id":1674,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1667\/revisions\/1674"}],"up":[{"embeddable":true,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1538"}],"wp:attachment":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1667"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}