Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.devsuperior.bds04.components;

import com.devsuperior.bds04.entities.User;
import com.devsuperior.bds04.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenEnhancer implements TokenEnhancer {

@Autowired
private UserRepository userRepository;
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
User user = userRepository.findByEmail(oAuth2Authentication.getName());
Map<String, Object> map = new HashMap<>();
map.put("userName", user.getUsername());
map.put("userId", user.getId());

DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
token.setAdditionalInformation(map);
return oAuth2AccessToken;
}
}
38 changes: 38 additions & 0 deletions src/main/java/com/devsuperior/bds04/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.devsuperior.bds04.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

//Classes de configuração
@Configuration
public class AppConfig {

//irá ler o valor da variavel de ambiente
@Value("${jwt.secret}")
private String jwtSecret;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}


//metodos para acessar e ler o token JWT
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
//ASSINATURA DO TOKEN JWT
tokenConverter.setSigningKey(jwtSecret);
return tokenConverter;
}

@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.devsuperior.bds04.config;

import com.devsuperior.bds04.components.JwtTokenEnhancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${jwt.duration}")
private Integer jwtDuration;

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private JwtAccessTokenConverter accessTokenConverter;

@Autowired
private JwtTokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient(clientId)
.secret(passwordEncoder.encode(clientSecret))
.scopes("read", "write")
.authorizedGrantTypes("password")
.accessTokenValiditySeconds(jwtDuration);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.devsuperior.bds04.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
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.token.store.JwtTokenStore;

import java.util.Arrays;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Autowired
private Environment environment;

@Autowired
private JwtTokenStore tokenStore;

private static final String[] PUBLIC = { "/oauth/token", "/h2-console/**"};
private static final String[] PUBLIC_GET = {"/events/**", "/cities/**" };
private static final String[] EVENTS_POST = { "/events" };
private static final String[] CITIES_POST = { "/cities" };

private static final String[] ADMIN = { "/events", "/cities" };
public ResourceServerConfig() {
super();
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}

@Override
public void configure(HttpSecurity http) throws Exception {
//liberando o h2
if(Arrays.asList(environment.getActiveProfiles()).contains("test")) {
http.headers().frameOptions().disable();
}

http.authorizeRequests()
.antMatchers(PUBLIC).permitAll()
.antMatchers(HttpMethod.GET, PUBLIC_GET).permitAll()
.antMatchers(HttpMethod.POST, EVENTS_POST).hasAnyRole("CLIENT", "ADMIN")
.antMatchers(HttpMethod.POST, CITIES_POST).hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, ADMIN).hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, ADMIN).hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, ADMIN).hasRole("ADMIN")
.anyRequest().authenticated();
}
}

//ANA -> CLIENTE
//BOB -> ADMIN
39 changes: 39 additions & 0 deletions src/main/java/com/devsuperior/bds04/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.devsuperior.bds04.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.web.builders.WebSecurity;
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.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/actuator/**");
}

@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.devsuperior.bds04.controllers;

import com.devsuperior.bds04.dto.CityDTO;
import com.devsuperior.bds04.services.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(value = "cities")
public class CityController {

/**
* @Todo
* CRUD para eventos e cidades
* Endpoint de login
* Configuração OAUTH
* Configuração spring security JWT
*/

@Autowired
private CityService service;

@GetMapping
public ResponseEntity<List<CityDTO>> findAll() {

List<CityDTO> list = service.findAllSortedByName();

return ResponseEntity.ok().body(list);
}

@GetMapping(value = "/{id}")
public ResponseEntity<CityDTO> findById(@PathVariable Long id) {
CityDTO city = service.findById(id);
return ResponseEntity.ok().body(city);
}

@PostMapping
public ResponseEntity<CityDTO> create(@RequestBody @Valid CityDTO dto) {
dto = service.create(dto);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(dto.getId()).toUri();
return ResponseEntity.created(uri).body(dto);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.devsuperior.bds04.controllers;

import com.devsuperior.bds04.dto.EventDTO;
import com.devsuperior.bds04.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;

@RestController
@RequestMapping(value = "events")
public class EventController {

@Autowired
private EventService service;

@GetMapping
public ResponseEntity<Page<EventDTO>> findAll(Pageable pageable) {
Page<EventDTO> list = service.findAllPaged(pageable);
return ResponseEntity.ok().body(list);
}

@GetMapping(value = "/{id}")
public ResponseEntity<EventDTO> findById(@PathVariable Long id) {
EventDTO city = service.findById(id);
return ResponseEntity.ok().body(city);
}

@PostMapping
public ResponseEntity<EventDTO> create(@RequestBody @Valid EventDTO dto) {
dto = service.create(dto);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(dto.getId()).toUri();
return ResponseEntity.created(uri).body(dto);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.devsuperior.bds04.controllers;

import com.devsuperior.bds04.dto.UserDTO;
import com.devsuperior.bds04.dto.UserInsertDTO;
import com.devsuperior.bds04.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;

@RestController
@RequestMapping(value = "users")
public class UserController {

@Autowired
private UserService service;


@PostMapping
public ResponseEntity<UserDTO> createUser(@RequestBody @Valid UserInsertDTO dto) {
UserDTO newDto = service.insert(dto);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(newDto.getId()).toUri();
return ResponseEntity.created(uri).body(newDto);
}

}
Loading