diff --git a/spring-security-oauth/spring-security-oauth-server-demo/.classpath b/persistence-jpa/.classpath similarity index 85% rename from spring-security-oauth/spring-security-oauth-server-demo/.classpath rename to persistence-jpa/.classpath index 0cad5db2d0..fae1a2b37d 100644 --- a/spring-security-oauth/spring-security-oauth-server-demo/.classpath +++ b/persistence-jpa/.classpath @@ -17,6 +17,11 @@ + + + + + @@ -25,7 +30,6 @@ - diff --git a/spring-security-oauth/spring-security-oauth-server/.project b/persistence-jpa/.project similarity index 60% rename from spring-security-oauth/spring-security-oauth-server/.project rename to persistence-jpa/.project index a66e7f1009..b5ac58ebd1 100644 --- a/spring-security-oauth/spring-security-oauth-server/.project +++ b/persistence-jpa/.project @@ -1,12 +1,12 @@ - spring-security-oauth-server + jpa-storedprocedure - org.eclipse.wst.jsdt.core.javascriptValidator + org.eclipse.wst.common.project.facet.core.builder @@ -16,12 +16,7 @@ - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder + org.eclipse.m2e.core.maven2Builder @@ -30,19 +25,10 @@ - - org.eclipse.m2e.core.maven2Builder - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature diff --git a/spring-security-oauth/.project b/spring-security-oauth/.project deleted file mode 100644 index fe6e295165..0000000000 --- a/spring-security-oauth/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - spring-security-oauth - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - diff --git a/spring-security-oauth/README.md b/spring-security-oauth/README.md deleted file mode 100644 index 6baa0a1824..0000000000 --- a/spring-security-oauth/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Spring Security OAuth - -### Relevant Articles: -- [Spring REST API + OAuth2 + AngularJS](http://www.baeldung.com/rest-api-spring-oauth2-angularjs) - -### Build the Project -``` -mvn clean install -``` - -### Notes -- Make sure to run the project on port 8081 -- Run 4 sub-modules simultaneously - - spring-security-oauth-server - - spring-security-oauth-resource - - spring-security-oauth-ui-implicit - - spring-security-oauth-ui-password diff --git a/spring-security-oauth/pom.xml b/spring-security-oauth/pom.xml deleted file mode 100644 index 7add3957c9..0000000000 --- a/spring-security-oauth/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - 4.0.0 - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - spring-security-oauth - pom - - - org.springframework.boot - spring-boot-starter-parent - 1.3.3.RELEASE - - - - spring-security-oauth-server - spring-security-oauth-resource - spring-security-oauth-ui-implicit - spring-security-oauth-ui-password - - - - spring-security-oauth - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - true - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - - - - - - - - - - 4.2.5.RELEASE - 4.0.4.RELEASE - 2.0.9.RELEASE - - - - 2.7.0 - - - 1.7.12 - 1.1.3 - - - 19.0 - 3.3.2 - - - 1.3 - 4.11 - 1.10.19 - - 4.4 - 4.4 - - 2.4.0 - - - 3.3 - 2.6 - 2.19 - 1.4.16 - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/.classpath b/spring-security-oauth/spring-security-oauth-resource-demo/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/.project b/spring-security-oauth/spring-security-oauth-resource-demo/.project deleted file mode 100644 index f6e67b2426..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-security-oauth-resource-demo - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/pom.xml b/spring-security-oauth/spring-security-oauth-resource-demo/pom.xml deleted file mode 100644 index 8a6eb8a2d4..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - 4.0.0 - spring-security-oauth-resource-demo - spring-security-oauth-resource-demo - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - - org.springframework.security.oauth - spring-security-oauth2 - ${oauth.version} - - - org.springframework.security - spring-security-jwt - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - - spring-security-oauth-resource-demo - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/MethodSecurityConfig.java deleted file mode 100644 index 25fcab2ffd..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/MethodSecurityConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; -import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { - - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - return new OAuth2MethodSecurityExpressionHandler(); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig1.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig1.java deleted file mode 100644 index d7e1a3e310..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig1.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; - -//@Configuration -//@EnableResourceServer -public class OAuth2ResourceServerConfig1 extends ResourceServerConfigurerAdapter { - - // - - @Override - public void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and().authorizeRequests().anyRequest().authenticated(); - ; - // @formatter:on - } - - @Bean - public TokenStore tokenStore() { - return new InMemoryTokenStore(); - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig2.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig2.java deleted file mode 100644 index 49d258c985..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig2.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.token.DefaultTokenServices; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; - -@Configuration -@EnableResourceServer -public class OAuth2ResourceServerConfig2 extends ResourceServerConfigurerAdapter { - - // - - @Override - public void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and().authorizeRequests().anyRequest().authenticated(); - ; - // @formatter:on - } - - @Override - public void configure(final ResourceServerSecurityConfigurer config) { - config.tokenServices(tokenServices()); - } - - // JWT - - @Bean - @Primary - public DefaultTokenServices tokenServices() { - final DefaultTokenServices tokenServices = new DefaultTokenServices(); - tokenServices.setTokenStore(tokenStore()); - return tokenServices; - } - - @Bean - public TokenStore tokenStore() { - return new JwtTokenStore(accessTokenConverter()); - } - - @Bean - public JwtAccessTokenConverter accessTokenConverter() { - final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); - converter.setSigningKey("123"); - return converter; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerApplication.java deleted file mode 100644 index 1e35eff551..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class ResourceServerApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(ResourceServerApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerWebConfig.java deleted file mode 100644 index 81b2d242ac..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/config/ResourceServerWebConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.web.controller" }) -public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { - // -} diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/BarController.java deleted file mode 100644 index 72163ff9ff..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/BarController.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import org.baeldung.web.dto.Bar; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class BarController { - - public BarController() { - super(); - } - - // API - read - // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") - @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") - @ResponseBody - public Bar findById(@PathVariable final long id) { - return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); - } - - // API - write - // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") - @RequestMapping(method = RequestMethod.POST, value = "/bars") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Bar create(@RequestBody final Bar bar) { - bar.setId(Long.parseLong(randomNumeric(2))); - return bar; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index d9ef1baa31..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import org.baeldung.web.dto.Foo; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class FooController { - - public FooController() { - super(); - } - - // API - read - // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id) { - return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); - } - - // API - write - // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") - @RequestMapping(method = RequestMethod.POST, value = "/foos") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo foo) { - foo.setId(Long.parseLong(randomNumeric(2))); - return foo; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Bar.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Bar.java deleted file mode 100644 index adbb2aa2ad..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Bar.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.dto; - -public class Bar { - private long id; - private String name; - - public Bar() { - super(); - } - - public Bar(final long id, final String name) { - super(); - - this.id = id; - this.name = name; - } - - // - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Foo.java b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Foo.java deleted file mode 100644 index 9d26618e7f..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/java/org/baeldung/web/dto/Foo.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.dto; - -public class Foo { - private long id; - private String name; - - public Foo() { - super(); - } - - public Foo(final long id, final String name) { - super(); - - this.id = id; - this.name = name; - } - - // - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-resource-demo/src/main/resources/application.properties deleted file mode 100644 index 62a10d1751..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource-demo/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-resource -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/.classpath b/spring-security-oauth/spring-security-oauth-resource/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-resource/.project b/spring-security-oauth/spring-security-oauth-resource/.project deleted file mode 100644 index c3a285960b..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-security-oauth-resource - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-security-oauth/spring-security-oauth-resource/pom.xml b/spring-security-oauth/spring-security-oauth-resource/pom.xml deleted file mode 100644 index 84a5027cb5..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - 4.0.0 - spring-security-oauth-resource - spring-security-oauth-resource - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework - spring-jdbc - - - - mysql - mysql-connector-java - runtime - - - - org.springframework.security.oauth - spring-security-oauth2 - ${oauth.version} - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - - - spring-security-oauth-resource - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java deleted file mode 100644 index 25fcab2ffd..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/MethodSecurityConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; -import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { - - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - return new OAuth2MethodSecurityExpressionHandler(); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java deleted file mode 100644 index 85d75a857b..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/OAuth2ResourceServerConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.baeldung.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpMethod; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; - -@Configuration -@PropertySource({ "classpath:persistence.properties" }) -@EnableResourceServer -public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { - - @Autowired - private Environment env; - - // - - @Override - public void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and() - .requestMatchers().antMatchers("/foos/**","/bars/**") - .and() - .authorizeRequests() - .antMatchers(HttpMethod.GET,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") - .antMatchers(HttpMethod.POST,"/foos/**").access("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") - .antMatchers(HttpMethod.GET,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") - .antMatchers(HttpMethod.POST,"/bars/**").access("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") - ; - // @formatter:on - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - return dataSource; - } - - @Bean - public TokenStore tokenStore() { - return new JdbcTokenStore(dataSource()); - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java deleted file mode 100644 index 1e35eff551..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class ResourceServerApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(ResourceServerApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java deleted file mode 100644 index 81b2d242ac..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -@ComponentScan({ "org.baeldung.web.controller" }) -public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { - // -} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java deleted file mode 100644 index 72163ff9ff..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/BarController.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import org.baeldung.web.dto.Bar; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class BarController { - - public BarController() { - super(); - } - - // API - read - // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") - @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") - @ResponseBody - public Bar findById(@PathVariable final long id) { - return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); - } - - // API - write - // @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") - @RequestMapping(method = RequestMethod.POST, value = "/bars") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Bar create(@RequestBody final Bar bar) { - bar.setId(Long.parseLong(randomNumeric(2))); - return bar; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index d9ef1baa31..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.web.controller; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; - -import org.baeldung.web.dto.Foo; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -@Controller -public class FooController { - - public FooController() { - super(); - } - - // API - read - // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") - @ResponseBody - public Foo findById(@PathVariable final long id) { - return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); - } - - // API - write - // @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") - @RequestMapping(method = RequestMethod.POST, value = "/foos") - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo foo) { - foo.setId(Long.parseLong(randomNumeric(2))); - return foo; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java deleted file mode 100644 index adbb2aa2ad..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Bar.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.dto; - -public class Bar { - private long id; - private String name; - - public Bar() { - super(); - } - - public Bar(final long id, final String name) { - super(); - - this.id = id; - this.name = name; - } - - // - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Foo.java b/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Foo.java deleted file mode 100644 index 9d26618e7f..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/java/org/baeldung/web/dto/Foo.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.web.dto; - -public class Foo { - private long id; - private String name; - - public Foo() { - super(); - } - - public Foo(final long id, final String name) { - super(); - - this.id = id; - this.name = name; - } - - // - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-resource/src/main/resources/application.properties deleted file mode 100644 index 62a10d1751..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-resource -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-resource/src/main/resources/persistence.properties b/spring-security-oauth/spring-security-oauth-resource/src/main/resources/persistence.properties deleted file mode 100644 index b975b10e9f..0000000000 --- a/spring-security-oauth/spring-security-oauth-resource/src/main/resources/persistence.properties +++ /dev/null @@ -1,6 +0,0 @@ -################### DataSource Configuration ########################## -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/oauth2?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - diff --git a/spring-security-oauth/spring-security-oauth-server-demo/.project b/spring-security-oauth/spring-security-oauth-server-demo/.project deleted file mode 100644 index 0ee409f87b..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-security-oauth-server-demo - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-security-oauth/spring-security-oauth-server-demo/.springBeans b/spring-security-oauth/spring-security-oauth-server-demo/.springBeans deleted file mode 100644 index 18656ebe2e..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/.springBeans +++ /dev/null @@ -1,16 +0,0 @@ - - - 1 - - - - - - - java:org.baeldung.config.AuthorizationServerApplication - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-server-demo/pom.xml b/spring-security-oauth/spring-security-oauth-server-demo/pom.xml deleted file mode 100644 index 9ddba9d1b2..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - 4.0.0 - spring-security-oauth-server-demo - - spring-security-oauth-server-demo - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - - org.springframework.security.oauth - spring-security-oauth2 - ${oauth.version} - - - org.springframework.security - spring-security-jwt - - - - - - spring-security-oauth-server-demo - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/AuthorizationServerApplication.java b/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/AuthorizationServerApplication.java deleted file mode 100644 index 73b8fc1976..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/AuthorizationServerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class AuthorizationServerApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(AuthorizationServerApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig1.java b/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig1.java deleted file mode 100644 index 331b4cacf6..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig1.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; - -//@Configuration -//@EnableAuthorizationServer -public class OAuth2AuthorizationServerConfig1 extends AuthorizationServerConfigurerAdapter { - - @Autowired - @Qualifier("authenticationManagerBean") - private AuthenticationManager authenticationManager; - - // - - @Override - public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { - oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); - } - - @Override - public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off - clients.inMemory() - .withClient("fooClientIdPassword") - .secret("secret") - .authorizedGrantTypes("password", "authorization_code") - .scopes("foo", "read", "write") - .accessTokenValiditySeconds(3600) // 1 hour - ; - } // @formatter:on - - @Override - public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager); - } - - @Bean - public TokenStore tokenStore() { - return new InMemoryTokenStore(); - } - -} diff --git a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig2.java b/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig2.java deleted file mode 100644 index 808a2351a0..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig2.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.baeldung.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.token.DefaultTokenServices; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; - -@Configuration -@EnableAuthorizationServer -public class OAuth2AuthorizationServerConfig2 extends AuthorizationServerConfigurerAdapter { - - @Autowired - @Qualifier("authenticationManagerBean") - private AuthenticationManager authenticationManager; - - // - - @Override - public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { - oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); - } - - @Override - public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off - clients.inMemory() - .withClient("fooClientIdPassword") - .secret("secret") - .authorizedGrantTypes("password", "authorization_code" ) - .scopes("foo", "read", "write") - .accessTokenValiditySeconds(3600) // 1 hour - ; - } // @formatter:on - - @Override - public void configure(final AuthorizationServerEndpointsConfigurer conf) { // @formatter:off - conf. - tokenStore(tokenStore()) - .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST) - .accessTokenConverter(accessTokenConverter()) - .authenticationManager(authenticationManager) - ; - } // @formatter:on - - // JWT - - @Bean - @Primary - public DefaultTokenServices tokenServices() { - final DefaultTokenServices tokenServices = new DefaultTokenServices(); - tokenServices.setTokenStore(tokenStore()); - return tokenServices; - } - - @Bean - public TokenStore tokenStore() { - return new JwtTokenStore(accessTokenConverter()); - } - - @Bean - public JwtAccessTokenConverter accessTokenConverter() { - final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); - converter.setSigningKey("123"); - return converter; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/WebSecurityConfig.java b/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/WebSecurityConfig.java deleted file mode 100644 index 63ae10ae03..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/src/main/java/org/baeldung/config/WebSecurityConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception {// @formatter:off - auth.inMemoryAuthentication(). - withUser("john").password("123").roles("USER"). - and(). - withUser("tom").password("111").roles("ADMIN"); - }// @formatter:on - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() - .anyRequest().authenticated() - .and().formLogin().permitAll() - ; - // @formatter:on - } - -} diff --git a/spring-security-oauth/spring-security-oauth-server-demo/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-server-demo/src/main/resources/application.properties deleted file mode 100644 index e33e7dabf6..0000000000 --- a/spring-security-oauth/spring-security-oauth-server-demo/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-server -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/.classpath b/spring-security-oauth/spring-security-oauth-server/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-server/.springBeans b/spring-security-oauth/spring-security-oauth-server/.springBeans deleted file mode 100644 index 18656ebe2e..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/.springBeans +++ /dev/null @@ -1,16 +0,0 @@ - - - 1 - - - - - - - java:org.baeldung.config.AuthorizationServerApplication - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-server/pom.xml b/spring-security-oauth/spring-security-oauth-server/pom.xml deleted file mode 100644 index 3f6e257541..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - 4.0.0 - spring-security-oauth-server - - spring-security-oauth-server - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework - spring-jdbc - - - - mysql - mysql-connector-java - runtime - - - - - org.springframework.security.oauth - spring-security-oauth2 - ${oauth.version} - - - - - - spring-security-oauth-server - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java deleted file mode 100644 index 73b8fc1976..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/AuthorizationServerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class AuthorizationServerApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(AuthorizationServerApplication.class, args); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java deleted file mode 100644 index e8e3408968..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/OAuth2AuthorizationServerConfig.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.baeldung.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.core.io.Resource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.init.DataSourceInitializer; -import org.springframework.jdbc.datasource.init.DatabasePopulator; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; - -@Configuration -@PropertySource({ "classpath:persistence.properties" }) -@EnableAuthorizationServer -public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { - - @Autowired - private Environment env; - - @Autowired - @Qualifier("authenticationManagerBean") - private AuthenticationManager authenticationManager; - - @Value("classpath:schema.sql") - private Resource schemaScript; - - // - - @Override - public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { - oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); - } - - @Override - public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off - clients.jdbc(dataSource()) - .withClient("sampleClientId") - .authorizedGrantTypes("implicit") - .scopes("read","write","foo","bar") - .autoApprove(false) - .accessTokenValiditySeconds(3600) - - .and() - .withClient("fooClientIdPassword") - .secret("secret") - .authorizedGrantTypes("password","authorization_code", "refresh_token") - .scopes("foo","read","write") - .accessTokenValiditySeconds(15) // 1 hour - .refreshTokenValiditySeconds(2592000) // 30 days - - .and() - .withClient("barClientIdPassword") - .secret("secret") - .authorizedGrantTypes("password","authorization_code", "refresh_token") - .scopes("bar","read","write") - .accessTokenValiditySeconds(3600) // 1 hour - .refreshTokenValiditySeconds(2592000) // 30 days - ; - } // @formatter:on - - @Override - public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager); - } - - @Bean - public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { - final DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); - initializer.setDatabasePopulator(databasePopulator()); - return initializer; - } - - private DatabasePopulator databasePopulator() { - final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); - populator.addScript(schemaScript); - return populator; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - return dataSource; - } - - @Bean - public TokenStore tokenStore() { - return new JdbcTokenStore(dataSource()); - } - -} diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java b/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java deleted file mode 100644 index 63ae10ae03..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/java/org/baeldung/config/WebSecurityConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception {// @formatter:off - auth.inMemoryAuthentication(). - withUser("john").password("123").roles("USER"). - and(). - withUser("tom").password("111").roles("ADMIN"); - }// @formatter:on - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() - .anyRequest().authenticated() - .and().formLogin().permitAll() - ; - // @formatter:on - } - -} diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-server/src/main/resources/application.properties deleted file mode 100644 index e33e7dabf6..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-server -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/resources/persistence.properties b/spring-security-oauth/spring-security-oauth-server/src/main/resources/persistence.properties deleted file mode 100644 index b975b10e9f..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/resources/persistence.properties +++ /dev/null @@ -1,6 +0,0 @@ -################### DataSource Configuration ########################## -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/oauth2?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - diff --git a/spring-security-oauth/spring-security-oauth-server/src/main/resources/schema.sql b/spring-security-oauth/spring-security-oauth-server/src/main/resources/schema.sql deleted file mode 100644 index 98e67ad24e..0000000000 --- a/spring-security-oauth/spring-security-oauth-server/src/main/resources/schema.sql +++ /dev/null @@ -1,65 +0,0 @@ -drop table if exists oauth_client_details; -create table oauth_client_details ( - client_id VARCHAR(255) PRIMARY KEY, - resource_ids VARCHAR(255), - client_secret VARCHAR(255), - scope VARCHAR(255), - authorized_grant_types VARCHAR(255), - web_server_redirect_uri VARCHAR(255), - authorities VARCHAR(255), - access_token_validity INTEGER, - refresh_token_validity INTEGER, - additional_information VARCHAR(4096), - autoapprove VARCHAR(255) -); - -create table if not exists oauth_client_token ( - token_id VARCHAR(255), - token LONG VARBINARY, - authentication_id VARCHAR(255) PRIMARY KEY, - user_name VARCHAR(255), - client_id VARCHAR(255) -); - -create table if not exists oauth_access_token ( - token_id VARCHAR(255), - token LONG VARBINARY, - authentication_id VARCHAR(255) PRIMARY KEY, - user_name VARCHAR(255), - client_id VARCHAR(255), - authentication LONG VARBINARY, - refresh_token VARCHAR(255) -); - -create table if not exists oauth_refresh_token ( - token_id VARCHAR(255), - token LONG VARBINARY, - authentication LONG VARBINARY -); - -create table if not exists oauth_code ( - code VARCHAR(255), authentication LONG VARBINARY -); - -create table if not exists oauth_approvals ( - userId VARCHAR(255), - clientId VARCHAR(255), - scope VARCHAR(255), - status VARCHAR(10), - expiresAt TIMESTAMP, - lastModifiedAt TIMESTAMP -); - -create table if not exists ClientDetails ( - appId VARCHAR(255) PRIMARY KEY, - resourceIds VARCHAR(255), - appSecret VARCHAR(255), - scope VARCHAR(255), - grantTypes VARCHAR(255), - redirectUrl VARCHAR(255), - authorities VARCHAR(255), - access_token_validity INTEGER, - refresh_token_validity INTEGER, - additionalInformation VARCHAR(4096), - autoApproveScopes VARCHAR(255) -); diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/.classpath b/spring-security-oauth/spring-security-oauth-ui-implicit/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/.project b/spring-security-oauth/spring-security-oauth-ui-implicit/.project deleted file mode 100644 index b96a26c60d..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/.project +++ /dev/null @@ -1,53 +0,0 @@ - - - spring-security-oauth-ui-implicit - - - - - - org.eclipse.ui.externaltools.ExternalToolBuilder - full,incremental, - - - LaunchConfigHandle - <project>/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator (1).launch - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/pom.xml b/spring-security-oauth/spring-security-oauth-ui-implicit/pom.xml deleted file mode 100644 index aaa2900d48..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - 4.0.0 - spring-security-oauth-ui-implicit - - spring-security-oauth-ui-implicit - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - - spring-security-oauth-ui-implicit - - - src/main/resources - true - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiApplication.java deleted file mode 100644 index 8f491516aa..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; - -@SpringBootApplication -public class UiApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(UiApplication.class, args); - } -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java deleted file mode 100644 index 71197ce5d2..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/java/org/baeldung/config/UiWebConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -public class UiWebConfig extends WebMvcConfigurerAdapter { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/oauthTemp"); - registry.addViewController("/index"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/application.properties deleted file mode 100644 index 33de0adb88..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -server.contextPath=/spring-security-oauth-ui-implicit -server.port=8081 \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/oauth-ng.js b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/oauth-ng.js deleted file mode 100644 index 333070b935..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/oauth-ng.js +++ /dev/null @@ -1,539 +0,0 @@ -/* oauth-ng - v0.4.2 - 2015-08-27 */ - -'use strict'; - -// App libraries -angular.module('oauth', [ - 'oauth.directive', // login directive - 'oauth.accessToken', // access token service - 'oauth.endpoint', // oauth endpoint service - 'oauth.profile', // profile model - 'oauth.storage', // storage - 'oauth.interceptor', // bearer token interceptor - 'oauth.configuration' // token appender -]) - .config(['$locationProvider','$httpProvider', - function($locationProvider, $httpProvider) { - $httpProvider.interceptors.push('ExpiredInterceptor'); - }]); - -'use strict'; - -var accessTokenService = angular.module('oauth.accessToken', []); - -accessTokenService.factory('AccessToken', ['Storage', '$rootScope', '$location', '$interval', function(Storage, $rootScope, $location, $interval){ - - var service = { - token: null - }, - oAuth2HashTokens = [ //per http://tools.ietf.org/html/rfc6749#section-4.2.2 - 'access_token', 'token_type', 'expires_in', 'scope', 'state', - 'error','error_description' - ]; - - /** - * Returns the access token. - */ - service.get = function(){ - return this.token; - }; - - /** - * Sets and returns the access token. It tries (in order) the following strategies: - * - takes the token from the fragment URI - * - takes the token from the sessionStorage - */ - service.set = function(){ - this.setTokenFromString($location.hash()); - - //If hash is present in URL always use it, cuz its coming from oAuth2 provider redirect - if(null === service.token){ - setTokenFromSession(); - } - - return this.token; - }; - - /** - * Delete the access token and remove the session. - * @returns {null} - */ - service.destroy = function(){ - Storage.delete('token'); - this.token = null; - return this.token; - }; - - /** - * Tells if the access token is expired. - */ - service.expired = function(){ - return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date()); - }; - - /** - * Get the access token from a string and save it - * @param hash - */ - service.setTokenFromString = function(hash){ - var params = getTokenFromString(hash); - - if(params){ - removeFragment(); - setToken(params); - setExpiresAt(); - // We have to save it again to make sure expires_at is set - // and the expiry event is set up properly - setToken(this.token); - $rootScope.$broadcast('oauth:login', service.token); - } - }; - - /* * * * * * * * * * - * PRIVATE METHODS * - * * * * * * * * * */ - - /** - * Set the access token from the sessionStorage. - */ - var setTokenFromSession = function(){ - var params = Storage.get('token'); - if (params) { - setToken(params); - } - }; - - /** - * Set the access token. - * - * @param params - * @returns {*|{}} - */ - var setToken = function(params){ - service.token = service.token || {}; // init the token - angular.extend(service.token, params); // set the access token params - setTokenInSession(); // save the token into the session - setExpiresAtEvent(); // event to fire when the token expires - - return service.token; - }; - - /** - * Parse the fragment URI and return an object - * @param hash - * @returns {{}} - */ - var getTokenFromString = function(hash){ - var params = {}, - regex = /([^&=]+)=([^&]*)/g, - m; - - while ((m = regex.exec(hash)) !== null) { - params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); - } - - if(params.access_token || params.error){ - return params; - } - }; - - /** - * Save the access token into the session - */ - var setTokenInSession = function(){ - Storage.set('token', service.token); - }; - - /** - * Set the access token expiration date (useful for refresh logics) - */ - var setExpiresAt = function(){ - if (!service.token) { - return; - } - if(typeof(service.token.expires_in) !== 'undefined' && service.token.expires_in !== null) { - var expires_at = new Date(); - expires_at.setSeconds(expires_at.getSeconds() + parseInt(service.token.expires_in)-60); // 60 seconds less to secure browser and response latency - service.token.expires_at = expires_at; - } - else { - service.token.expires_at = null; - } - }; - - - /** - * Set the timeout at which the expired event is fired - */ - var setExpiresAtEvent = function(){ - // Don't bother if there's no expires token - if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) { - return; - } - var time = (new Date(service.token.expires_at))-(new Date()); - if(time && time > 0){ - $interval(function(){ - $rootScope.$broadcast('oauth:expired', service.token); - }, time, 1); - } - }; - - /** - * Remove the oAuth2 pieces from the hash fragment - */ - var removeFragment = function(){ - var curHash = $location.hash(); - angular.forEach(oAuth2HashTokens,function(hashKey){ - var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?'); - curHash = curHash.replace(re,''); - }); - - $location.hash(curHash); - }; - - return service; - -}]); - -'use strict'; - -var endpointClient = angular.module('oauth.endpoint', []); - -endpointClient.factory('Endpoint', function() { - - var service = {}; - - /* - * Defines the authorization URL - */ - - service.set = function(configuration) { - this.config = configuration; - return this.get(); - }; - - /* - * Returns the authorization URL - */ - - service.get = function( overrides ) { - var params = angular.extend( {}, service.config, overrides); - var oAuthScope = (params.scope) ? encodeURIComponent(params.scope) : '', - state = (params.state) ? encodeURIComponent(params.state) : '', - authPathHasQuery = (params.authorizePath.indexOf('?') === -1) ? false : true, - appendChar = (authPathHasQuery) ? '&' : '?', //if authorizePath has ? already append OAuth2 params - responseType = (params.responseType) ? encodeURIComponent(params.responseType) : ''; - - var url = params.site + - params.authorizePath + - appendChar + 'response_type=' + responseType + '&' + - 'client_id=' + encodeURIComponent(params.clientId) + '&' + - 'redirect_uri=' + encodeURIComponent(params.redirectUri) + '&' + - 'scope=' + oAuthScope + '&' + - 'state=' + state; - - if( params.nonce ) { - url = url + '&nonce=' + params.nonce; - } - return url; - }; - - /* - * Redirects the app to the authorization URL - */ - - service.redirect = function( overrides ) { - var targetLocation = this.get( overrides ); - window.location.replace(targetLocation); - }; - - return service; -}); - -'use strict'; - -var profileClient = angular.module('oauth.profile', []); - -profileClient.factory('Profile', ['$http', 'AccessToken', '$rootScope', function($http, AccessToken, $rootScope) { - var service = {}; - var profile; - - service.find = function(uri) { - var promise = $http.get(uri, { headers: headers() }); - promise.success(function(response) { - profile = response; - $rootScope.$broadcast('oauth:profile', profile); - }); - return promise; - }; - - service.get = function() { - return profile; - }; - - service.set = function(resource) { - profile = resource; - return profile; - }; - - var headers = function() { - return { Authorization: 'Bearer ' + AccessToken.get().access_token }; - }; - - return service; -}]); - -'use strict'; - -var storageService = angular.module('oauth.storage', ['ngStorage']); - -storageService.factory('Storage', ['$rootScope', '$sessionStorage', '$localStorage', function($rootScope, $sessionStorage, $localStorage){ - - var service = { - storage: $sessionStorage // By default - }; - - /** - * Deletes the item from storage, - * Returns the item's previous value - */ - service.delete = function (name) { - var stored = this.get(name); - delete this.storage[name]; - return stored; - }; - - /** - * Returns the item from storage - */ - service.get = function (name) { - return this.storage[name]; - }; - - /** - * Sets the item in storage to the value specified - * Returns the item's value - */ - service.set = function (name, value) { - this.storage[name] = value; - return this.get(name); - }; - - /** - * Change the storage service being used - */ - service.use = function (storage) { - if (storage === 'sessionStorage') { - this.storage = $sessionStorage; - } else if (storage === 'localStorage') { - this.storage = $localStorage; - } - }; - - return service; -}]); -'use strict'; - -var oauthConfigurationService = angular.module('oauth.configuration', []); - -oauthConfigurationService.provider('OAuthConfiguration', function() { - var _config = {}; - - this.init = function(config, httpProvider) { - _config.protectedResources = config.protectedResources || []; - httpProvider.interceptors.push('AuthInterceptor'); - }; - - this.$get = function() { - return { - getConfig: function() { - return _config; - } - }; - }; -}) -.factory('AuthInterceptor', function($q, $rootScope, OAuthConfiguration, AccessToken) { - return { - 'request': function(config) { - OAuthConfiguration.getConfig().protectedResources.forEach(function(resource) { - // If the url is one of the protected resources, we want to see if there's a token and then - // add the token if it exists. - if (config.url.indexOf(resource) > -1) { - var token = AccessToken.get(); - if (token) { - config.headers.Authorization = 'Bearer ' + token.access_token; - } - } - }); - - return config; - } - }; -}); -'use strict'; - -var interceptorService = angular.module('oauth.interceptor', []); - -interceptorService.factory('ExpiredInterceptor', ['Storage', '$rootScope', function (Storage, $rootScope) { - - var service = {}; - - service.request = function(config) { - var token = Storage.get('token'); - - if (token && expired(token)) { - $rootScope.$broadcast('oauth:expired', token); - } - - return config; - }; - - var expired = function(token) { - return (token && token.expires_at && new Date(token.expires_at) < new Date()); - }; - - return service; -}]); - -'use strict'; - -var directives = angular.module('oauth.directive', []); - -directives.directive('oauth', [ - 'AccessToken', - 'Endpoint', - 'Profile', - 'Storage', - '$location', - '$rootScope', - '$compile', - '$http', - '$templateCache', - function(AccessToken, Endpoint, Profile, Storage, $location, $rootScope, $compile, $http, $templateCache) { - - var definition = { - restrict: 'AE', - replace: true, - scope: { - site: '@', // (required) set the oauth server host (e.g. http://oauth.example.com) - clientId: '@', // (required) client id - redirectUri: '@', // (required) client redirect uri - responseType: '@', // (optional) response type, defaults to token (use 'token' for implicit flow and 'code' for authorization code flow - scope: '@', // (optional) scope - profileUri: '@', // (optional) user profile uri (e.g http://example.com/me) - template: '@', // (optional) template to render (e.g bower_components/oauth-ng/dist/views/templates/default.html) - text: '@', // (optional) login text - authorizePath: '@', // (optional) authorization url - state: '@', // (optional) An arbitrary unique string created by your app to guard against Cross-site Request Forgery - storage: '@' // (optional) Store token in 'sessionStorage' or 'localStorage', defaults to 'sessionStorage' - } - }; - - definition.link = function postLink(scope, element) { - scope.show = 'none'; - - scope.$watch('clientId', function() { - init(); - }); - - var init = function() { - initAttributes(); // sets defaults - Storage.use(scope.storage);// set storage - compile(); // compiles the desired layout - Endpoint.set(scope); // sets the oauth authorization url - AccessToken.set(scope); // sets the access token object (if existing, from fragment or session) - initProfile(scope); // gets the profile resource (if existing the access token) - initView(); // sets the view (logged in or out) - }; - - var initAttributes = function() { - scope.authorizePath = scope.authorizePath || '/oauth/authorize'; - scope.tokenPath = scope.tokenPath || '/oauth/token'; - scope.template = scope.template || 'bower_components/oauth-ng/dist/views/templates/default.html'; - scope.responseType = scope.responseType || 'token'; - scope.text = scope.text || 'Sign In'; - scope.state = scope.state || undefined; - scope.scope = scope.scope || undefined; - scope.storage = scope.storage || 'sessionStorage'; - }; - - var compile = function() { - $http.get(scope.template, { cache: $templateCache }).success(function(html) { - element.html(html); - $compile(element.contents())(scope); - }); - }; - - var initProfile = function(scope) { - var token = AccessToken.get(); - - if (token && token.access_token && scope.profileUri) { - Profile.find(scope.profileUri).success(function(response) { - scope.profile = response; - }); - } - }; - - var initView = function() { - var token = AccessToken.get(); - - if (!token) { - return loggedOut(); // without access token it's logged out - } - if (token.access_token) { - return authorized(); // if there is the access token we are done - } - if (token.error) { - return denied(); // if the request has been denied we fire the denied event - } - }; - - scope.login = function() { - Endpoint.redirect(); - }; - - scope.logout = function() { - AccessToken.destroy(scope); - $rootScope.$broadcast('oauth:logout'); - loggedOut(); - }; - - scope.$on('oauth:expired', function() { - AccessToken.destroy(scope); - scope.show = 'logged-out'; - }); - - // user is authorized - var authorized = function() { - $rootScope.$broadcast('oauth:authorized', AccessToken.get()); - scope.show = 'logged-in'; - }; - - // set the oauth directive to the logged-out status - var loggedOut = function() { - $rootScope.$broadcast('oauth:loggedOut'); - scope.show = 'logged-out'; - }; - - // set the oauth directive to the denied status - var denied = function() { - scope.show = 'denied'; - $rootScope.$broadcast('oauth:denied'); - }; - - // Updates the template at runtime - scope.$on('oauth:template:update', function(event, template) { - scope.template = template; - compile(scope); - }); - - // Hack to update the directive content on logout - // TODO think to a cleaner solution - scope.$on('$routeChangeSuccess', function () { - init(); - }); - }; - - return definition; - } -]); diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html deleted file mode 100644 index aa891bc289..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/header.html +++ /dev/null @@ -1,101 +0,0 @@ -
- - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html deleted file mode 100755 index 2996af04f0..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/index.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - -Spring Security OAuth - - - - -
- -
-
{{message}}
-

Foo Details

-
-
- - -
- -
- - -
- - -
- -
-
-
-
-
-

Bar Details

-
-
- - -
- -
- - -
- - -
- - -
- - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/oauthTemp.html b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/oauthTemp.html deleted file mode 100644 index 1efc1eed3c..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/resources/templates/oauthTemp.html +++ /dev/null @@ -1,6 +0,0 @@ - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/webapp/resources/oauth-ng.js b/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/webapp/resources/oauth-ng.js deleted file mode 100644 index 333070b935..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-implicit/src/main/webapp/resources/oauth-ng.js +++ /dev/null @@ -1,539 +0,0 @@ -/* oauth-ng - v0.4.2 - 2015-08-27 */ - -'use strict'; - -// App libraries -angular.module('oauth', [ - 'oauth.directive', // login directive - 'oauth.accessToken', // access token service - 'oauth.endpoint', // oauth endpoint service - 'oauth.profile', // profile model - 'oauth.storage', // storage - 'oauth.interceptor', // bearer token interceptor - 'oauth.configuration' // token appender -]) - .config(['$locationProvider','$httpProvider', - function($locationProvider, $httpProvider) { - $httpProvider.interceptors.push('ExpiredInterceptor'); - }]); - -'use strict'; - -var accessTokenService = angular.module('oauth.accessToken', []); - -accessTokenService.factory('AccessToken', ['Storage', '$rootScope', '$location', '$interval', function(Storage, $rootScope, $location, $interval){ - - var service = { - token: null - }, - oAuth2HashTokens = [ //per http://tools.ietf.org/html/rfc6749#section-4.2.2 - 'access_token', 'token_type', 'expires_in', 'scope', 'state', - 'error','error_description' - ]; - - /** - * Returns the access token. - */ - service.get = function(){ - return this.token; - }; - - /** - * Sets and returns the access token. It tries (in order) the following strategies: - * - takes the token from the fragment URI - * - takes the token from the sessionStorage - */ - service.set = function(){ - this.setTokenFromString($location.hash()); - - //If hash is present in URL always use it, cuz its coming from oAuth2 provider redirect - if(null === service.token){ - setTokenFromSession(); - } - - return this.token; - }; - - /** - * Delete the access token and remove the session. - * @returns {null} - */ - service.destroy = function(){ - Storage.delete('token'); - this.token = null; - return this.token; - }; - - /** - * Tells if the access token is expired. - */ - service.expired = function(){ - return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date()); - }; - - /** - * Get the access token from a string and save it - * @param hash - */ - service.setTokenFromString = function(hash){ - var params = getTokenFromString(hash); - - if(params){ - removeFragment(); - setToken(params); - setExpiresAt(); - // We have to save it again to make sure expires_at is set - // and the expiry event is set up properly - setToken(this.token); - $rootScope.$broadcast('oauth:login', service.token); - } - }; - - /* * * * * * * * * * - * PRIVATE METHODS * - * * * * * * * * * */ - - /** - * Set the access token from the sessionStorage. - */ - var setTokenFromSession = function(){ - var params = Storage.get('token'); - if (params) { - setToken(params); - } - }; - - /** - * Set the access token. - * - * @param params - * @returns {*|{}} - */ - var setToken = function(params){ - service.token = service.token || {}; // init the token - angular.extend(service.token, params); // set the access token params - setTokenInSession(); // save the token into the session - setExpiresAtEvent(); // event to fire when the token expires - - return service.token; - }; - - /** - * Parse the fragment URI and return an object - * @param hash - * @returns {{}} - */ - var getTokenFromString = function(hash){ - var params = {}, - regex = /([^&=]+)=([^&]*)/g, - m; - - while ((m = regex.exec(hash)) !== null) { - params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); - } - - if(params.access_token || params.error){ - return params; - } - }; - - /** - * Save the access token into the session - */ - var setTokenInSession = function(){ - Storage.set('token', service.token); - }; - - /** - * Set the access token expiration date (useful for refresh logics) - */ - var setExpiresAt = function(){ - if (!service.token) { - return; - } - if(typeof(service.token.expires_in) !== 'undefined' && service.token.expires_in !== null) { - var expires_at = new Date(); - expires_at.setSeconds(expires_at.getSeconds() + parseInt(service.token.expires_in)-60); // 60 seconds less to secure browser and response latency - service.token.expires_at = expires_at; - } - else { - service.token.expires_at = null; - } - }; - - - /** - * Set the timeout at which the expired event is fired - */ - var setExpiresAtEvent = function(){ - // Don't bother if there's no expires token - if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) { - return; - } - var time = (new Date(service.token.expires_at))-(new Date()); - if(time && time > 0){ - $interval(function(){ - $rootScope.$broadcast('oauth:expired', service.token); - }, time, 1); - } - }; - - /** - * Remove the oAuth2 pieces from the hash fragment - */ - var removeFragment = function(){ - var curHash = $location.hash(); - angular.forEach(oAuth2HashTokens,function(hashKey){ - var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?'); - curHash = curHash.replace(re,''); - }); - - $location.hash(curHash); - }; - - return service; - -}]); - -'use strict'; - -var endpointClient = angular.module('oauth.endpoint', []); - -endpointClient.factory('Endpoint', function() { - - var service = {}; - - /* - * Defines the authorization URL - */ - - service.set = function(configuration) { - this.config = configuration; - return this.get(); - }; - - /* - * Returns the authorization URL - */ - - service.get = function( overrides ) { - var params = angular.extend( {}, service.config, overrides); - var oAuthScope = (params.scope) ? encodeURIComponent(params.scope) : '', - state = (params.state) ? encodeURIComponent(params.state) : '', - authPathHasQuery = (params.authorizePath.indexOf('?') === -1) ? false : true, - appendChar = (authPathHasQuery) ? '&' : '?', //if authorizePath has ? already append OAuth2 params - responseType = (params.responseType) ? encodeURIComponent(params.responseType) : ''; - - var url = params.site + - params.authorizePath + - appendChar + 'response_type=' + responseType + '&' + - 'client_id=' + encodeURIComponent(params.clientId) + '&' + - 'redirect_uri=' + encodeURIComponent(params.redirectUri) + '&' + - 'scope=' + oAuthScope + '&' + - 'state=' + state; - - if( params.nonce ) { - url = url + '&nonce=' + params.nonce; - } - return url; - }; - - /* - * Redirects the app to the authorization URL - */ - - service.redirect = function( overrides ) { - var targetLocation = this.get( overrides ); - window.location.replace(targetLocation); - }; - - return service; -}); - -'use strict'; - -var profileClient = angular.module('oauth.profile', []); - -profileClient.factory('Profile', ['$http', 'AccessToken', '$rootScope', function($http, AccessToken, $rootScope) { - var service = {}; - var profile; - - service.find = function(uri) { - var promise = $http.get(uri, { headers: headers() }); - promise.success(function(response) { - profile = response; - $rootScope.$broadcast('oauth:profile', profile); - }); - return promise; - }; - - service.get = function() { - return profile; - }; - - service.set = function(resource) { - profile = resource; - return profile; - }; - - var headers = function() { - return { Authorization: 'Bearer ' + AccessToken.get().access_token }; - }; - - return service; -}]); - -'use strict'; - -var storageService = angular.module('oauth.storage', ['ngStorage']); - -storageService.factory('Storage', ['$rootScope', '$sessionStorage', '$localStorage', function($rootScope, $sessionStorage, $localStorage){ - - var service = { - storage: $sessionStorage // By default - }; - - /** - * Deletes the item from storage, - * Returns the item's previous value - */ - service.delete = function (name) { - var stored = this.get(name); - delete this.storage[name]; - return stored; - }; - - /** - * Returns the item from storage - */ - service.get = function (name) { - return this.storage[name]; - }; - - /** - * Sets the item in storage to the value specified - * Returns the item's value - */ - service.set = function (name, value) { - this.storage[name] = value; - return this.get(name); - }; - - /** - * Change the storage service being used - */ - service.use = function (storage) { - if (storage === 'sessionStorage') { - this.storage = $sessionStorage; - } else if (storage === 'localStorage') { - this.storage = $localStorage; - } - }; - - return service; -}]); -'use strict'; - -var oauthConfigurationService = angular.module('oauth.configuration', []); - -oauthConfigurationService.provider('OAuthConfiguration', function() { - var _config = {}; - - this.init = function(config, httpProvider) { - _config.protectedResources = config.protectedResources || []; - httpProvider.interceptors.push('AuthInterceptor'); - }; - - this.$get = function() { - return { - getConfig: function() { - return _config; - } - }; - }; -}) -.factory('AuthInterceptor', function($q, $rootScope, OAuthConfiguration, AccessToken) { - return { - 'request': function(config) { - OAuthConfiguration.getConfig().protectedResources.forEach(function(resource) { - // If the url is one of the protected resources, we want to see if there's a token and then - // add the token if it exists. - if (config.url.indexOf(resource) > -1) { - var token = AccessToken.get(); - if (token) { - config.headers.Authorization = 'Bearer ' + token.access_token; - } - } - }); - - return config; - } - }; -}); -'use strict'; - -var interceptorService = angular.module('oauth.interceptor', []); - -interceptorService.factory('ExpiredInterceptor', ['Storage', '$rootScope', function (Storage, $rootScope) { - - var service = {}; - - service.request = function(config) { - var token = Storage.get('token'); - - if (token && expired(token)) { - $rootScope.$broadcast('oauth:expired', token); - } - - return config; - }; - - var expired = function(token) { - return (token && token.expires_at && new Date(token.expires_at) < new Date()); - }; - - return service; -}]); - -'use strict'; - -var directives = angular.module('oauth.directive', []); - -directives.directive('oauth', [ - 'AccessToken', - 'Endpoint', - 'Profile', - 'Storage', - '$location', - '$rootScope', - '$compile', - '$http', - '$templateCache', - function(AccessToken, Endpoint, Profile, Storage, $location, $rootScope, $compile, $http, $templateCache) { - - var definition = { - restrict: 'AE', - replace: true, - scope: { - site: '@', // (required) set the oauth server host (e.g. http://oauth.example.com) - clientId: '@', // (required) client id - redirectUri: '@', // (required) client redirect uri - responseType: '@', // (optional) response type, defaults to token (use 'token' for implicit flow and 'code' for authorization code flow - scope: '@', // (optional) scope - profileUri: '@', // (optional) user profile uri (e.g http://example.com/me) - template: '@', // (optional) template to render (e.g bower_components/oauth-ng/dist/views/templates/default.html) - text: '@', // (optional) login text - authorizePath: '@', // (optional) authorization url - state: '@', // (optional) An arbitrary unique string created by your app to guard against Cross-site Request Forgery - storage: '@' // (optional) Store token in 'sessionStorage' or 'localStorage', defaults to 'sessionStorage' - } - }; - - definition.link = function postLink(scope, element) { - scope.show = 'none'; - - scope.$watch('clientId', function() { - init(); - }); - - var init = function() { - initAttributes(); // sets defaults - Storage.use(scope.storage);// set storage - compile(); // compiles the desired layout - Endpoint.set(scope); // sets the oauth authorization url - AccessToken.set(scope); // sets the access token object (if existing, from fragment or session) - initProfile(scope); // gets the profile resource (if existing the access token) - initView(); // sets the view (logged in or out) - }; - - var initAttributes = function() { - scope.authorizePath = scope.authorizePath || '/oauth/authorize'; - scope.tokenPath = scope.tokenPath || '/oauth/token'; - scope.template = scope.template || 'bower_components/oauth-ng/dist/views/templates/default.html'; - scope.responseType = scope.responseType || 'token'; - scope.text = scope.text || 'Sign In'; - scope.state = scope.state || undefined; - scope.scope = scope.scope || undefined; - scope.storage = scope.storage || 'sessionStorage'; - }; - - var compile = function() { - $http.get(scope.template, { cache: $templateCache }).success(function(html) { - element.html(html); - $compile(element.contents())(scope); - }); - }; - - var initProfile = function(scope) { - var token = AccessToken.get(); - - if (token && token.access_token && scope.profileUri) { - Profile.find(scope.profileUri).success(function(response) { - scope.profile = response; - }); - } - }; - - var initView = function() { - var token = AccessToken.get(); - - if (!token) { - return loggedOut(); // without access token it's logged out - } - if (token.access_token) { - return authorized(); // if there is the access token we are done - } - if (token.error) { - return denied(); // if the request has been denied we fire the denied event - } - }; - - scope.login = function() { - Endpoint.redirect(); - }; - - scope.logout = function() { - AccessToken.destroy(scope); - $rootScope.$broadcast('oauth:logout'); - loggedOut(); - }; - - scope.$on('oauth:expired', function() { - AccessToken.destroy(scope); - scope.show = 'logged-out'; - }); - - // user is authorized - var authorized = function() { - $rootScope.$broadcast('oauth:authorized', AccessToken.get()); - scope.show = 'logged-in'; - }; - - // set the oauth directive to the logged-out status - var loggedOut = function() { - $rootScope.$broadcast('oauth:loggedOut'); - scope.show = 'logged-out'; - }; - - // set the oauth directive to the denied status - var denied = function() { - scope.show = 'denied'; - $rootScope.$broadcast('oauth:denied'); - }; - - // Updates the template at runtime - scope.$on('oauth:template:update', function(event, template) { - scope.template = template; - compile(scope); - }); - - // Hack to update the directive content on logout - // TODO think to a cleaner solution - scope.$on('$routeChangeSuccess', function () { - init(); - }); - }; - - return definition; - } -]); diff --git a/spring-security-oauth/spring-security-oauth-ui-password/.classpath b/spring-security-oauth/spring-security-oauth-ui-password/.classpath deleted file mode 100644 index 0cad5db2d0..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-security-oauth/spring-security-oauth-ui-password/.project b/spring-security-oauth/spring-security-oauth-ui-password/.project deleted file mode 100644 index 58d50a3f3a..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-security-oauth-ui-password - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.springframework.ide.eclipse.core.springnature - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml b/spring-security-oauth/spring-security-oauth-ui-password/pom.xml deleted file mode 100644 index e8b2aa3d0d..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - 4.0.0 - spring-security-oauth-ui-password - - spring-security-oauth-ui-password - war - - - org.baeldung - spring-security-oauth - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - org.springframework.cloud - spring-cloud-starter-zuul - 1.0.4.RELEASE - - - - - - - org.springframework - spring-test - test - - - - junit - junit - test - - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - - com.jayway.restassured - rest-assured - ${rest-assured.version} - test - - - commons-logging - commons-logging - - - - - - - - spring-security-oauth-ui-password - - - src/main/resources - true - - - - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomHttpServletRequest.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomHttpServletRequest.java deleted file mode 100644 index c90f60a357..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomHttpServletRequest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.config; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - -public class CustomHttpServletRequest extends HttpServletRequestWrapper { - private final Map additionalParams; - private final HttpServletRequest request; - - public CustomHttpServletRequest(final HttpServletRequest request, final Map additionalParams) { - super(request); - this.request = request; - this.additionalParams = additionalParams; - } - - @Override - public Map getParameterMap() { - final Map map = request.getParameterMap(); - final Map param = new HashMap(); - param.putAll(map); - param.putAll(additionalParams); - return param; - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java deleted file mode 100644 index 333cc177f2..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPostZuulFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.baeldung.config; - -import java.io.InputStream; - -import javax.servlet.http.Cookie; - -import org.apache.commons.io.IOUtils; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.map.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -@Component -public class CustomPostZuulFilter extends ZuulFilter { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final ObjectMapper mapper = new ObjectMapper(); - - @Override - public Object run() { - final RequestContext ctx = RequestContext.getCurrentContext(); - logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); - - JsonNode json; - try { - final InputStream is = ctx.getResponseDataStream(); - final String responseBody = IOUtils.toString(is, "UTF-8"); - - ctx.setResponseBody(responseBody); - - if (responseBody.contains("refresh_token")) { - json = mapper.readTree(responseBody); - final String refreshToken = json.get("refresh_token").getTextValue(); - final Cookie cookie = new Cookie("refreshToken", refreshToken); - cookie.setHttpOnly(true); - // cookie.setSecure(true); - cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token"); - cookie.setMaxAge(2592000); // 30 days - ctx.getResponse().addCookie(cookie); - - logger.info("refresh token = " + refreshToken); - } - } catch (final Exception e) { - logger.error("Error occured in zuul post filter", e); - } - - return null; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public int filterOrder() { - return 10; - } - - @Override - public String filterType() { - return "post"; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java deleted file mode 100644 index a97a427510..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/CustomPreZuulFilter.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.baeldung.config; - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.crypto.codec.Base64; -import org.springframework.stereotype.Component; - -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -@Component -public class CustomPreZuulFilter extends ZuulFilter { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public Object run() { - final RequestContext ctx = RequestContext.getCurrentContext(); - logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); - byte[] encoded; - try { - encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8")); - ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded)); - logger.info("pre filter"); - logger.info(ctx.getRequest().getHeader("Authorization")); - - // - final HttpServletRequest req = ctx.getRequest(); - - final String refreshToken = extractRefreshToken(req); - if (refreshToken != null) { - final Map param = new HashMap(); - param.put("refresh_token", new String[] { refreshToken }); - param.put("grant_type", new String[] { "refresh_token" }); - - ctx.setRequest(new CustomHttpServletRequest(req, param)); - } - - } catch (final UnsupportedEncodingException e) { - logger.error("Error occured in pre filter", e); - } - - // - - return null; - } - - private String extractRefreshToken(HttpServletRequest req) { - final Cookie[] cookies = req.getCookies(); - if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equalsIgnoreCase("refreshToken")) { - return cookies[i].getValue(); - } - } - } - return null; - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public int filterOrder() { - return -2; - } - - @Override - public String filterType() { - return "pre"; - } - -} diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java deleted file mode 100644 index 60c92d9eef..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.config; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.web.SpringBootServletInitializer; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; - -@EnableZuulProxy -@SpringBootApplication -public class UiApplication extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(UiApplication.class, args); - } -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java deleted file mode 100644 index 0732182354..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiWebConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -public class UiWebConfig extends WebMvcConfigurerAdapter { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Override - public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/").setViewName("forward:/index"); - registry.addViewController("/index"); - registry.addViewController("/login"); - } - - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } - -} \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties deleted file mode 100644 index 9e3565dc2a..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -zuul.Servlet30WrapperFilter.pre.disable=true \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml deleted file mode 100644 index 285796f607..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.yml +++ /dev/null @@ -1,7 +0,0 @@ -server: - port: 8081 -zuul: - routes: - oauth: - path: /oauth/** - url: http://localhost:8081/spring-security-oauth-server/oauth \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html deleted file mode 100644 index 616cbff228..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html +++ /dev/null @@ -1,76 +0,0 @@ -
- - - - - - - - - - - -
\ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/index.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/index.html deleted file mode 100755 index e2458c2940..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/index.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - -Spring Security OAuth - - - - -
- -
-

Foo Details

-
- - {{foo.id}} -
- -
- -{{foo.name}} -
- - - -
- - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html b/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html deleted file mode 100755 index e1e6e3e6e0..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - -Spring Security OAuth - - - - -
- -
- -

Login

-
-
- - -
- -
- - -
- -
-Login - -
- -
- -
- - \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/main/webapp/resources/angular-utf8-base64.min.js b/spring-security-oauth/spring-security-oauth-ui-password/src/main/webapp/resources/angular-utf8-base64.min.js deleted file mode 100644 index 24af57d020..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/main/webapp/resources/angular-utf8-base64.min.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";angular.module("ab-base64",[]).constant("base64",function(){var a={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",lookup:null,ie:/MSIE /.test(navigator.userAgent),ieo:/MSIE [67]/.test(navigator.userAgent),encode:function(b){var c,d,e,f,g=a.toUtf8(b),h=-1,i=g.length,j=[,,,];if(a.ie){for(c=[];++h>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c.push(a.alphabet.charAt(j[0]),a.alphabet.charAt(j[1]),a.alphabet.charAt(j[2]),a.alphabet.charAt(j[3]));return c.join("")}for(c="";++h>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c+=a.alphabet[j[0]]+a.alphabet[j[1]]+a.alphabet[j[2]]+a.alphabet[j[3]];return c},decode:function(b){if(b=b.replace(/\s/g,""),b.length%4)throw new Error("InvalidLengthError: decode failed: The string to be decoded is not the correct length for a base64 encoded string.");if(/[^A-Za-z0-9+\/=\s]/g.test(b))throw new Error("InvalidCharacterError: decode failed: The string contains characters invalid in a base64 encoded string.");var c,d=a.fromUtf8(b),e=0,f=d.length;if(a.ieo){for(c=[];f>e;)c.push(d[e]<128?String.fromCharCode(d[e++]):d[e]>191&&d[e]<224?String.fromCharCode((31&d[e++])<<6|63&d[e++]):String.fromCharCode((15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]));return c.join("")}for(c="";f>e;)c+=String.fromCharCode(d[e]<128?d[e++]:d[e]>191&&d[e]<224?(31&d[e++])<<6|63&d[e++]:(15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]);return c},toUtf8:function(a){var b,c=-1,d=a.length,e=[];if(/^[\x00-\x7f]*$/.test(a))for(;++cb?e.push(b):2048>b?e.push(b>>6|192,63&b|128):e.push(b>>12|224,b>>6&63|128,63&b|128);return e},fromUtf8:function(b){var c,d=-1,e=[],f=[,,,];if(!a.lookup){for(c=a.alphabet.length,a.lookup={};++d>4),f[2]=a.lookup[b.charAt(++d)],64!==f[2])&&(e.push((15&f[1])<<4|f[2]>>2),f[3]=a.lookup[b.charAt(++d)],64!==f[3]);)e.push((3&f[2])<<6|f[3]);return e}},b={decode:function(b){b=b.replace(/-/g,"+").replace(/_/g,"/");var c=b.length%4;if(c){if(1===c)throw new Error("InvalidLengthError: Input base64url string is the wrong length to determine padding");b+=new Array(5-c).join("=")}return a.decode(b)},encode:function(b){var c=a.encode(b);return c.replace(/\+/g,"-").replace(/\//g,"_").split("=",1)[0]}};return{decode:a.decode,encode:a.encode,urldecode:b.decode,urlencode:b.encode}}()); \ No newline at end of file diff --git a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java b/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java deleted file mode 100644 index e5e9d8428f..0000000000 --- a/spring-security-oauth/spring-security-oauth-ui-password/src/test/java/org/baeldung/live/AuthorizationLiveTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.baeldung.live; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.springframework.http.MediaType; - -import com.jayway.restassured.RestAssured; -import com.jayway.restassured.response.Response; - -public class AuthorizationLiveTest { - - private String obtainAccessToken(String clientId, String username, String password) { - final Map params = new HashMap(); - params.put("grant_type", "password"); - params.put("client_id", clientId); - params.put("username", username); - params.put("password", password); - final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("http://localhost:8081/spring-security-oauth-server/oauth/token"); - return response.jsonPath().getString("access_token"); - } - - @Test - public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { - final String accessToken = obtainAccessToken("fooClientIdPassword", "john", "123"); - - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(200, fooResponse.getStatusCode()); - assertNotNull(fooResponse.jsonPath().get("name")); - - final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(403, barResponse.getStatusCode()); - } - - @Test - public void givenUser_whenUseBarClient_thenOkForBarResourceReadOnly() { - final String accessToken = obtainAccessToken("barClientIdPassword", "john", "123"); - - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(403, fooResponse.getStatusCode()); - - final Response barReadResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(200, barReadResponse.getStatusCode()); - assertNotNull(barReadResponse.jsonPath().get("name")); - - final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}").post("http://localhost:8081/spring-security-oauth-resource/bars"); - assertEquals(403, barWritResponse.getStatusCode()); - } - - @Test - public void givenAdmin_whenUseBarClient_thenOkForBarResourceReadWrite() { - final String accessToken = obtainAccessToken("barClientIdPassword", "tom", "111"); - - final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/foos/1"); - assertEquals(403, fooResponse.getStatusCode()); - - final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("http://localhost:8081/spring-security-oauth-resource/bars/1"); - assertEquals(200, barResponse.getStatusCode()); - assertNotNull(barResponse.jsonPath().get("name")); - - final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE).header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}").post("http://localhost:8081/spring-security-oauth-resource/bars"); - assertEquals(201, barWritResponse.getStatusCode()); - assertEquals("MyBar", barWritResponse.jsonPath().get("name")); - } - -}