{"id":1659,"date":"2016-10-05T16:21:01","date_gmt":"2016-10-05T14:21:01","guid":{"rendered":"http:\/\/blog.rabahi.net\/?page_id=1659"},"modified":"2017-05-11T12:48:20","modified_gmt":"2017-05-11T10:48:20","slug":"java-spring-security-oauth2","status":"publish","type":"page","link":"https:\/\/blog.rabahi.net\/?page_id=1659","title":{"rendered":"Java Spring Security &#8211; OAuth2"},"content":{"rendered":"<p>I will give two quick examples about OAuth2.<br \/>\nThe first example will use server + resource + client implicit (i.e. redirect to server to make authentication).<br \/>\nThe second one will use server + resource + client password (will have its own form to authenticate, but ask server if user is allowed to connect).<\/p>\n<div id=\"toc_container\" class=\"no_bullets\"><p class=\"toc_title\">Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Server\"><span class=\"toc_number toc_depth_1\">1<\/span> Server<\/a><\/li><li><a href=\"#Resource_server\"><span class=\"toc_number toc_depth_1\">2<\/span> Resource server<\/a><\/li><li><a href=\"#Implicit_client\"><span class=\"toc_number toc_depth_1\">3<\/span> Implicit client<\/a><\/li><li><a href=\"#Password_client\"><span class=\"toc_number toc_depth_1\">4<\/span> Password client<\/a><\/li><\/ul><\/div>\n<h1><span id=\"Server\">Server<\/span><\/h1>\n<p>The server must extends AuthorizationServerConfigurerAdapter :<\/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(\"clientImplicit\")\r\n               .authorizedGrantTypes(\"implicit\")\r\n               .scopes(\"read\",\"write\",\"foo\",\"bar\")\r\n               .autoApprove(false)\r\n               .accessTokenValiditySeconds(3600)\r\n\r\n               .and()\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<h1><span id=\"Resource_server\">Resource server<\/span><\/h1>\n<p>The resource server will extends ResourceServerConfigurerAdapter :<\/p>\n<pre lang=\"java\">\r\n@Configuration\r\n@EnableResourceServer\r\npublic class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {\r\n  (...)\r\n\r\n    @Override\r\n    public void configure(final HttpSecurity http) throws Exception {\r\n        http\r\n            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)\r\n            .and().authorizeRequests().anyRequest().authenticated();\r\n    }\r\n\r\n  (...)\r\n}\r\n<\/pre>\n<p>When a user will request the spring servlets, the authorization can be checked like this :<\/p>\n<pre lang=\"java\">\r\n@PreAuthorize(\"#oauth2.hasScope('foo') and #oauth2.hasScope('read')\")\r\n@RequestMapping(method = RequestMethod.GET, value = \"\/foos\/get\")\r\npublic Foo get() {\r\n  return new Foo();\r\n}\r\n<\/pre>\n<p>Or simply like this :<\/p>\n<pre lang=\"java\">\r\n@PreAuthorize(\"isFullyAuthenticated()\")\r\n@RequestMapping(method = RequestMethod.GET, value = \"\/foos\/get\")\r\npublic Foo get() {\r\n  return new Foo();\r\n}\r\n<\/pre>\n<h1><span id=\"Implicit_client\">Implicit client<\/span><\/h1>\n<p>To get the access token, the client will request :<\/p>\n<pre>\r\nhttp:\/\/oauth-server\/oauth-authorize?response_type=token\r\n                                   &scope=read write foo bar\r\n                                   &client_id=clientImplicit\r\n                                   &redirect_uri=http:\/\/oauth-client-implicit\r\n  \r\n<\/pre>\n<p>The server will authenticate user.<br \/>\nIf succeed, redirect to http:\/\/oauth-client-implicit?access_token=YOUR_ACCESS_TOKEN.<\/p>\n<p>You can get the access token like this :<\/p>\n<pre lang=\"javascript\">\r\nvar match = document.location.hash.match(\/access_token=([\\w-\\.]+)\/);\r\nvar access_token=!!match && match[1];\r\n<\/pre>\n<h1><span id=\"Password_client\">Password client<\/span><\/h1>\n<p>To get the access_token, the client must request zuul server :<\/p>\n<pre lang=\"javascript\">\r\njQuery.ajax({\r\n\t\turl: \"http:\/\/oauth-client-password\/oauth\/token\",\r\n\t\tbeforeSend: function (xhr) {\r\n\t\t\txhr.setRequestHeader('Accept',        \"application\/json\");\r\n\t\t},\t\t\r\n\t\tdata : {grant_type : \"password\",\r\n\t\t\tusername : \"user1\",\r\n\t\t\tpassword : \"user1Password\",\r\n\t\t\tclient_id : \"clientPassword\"\r\n                       },\r\n\t\tsuccess: function(response) {\r\n                    access_token = response.access_token;\r\n                },\t\t\r\n\t\terror : function( jqXHR, textStatus, errorThrown) {\r\n\t\t\tconsole.error(jqXHR);\r\n\t\t}\r\n\t});\r\n<\/pre>\n<p>To refresh access token :<\/p>\n<pre lang=\"javascript\">\r\njQuery.ajax({\r\n\t\turl: \"http:\/\/oauth-client-password\/oauth\/token\",\r\n\t\tbeforeSend: function (xhr) {\r\n\t\t\txhr.setRequestHeader('Accept',        \"application\/json\");\r\n                        xhr.setRequestHeader('Authorization', \"Bearer YOUR_ACCESS_TOKEN\");\r\n\t\t},\t\t\r\n\t\tdata : {grant_type : \"refresh_token\"},\r\n\t\tsuccess: function(response) {\r\n                    access_token = response.access_token;\r\n                },\t\t\r\n\t\terror : function( jqXHR, textStatus, errorThrown) {\r\n\t\t\tconsole.error(jqXHR);\r\n\t\t}\r\n\t});\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>I will give two quick examples about OAuth2. The first example will use server + resource + client implicit (i.e. redirect to server to make authentication). The second one will use server + resource + client password (will have its own form to authenticate, but ask server if user is allowed to connect). Contents1 Server2 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1642,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1659","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1659","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=1659"}],"version-history":[{"count":6,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1659\/revisions"}],"predecessor-version":[{"id":1985,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1659\/revisions\/1985"}],"up":[{"embeddable":true,"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=\/wp\/v2\/pages\/1642"}],"wp:attachment":[{"href":"https:\/\/blog.rabahi.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1659"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}