diff --git a/examples/oauth2-example/.gitignore b/examples/oauth2-example/.gitignore
new file mode 100644
index 00000000..e62c33c2
--- /dev/null
+++ b/examples/oauth2-example/.gitignore
@@ -0,0 +1,4 @@
+.idea/
+*.iml
+
+target/
diff --git a/examples/oauth2-example/README.md b/examples/oauth2-example/README.md
new file mode 100644
index 00000000..9f2358ec
--- /dev/null
+++ b/examples/oauth2-example/README.md
@@ -0,0 +1,6 @@
+## Пример аутентификации/авторизации с помощью OAuth2 сервера и JWT
+
+* *В примере есть проект authorization-server, призванный выдавать jwt токены в ответ на корректный POST запрос по http://localhost:8090/oauth/token *
+* *В теле такого запроса нужно передать client_id, grant_type, имя и пароль пользователя пользователя пытающегося выполнить вход*
+* *Далее, полученный токен XXX нужно прикладывать к каждому запросу к приложению из проекта resource-server в виде загловка "Authorization Bearer XXX"*
+* *Для демонстрации работы примера нужно запустить приложение authorization-server и следом изучить работу E2E теста в проекте resource-server*
diff --git a/examples/oauth2-example/authorization-server/.gitignore b/examples/oauth2-example/authorization-server/.gitignore
new file mode 100644
index 00000000..a2a3040a
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/.gitignore
@@ -0,0 +1,31 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**
+!**/src/test/**
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+
+### VS Code ###
+.vscode/
diff --git a/examples/oauth2-example/authorization-server/pom.xml b/examples/oauth2-example/authorization-server/pom.xml
new file mode 100644
index 00000000..547638cb
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/pom.xml
@@ -0,0 +1,92 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.2.6.RELEASE
+
+
+ ru.otus
+ authorization-server
+ 0.0.1-SNAPSHOT
+ authorization-server
+ Authorization server demo
+
+
+ 13
+ 13
+ 13
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+
+ org.springframework.security.oauth
+ spring-security-oauth2
+ 2.3.8.RELEASE
+
+
+
+ org.springframework.security
+ spring-security-jwt
+ 1.1.0.RELEASE
+
+
+
+
+ com.h2database
+ h2
+ runtime
+
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.junit.vintage
+ junit-vintage-engine
+
+
+
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/AuthorizationServerApplication.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/AuthorizationServerApplication.java
new file mode 100644
index 00000000..ba739fdc
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/AuthorizationServerApplication.java
@@ -0,0 +1,15 @@
+package ru.otus.authorizationserver;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+
+@EnableConfigurationProperties
+@SpringBootApplication
+public class AuthorizationServerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(AuthorizationServerApplication.class, args);
+ }
+
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/AuthorizationServerConfig.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/AuthorizationServerConfig.java
new file mode 100644
index 00000000..8cedd2fe
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/AuthorizationServerConfig.java
@@ -0,0 +1,61 @@
+package ru.otus.authorizationserver.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+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.provider.token.DefaultTokenServices;
+import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import ru.otus.authorizationserver.services.CustomTokenEnhancer;
+
+import javax.sql.DataSource;
+import java.util.List;
+
+@Configuration
+@EnableAuthorizationServer
+public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
+
+ private static final int ACCESS_TOKEN_VALIDITY_SECONDS = 60 * 60 * 3;
+ private static final int REFRESH_TOKEN_VALIDITY_SECONDS = -1;
+
+ @Autowired
+ private OAuthProps oAuthProps;
+
+ @Autowired
+ private AuthenticationManager authManager;
+
+ @Autowired
+ private TokenStore tokenStore;
+
+ @Autowired
+ private JwtAccessTokenConverter jwtAccessTokenConverter;
+
+ @Override
+ public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
+ TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
+ tokenEnhancerChain.setTokenEnhancers(List.of(new CustomTokenEnhancer(), jwtAccessTokenConverter));
+ endpoints.authenticationManager(authManager)
+ .tokenEnhancer(tokenEnhancerChain)
+ .tokenStore(tokenStore);
+ }
+
+ @Override
+ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
+ clients
+ .inMemory()
+ .withClient(oAuthProps.getClientId())
+ .secret(oAuthProps.getClientSecret())
+ .authorizedGrantTypes("password", "authorization_code", "refresh_token")
+ .scopes("read", "write")
+ .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
+ .refreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS);
+ }
+
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/OAuthProps.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/OAuthProps.java
new file mode 100644
index 00000000..a48da2c5
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/OAuthProps.java
@@ -0,0 +1,14 @@
+package ru.otus.authorizationserver.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "app.oauth2")
+public class OAuthProps {
+ private String clientId;
+ private String clientSecret;
+ private String signingKey;
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/SecurityConfig.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/SecurityConfig.java
new file mode 100644
index 00000000..9bae433c
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/SecurityConfig.java
@@ -0,0 +1,40 @@
+package ru.otus.authorizationserver.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+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.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.password.NoOpPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import ru.otus.authorizationserver.services.InMemoryAuthenticationProvider;
+
+@Configuration
+@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ @Autowired
+ private UserDetailsService userDetailsService;
+
+ @Override
+ @Bean
+ public AuthenticationManager authenticationManagerBean() throws Exception {
+ return super.authenticationManagerBean();
+ }
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return NoOpPasswordEncoder.getInstance();
+ }
+
+
+ @Autowired
+ public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
+ auth.authenticationProvider(new InMemoryAuthenticationProvider(userDetailsService));
+ }
+}
\ No newline at end of file
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/TokenStoreConfig.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/TokenStoreConfig.java
new file mode 100644
index 00000000..fb20bf51
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/config/TokenStoreConfig.java
@@ -0,0 +1,36 @@
+package ru.otus.authorizationserver.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+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
+public class TokenStoreConfig {
+
+ @Autowired
+ private OAuthProps oAuthProps;
+
+ @Bean
+ public TokenStore tokenStore() {
+ return new JwtTokenStore(jwtAccessTokenConverter());
+ }
+
+ @Bean
+ public JwtAccessTokenConverter jwtAccessTokenConverter() {
+ var converter = new JwtAccessTokenConverter();
+ converter.setSigningKey(oAuthProps.getSigningKey());
+ return converter;
+ }
+
+ @Bean
+ public DefaultTokenServices tokenServices(TokenStore tokenStore) {
+ DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
+ defaultTokenServices.setTokenStore(tokenStore);
+ defaultTokenServices.setSupportRefreshToken(true);
+ return defaultTokenServices;
+ }
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/model/CustomUser.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/model/CustomUser.java
new file mode 100644
index 00000000..4d20d10e
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/model/CustomUser.java
@@ -0,0 +1,27 @@
+package ru.otus.authorizationserver.model;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+
+import java.util.Collection;
+
+public class CustomUser extends User {
+
+ @Getter
+ @Setter
+ private String firstName;
+
+ @Getter
+ @Setter
+ private String fatherName;
+
+ public CustomUser(String firstName, String fatherName,
+ String username, String password,
+ Collection extends GrantedAuthority> authorities) {
+ super(username, password, authorities);
+ this.firstName = firstName;
+ this.fatherName = fatherName;
+ }
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/CustomTokenEnhancer.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/CustomTokenEnhancer.java
new file mode 100644
index 00000000..dfbc1425
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/CustomTokenEnhancer.java
@@ -0,0 +1,21 @@
+package ru.otus.authorizationserver.services;
+
+import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class CustomTokenEnhancer implements TokenEnhancer {
+ @Override
+ public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
+ Map additionalInfo = new HashMap<>();
+ Map details = (Map) authentication.getUserAuthentication()
+ .getDetails();
+ additionalInfo.putAll(details);
+ ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
+ return accessToken;
+ }
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryAuthenticationProvider.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryAuthenticationProvider.java
new file mode 100644
index 00000000..79bc8dcf
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryAuthenticationProvider.java
@@ -0,0 +1,60 @@
+package ru.otus.authorizationserver.services;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import ru.otus.authorizationserver.model.CustomUser;
+
+import java.util.Map;
+
+@RequiredArgsConstructor
+public class InMemoryAuthenticationProvider implements AuthenticationProvider {
+
+ public static final String KEY_FIRST_NAME = "firstName";
+ public static final String KEY_FATHER_NAME = "fatherName";
+ private final UserDetailsService userDetailsService;
+
+ @Override
+ public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
+
+ if (authentication.getName() == null || authentication.getCredentials() == null) {
+ return null;
+ }
+
+ if (authentication.getName().isEmpty() || authentication.getCredentials().toString().isEmpty()) {
+ return null;
+ }
+
+ final String userName = authentication.getName();
+ final Object password = authentication.getCredentials();
+
+ CustomUser userDetails = (CustomUser) userDetailsService.loadUserByUsername(userName);
+
+
+ if (userName.equalsIgnoreCase(userDetails.getUsername()) && password.equals(userDetails.getPassword())) {
+ UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
+ userDetails.getUsername(),
+ userDetails.getPassword(),
+ userDetails.getAuthorities());
+
+ token.setDetails(
+ Map.of(
+ KEY_FIRST_NAME, userDetails.getFirstName(),
+ KEY_FATHER_NAME, userDetails.getFatherName()
+ )
+ );
+ return token;
+ }
+
+ throw new UsernameNotFoundException("Invalid username or password.");
+ }
+
+ @Override
+ public boolean supports(final Class> authentication) {
+ return authentication.equals(UsernamePasswordAuthenticationToken.class);
+ }
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryUserDetailsService.java b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryUserDetailsService.java
new file mode 100644
index 00000000..ac07975f
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/java/ru/otus/authorizationserver/services/InMemoryUserDetailsService.java
@@ -0,0 +1,40 @@
+package ru.otus.authorizationserver.services;
+
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Service;
+import ru.otus.authorizationserver.model.CustomUser;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+@Service
+public class InMemoryUserDetailsService implements UserDetailsService {
+
+ private final Map userMap;
+
+ public InMemoryUserDetailsService(PasswordEncoder passwordEncoder) {
+ userMap = Map.of(
+ "user1", new CustomUser("Василий", "Григорьевич",
+ "user1",
+ passwordEncoder.encode("user1"),
+ List.of(new SimpleGrantedAuthority("ADMIN"))),
+
+ "user2", new CustomUser("Ираклий", "Спиридонович",
+ "user2",
+ passwordEncoder.encode("user2"),
+ List.of(new SimpleGrantedAuthority("USER")))
+ );
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ return Optional.ofNullable(userMap.get(username))
+ .orElseThrow(() -> new UsernameNotFoundException(String.format("User %s not found", username)));
+ }
+}
diff --git a/examples/oauth2-example/authorization-server/src/main/resources/application.yml b/examples/oauth2-example/authorization-server/src/main/resources/application.yml
new file mode 100644
index 00000000..93cff256
--- /dev/null
+++ b/examples/oauth2-example/authorization-server/src/main/resources/application.yml
@@ -0,0 +1,8 @@
+server:
+ port: 8090
+
+app:
+ oauth2:
+ client-id: "any_id"
+ client-secret: "any_secret"
+ signing-key: 987654321
diff --git a/examples/oauth2-example/pom.xml b/examples/oauth2-example/pom.xml
new file mode 100644
index 00000000..bd4fd7e2
--- /dev/null
+++ b/examples/oauth2-example/pom.xml
@@ -0,0 +1,17 @@
+
+
+ 4.0.0
+
+ ru.otus
+ oauth2-example
+ 1.0
+
+ pom
+
+
+ authorization-server
+ resource-server
+
+
diff --git a/examples/oauth2-example/resource-server/.gitignore b/examples/oauth2-example/resource-server/.gitignore
new file mode 100644
index 00000000..a2a3040a
--- /dev/null
+++ b/examples/oauth2-example/resource-server/.gitignore
@@ -0,0 +1,31 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**
+!**/src/test/**
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+
+### VS Code ###
+.vscode/
diff --git a/examples/oauth2-example/resource-server/pom.xml b/examples/oauth2-example/resource-server/pom.xml
new file mode 100644
index 00000000..b957a21c
--- /dev/null
+++ b/examples/oauth2-example/resource-server/pom.xml
@@ -0,0 +1,92 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.2.6.RELEASE
+
+
+ ru.otus
+ resource-server
+ 0.0.1-SNAPSHOT
+ resource-server
+ Resource server demo
+
+
+ 13
+ 13
+ 13
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+
+ org.springframework.security.oauth
+ spring-security-oauth2
+ 2.3.8.RELEASE
+
+
+
+ org.springframework.security
+ spring-security-jwt
+ 1.1.0.RELEASE
+
+
+
+
+ com.h2database
+ h2
+ runtime
+
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.junit.vintage
+ junit-vintage-engine
+
+
+
+
+
+ org.springframework.security
+ spring-security-test
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/ResourceServerApplication.java b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/ResourceServerApplication.java
new file mode 100644
index 00000000..1530f5cb
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/ResourceServerApplication.java
@@ -0,0 +1,15 @@
+package ru.otus.resourceserver;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+
+@EnableConfigurationProperties
+@SpringBootApplication
+public class ResourceServerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ResourceServerApplication.class, args);
+ }
+
+}
diff --git a/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/OAuthProps.java b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/OAuthProps.java
new file mode 100644
index 00000000..60e416fd
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/OAuthProps.java
@@ -0,0 +1,14 @@
+package ru.otus.resourceserver.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "app.oauth2")
+public class OAuthProps {
+ private String clientId;
+ private String clientSecret;
+ private String signingKey;
+}
diff --git a/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/ResourceServerConfig.java b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/ResourceServerConfig.java
new file mode 100644
index 00000000..43deeb47
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/config/ResourceServerConfig.java
@@ -0,0 +1,51 @@
+package ru.otus.resourceserver.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+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.error.OAuth2AccessDeniedHandler;
+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
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+@EnableResourceServer
+public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
+
+ @Autowired
+ private OAuthProps oAuthProps;
+
+ @Bean
+ public TokenStore tokenStore() {
+ return new JwtTokenStore(jwtAccessTokenConverter());
+ }
+
+ @Bean
+ public JwtAccessTokenConverter jwtAccessTokenConverter() {
+ var converter = new JwtAccessTokenConverter();
+ converter.setSigningKey(oAuthProps.getSigningKey());
+ return converter;
+ }
+
+ @Override
+ public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
+ resources.tokenStore(tokenStore())
+ ;
+ }
+
+ @Override
+ public void configure(HttpSecurity http) throws Exception {
+ http.anonymous().disable()
+ .authorizeRequests()
+ .antMatchers("/api/**").authenticated()
+ .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
+ }
+
+}
\ No newline at end of file
diff --git a/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/controllers/ApiController.java b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/controllers/ApiController.java
new file mode 100644
index 00000000..b82e2e7e
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/controllers/ApiController.java
@@ -0,0 +1,40 @@
+package ru.otus.resourceserver.controllers;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
+import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.web.bind.annotation.*;
+import ru.otus.resourceserver.models.CurrentUserRequestResult;
+
+import java.util.Map;
+
+@RequiredArgsConstructor
+@RestController
+public class ApiController {
+
+ public static final String KEY_FIRST_NAME = "firstName";
+ public static final String KEY_FATHER_NAME = "fatherName";
+
+ private final TokenStore tokenStore;
+
+ @GetMapping("api/current-user")
+ @ResponseStatus(HttpStatus.OK)
+ @PreAuthorize("hasAuthority('ADMIN')")
+ public CurrentUserRequestResult getCurrentUser(Authentication authentication) {
+
+ Map info = getAdditionalInfo(authentication);
+ return new CurrentUserRequestResult((String) authentication.getPrincipal(),
+ (String) info.get(KEY_FIRST_NAME),
+ (String) info.get(KEY_FATHER_NAME));
+ }
+
+ private Map getAdditionalInfo(Authentication authentication) {
+ OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
+ OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
+ return accessToken.getAdditionalInformation();
+ }
+}
diff --git a/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/models/CurrentUserRequestResult.java b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/models/CurrentUserRequestResult.java
new file mode 100644
index 00000000..8c7b9d6f
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/java/ru/otus/resourceserver/models/CurrentUserRequestResult.java
@@ -0,0 +1,12 @@
+package ru.otus.resourceserver.models;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class CurrentUserRequestResult {
+ private String userName;
+ private String firstName;
+ private String fatherName;
+}
diff --git a/examples/oauth2-example/resource-server/src/main/resources/application.yml b/examples/oauth2-example/resource-server/src/main/resources/application.yml
new file mode 100644
index 00000000..f3f557c8
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/main/resources/application.yml
@@ -0,0 +1,8 @@
+server:
+ port: 8080
+
+app:
+ oauth2:
+ client-id: "any_id"
+ client-secret: "any_secret"
+ signing-key: 987654321
diff --git a/examples/oauth2-example/resource-server/src/test/java/ru/otus/resourceserver/ResourceServerApplicationTests.java b/examples/oauth2-example/resource-server/src/test/java/ru/otus/resourceserver/ResourceServerApplicationTests.java
new file mode 100644
index 00000000..e656426b
--- /dev/null
+++ b/examples/oauth2-example/resource-server/src/test/java/ru/otus/resourceserver/ResourceServerApplicationTests.java
@@ -0,0 +1,69 @@
+package ru.otus.resourceserver;
+
+import lombok.Data;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.*;
+import ru.otus.resourceserver.config.OAuthProps;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
+class ResourceServerApplicationTests {
+
+ @Autowired
+ private TestRestTemplate restTemplate;
+
+ @Autowired
+ private OAuthProps oAuthProps;
+
+ @Data
+ static class TokenResponse {
+ private String access_token;
+ private String token_type;
+ private String refresh_token;
+ private String expires_in;
+ private String scope;
+ }
+
+ @Test
+ void shouldSuccessfullyAccessTheEndpointAfterLoginOnAuthorizationServer() {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+ headers.setBasicAuth(oAuthProps.getClientId(), oAuthProps.getClientSecret());
+
+ ResponseEntity tokenResponse = restTemplate.postForEntity(
+ "http://localhost:8090/oauth/token?client_id=" + oAuthProps.getClientId() +
+ "&grant_type=password&username=user1&password=user1",
+ new HttpEntity<>(headers),
+ TokenResponse.class);
+
+
+/*
+ System.out.println(tokenResponse.getStatusCode());
+ System.out.println(tokenResponse.getHeaders());
+ System.out.println(tokenResponse.getBody());
+*/
+ assertThat(tokenResponse.getBody()).isNotNull();
+
+ headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ headers.setBearerAuth(tokenResponse.getBody().getAccess_token());
+
+
+ ResponseEntity currentUserResponse = restTemplate.exchange(
+ "http://localhost:8080/api/current-user",
+ HttpMethod.GET,
+ new HttpEntity<>(headers),
+ String.class);
+
+ System.out.println(currentUserResponse.getStatusCode());
+ System.out.println(currentUserResponse.getHeaders());
+ System.out.println(currentUserResponse.getBody());
+ assertThat(currentUserResponse.getBody())
+ .isNotNull().isEqualTo("{\"userName\":\"user1\",\"firstName\":\"Василий\",\"fatherName\":\"Григорьевич\"}");
+ }
+
+}