Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5a969ef

Browse files
all basic configurations
1 parent c7a3f71 commit 5a969ef

File tree

17 files changed

+544
-24
lines changed

17 files changed

+544
-24
lines changed

‎pom.xml‎

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
<java.version>1.8</java.version>
2525

2626
<base>frolvlad/alpine-oraclejdk8:slim</base>
27-
<tomcat.port>8081</tomcat.port>
27+
<tomcat.port>8080</tomcat.port>
2828
<tomcat.ip>127.0.0.1</tomcat.ip>
2929
<file>readme</file>
3030
</properties>
@@ -96,22 +96,6 @@
9696
<artifactId>spring-boot-maven-plugin</artifactId>
9797
</plugin>
9898

99-
<!--<plugin>-->
100-
<!--<groupId>org.springframework.boot</groupId>-->
101-
<!--<artifactId>spring-boot-maven-plugin</artifactId>-->
102-
<!--<configuration>-->
103-
<!--<executable>true</executable>-->
104-
<!--<addResources>true</addResources>-->
105-
<!--</configuration>-->
106-
<!--<executions>-->
107-
<!--<execution>-->
108-
<!--<goals>-->
109-
<!--<goal>repackage</goal>-->
110-
<!--</goals>-->
111-
<!--</execution>-->
112-
<!--</executions>-->
113-
<!--</plugin>-->
114-
11599
<plugin>
116100
<groupId>io.fabric8</groupId>
117101
<artifactId>docker-maven-plugin</artifactId>

‎readme.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Spring REST API with OAuth2 and JWT
2+
3+
### Para executar a aplicação
4+
5+
- Maven
6+
7+
```
8+
mnv clean spring-boot:run
9+
```
10+
11+
- Docker
12+
13+
```
14+
mvn clean package docker:build
15+
mvn docker:start
16+
```
17+
18+
### Informações adicionais
19+
20+
- client: ```6697a105331c91173a76381ebd249278```
21+
22+
- secret: ```B6813193F1D7EC8BF5B40183CAC2C160A946E43DFAA300C053292```
23+
24+
- Usuário comum: gabrielczar and 123456
25+
26+
- Administrador: gabrielczar.adm and 123456
27+
28+
- Recurso disponivel para todos os usuários: [http://localhost:8080/api/users](http://localhost:8080/api/users)
29+
- Recurso administrativo: [http://localhost:8080/api/users/adm](http://localhost:8080/api/users/adm)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.gabrielczar.springrestoauth2jwt.bootstrap;
2+
3+
4+
import com.gabrielczar.springrestoauth2jwt.domain.Authority;
5+
import com.gabrielczar.springrestoauth2jwt.domain.User;
6+
import com.gabrielczar.springrestoauth2jwt.repositories.UserRepository;
7+
import org.apache.log4j.Logger;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.context.ApplicationListener;
10+
import org.springframework.context.event.ContextRefreshedEvent;
11+
import org.springframework.stereotype.Component;
12+
13+
import java.util.Arrays;
14+
import java.util.Collections;
15+
16+
@Component
17+
public class DevBootstrap implements ApplicationListener<ContextRefreshedEvent> {
18+
private final Logger LOGGER = Logger.getLogger(this.getClass().getName());
19+
20+
private UserRepository userRepository;
21+
22+
@Autowired
23+
public DevBootstrap(UserRepository userRepository) {
24+
this.userRepository = userRepository;
25+
}
26+
27+
@Override
28+
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
29+
LOGGER.info("INIT APPLICATION CONTEXT");
30+
31+
userRepository.deleteAll();
32+
33+
User adm = new User();
34+
adm.setFirstName("Gabriel");
35+
adm.setLastName("Czar");
36+
adm.setUsername("gabrielczar.adm");
37+
adm.setPassword("123456");
38+
adm.setAuthorities(Collections.singletonList(new Authority("ROLE_ADMIN")));
39+
40+
User user = new User();
41+
user.setFirstName("Gabriel");
42+
user.setLastName("Czar");
43+
user.setUsername("gabrielczar");
44+
user.setPassword("123456");
45+
user.setAuthorities(Collections.singletonList(new Authority("ROLE_USER")));
46+
47+
userRepository.save(Arrays.asList(adm, user));
48+
}
49+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.gabrielczar.springrestoauth2jwt.configurations;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.authentication.AuthenticationManager;
7+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
8+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
9+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
10+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
11+
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
12+
import org.springframework.security.oauth2.provider.token.TokenStore;
13+
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
14+
15+
import java.util.Arrays;
16+
import java.util.Collections;
17+
18+
@Configuration
19+
@EnableAuthorizationServer
20+
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
21+
private final JwtAccessTokenConverter accessTokenConverter;
22+
private final AuthenticationManager authenticationManager;
23+
private final TokenStore tokenStore;
24+
25+
@Value("${security.jwt.client-id}")
26+
private String clientId;
27+
28+
@Value("${security.jwt.client-secret}")
29+
private String clientSecret;
30+
31+
@Value("${security.jwt.grant-type}")
32+
private String grantType;
33+
34+
@Value("${security.jwt.scope-read}")
35+
private String scopeRead;
36+
37+
@Value("${security.jwt.scope-write}")
38+
private String scopeWrite = "write";
39+
40+
@Value("${security.jwt.resource-ids}")
41+
private String resourceIds;
42+
43+
@Autowired
44+
public AuthorizationServerConfiguration(TokenStore tokenStore, JwtAccessTokenConverter accessTokenConverter, AuthenticationManager authenticationManager) {
45+
this.tokenStore = tokenStore;
46+
this.accessTokenConverter = accessTokenConverter;
47+
this.authenticationManager = authenticationManager;
48+
}
49+
50+
@Override
51+
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
52+
configurer
53+
.inMemory()
54+
.withClient(clientId)
55+
.secret(clientSecret)
56+
.authorizedGrantTypes(grantType)
57+
.scopes(scopeRead, scopeWrite)
58+
.resourceIds(resourceIds);
59+
}
60+
61+
@Override
62+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
63+
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
64+
enhancerChain.setTokenEnhancers(Collections.singletonList(accessTokenConverter));
65+
endpoints.tokenStore(tokenStore)
66+
.accessTokenConverter(accessTokenConverter)
67+
.tokenEnhancer(enhancerChain)
68+
.authenticationManager(authenticationManager);
69+
}
70+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.gabrielczar.springrestoauth2jwt.configurations;
2+
3+
import org.springframework.beans.factory.annotation.Value;
4+
import org.springframework.boot.web.servlet.FilterRegistrationBean;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.Configuration;
7+
import org.springframework.core.Ordered;
8+
import org.springframework.web.cors.CorsConfiguration;
9+
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
10+
import org.springframework.web.filter.CorsFilter;
11+
12+
import java.util.List;
13+
14+
@Configuration
15+
public class CORSConfiguration {
16+
17+
@Value("${cors.allowedHeaders}")
18+
private List<String> allowedHeaders;
19+
20+
@Value("${cors.allowedMethods}")
21+
private List<String> allowedMethods;
22+
23+
@Value("${cors.allowedOrigin}")
24+
private String allowedOrigin;
25+
26+
@Bean
27+
public CorsFilter corsFilter() {
28+
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
29+
CorsConfiguration config = new CorsConfiguration();
30+
config.setAllowCredentials(true);
31+
config.addAllowedOrigin(allowedOrigin);
32+
config.setAllowedMethods(allowedMethods);
33+
config.setAllowedHeaders(allowedHeaders);
34+
source.registerCorsConfiguration("/**", config);
35+
return new CorsFilter(source);
36+
}
37+
38+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.gabrielczar.springrestoauth2jwt.configurations;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
8+
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
9+
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
10+
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
11+
12+
@Configuration
13+
@EnableResourceServer
14+
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
15+
private final ResourceServerTokenServices tokenServices;
16+
17+
@Value("${security.jwt.resource-ids}")
18+
private String resourceIds;
19+
20+
@Autowired
21+
public ResourceServerConfiguration(ResourceServerTokenServices tokenServices) {
22+
this.tokenServices = tokenServices;
23+
}
24+
25+
@Override
26+
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
27+
resources.resourceId(resourceIds).tokenServices(tokenServices);
28+
}
29+
30+
@Override
31+
public void configure(HttpSecurity http) throws Exception {
32+
http
33+
.requestMatchers()
34+
.and()
35+
.authorizeRequests()
36+
.antMatchers("/actuator/**", "/api-docs/**")
37+
.permitAll()
38+
.antMatchers("/api/**" )
39+
.authenticated();
40+
}
41+
}
Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,94 @@
11
package com.gabrielczar.springrestoauth2jwt.configurations;
22

3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.context.annotation.Bean;
36
import org.springframework.context.annotation.Configuration;
7+
import org.springframework.context.annotation.Primary;
8+
import org.springframework.security.authentication.AuthenticationManager;
9+
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
410
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
11+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
512
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
613
import org.springframework.security.config.annotation.web.builders.WebSecurity;
14+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
715
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
16+
import org.springframework.security.config.http.SessionCreationPolicy;
17+
import org.springframework.security.core.userdetails.UserDetailsService;
18+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
19+
import org.springframework.security.crypto.password.PasswordEncoder;
20+
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
21+
import org.springframework.security.oauth2.provider.token.TokenStore;
22+
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
23+
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
24+
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
825

926
@Configuration
27+
@EnableWebSecurity
28+
@EnableGlobalMethodSecurity(prePostEnabled = true)
1029
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
30+
private final UserDetailsService userDetailsService;
31+
32+
@Value("${security.signing-key}")
33+
private String signingKey;
34+
35+
@Value("${security.security-realm}")
36+
private String securityRealm;
37+
38+
@Autowired
39+
public SecurityConfiguration(UserDetailsService userDetailsService) {
40+
this.userDetailsService = userDetailsService;
41+
}
42+
43+
@Bean
44+
public PasswordEncoder passwordEncoder() {
45+
return new BCryptPasswordEncoder();
46+
}
47+
48+
@Bean
49+
@Override
50+
protected AuthenticationManager authenticationManager() throws Exception {
51+
return super.authenticationManager();
52+
}
53+
54+
@Override
55+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
56+
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
57+
}
1158

1259
@Override
1360
protected void configure(HttpSecurity http) throws Exception {
1461
http
15-
.antMatcher("/**")
16-
.authorizeRequests()
17-
.antMatchers("/")
18-
.permitAll();
62+
.csrf()
63+
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
64+
.and()
65+
.sessionManagement()
66+
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
67+
.and()
68+
.httpBasic()
69+
.realmName(securityRealm);
70+
71+
}
72+
73+
@Bean
74+
public JwtAccessTokenConverter accessTokenConverter() {
75+
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
76+
converter.setSigningKey(signingKey);
77+
return converter;
78+
}
79+
80+
@Bean
81+
public TokenStore tokenStore() {
82+
return new JwtTokenStore(accessTokenConverter());
83+
}
84+
85+
@Bean
86+
@Primary
87+
//Making this primary to avoid any accidental duplication with another token service instance of the same name
88+
public DefaultTokenServices tokenServices() {
89+
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
90+
defaultTokenServices.setTokenStore(tokenStore());
91+
defaultTokenServices.setSupportRefreshToken(true);
92+
return defaultTokenServices;
1993
}
2094
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.gabrielczar.springrestoauth2jwt.controllers;
2+
3+
import org.springframework.boot.autoconfigure.web.ErrorController;
4+
import org.springframework.http.ResponseEntity;
5+
import org.springframework.web.bind.annotation.RequestMapping;
6+
import org.springframework.web.bind.annotation.RestController;
7+
8+
@RestController
9+
public class ErrorRestController implements ErrorController {
10+
11+
private static final String PATH = "/error";
12+
13+
@RequestMapping(value = PATH, produces = "application/json")
14+
public ResponseEntity error() {
15+
return ResponseEntity.badRequest().body("{ \"error\": \"The Content doesn't exist or is unauthorized!\"}");
16+
}
17+
18+
@Override
19+
public String getErrorPath() {
20+
return PATH;
21+
}
22+
23+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /