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
33 changes: 33 additions & 0 deletions src/main/java/com/devsuperior/bds03/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.devsuperior.bds03.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;

@Configuration
public class AppConfig {

@Value("${jwt.secret}")
private String jwtSecret;

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
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,67 @@
package com.devsuperior.bds03.config;

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.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@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,53 @@
package com.devsuperior.bds03.config;

import java.util.Arrays;

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;


@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[] OPERATOR_GET = {"/departments/**", "/employees/**"};


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


@Override
public void configure(HttpSecurity http) throws Exception {


if(Arrays.asList(environment.getActiveProfiles()).contains("test")) {
http.headers().frameOptions().disable();
}

http.authorizeRequests()
.antMatchers(PUBLIC).permitAll()
.antMatchers(HttpMethod.GET, OPERATOR_GET).hasAnyRole("OPERATOR","ADMIN")
.anyRequest().hasAnyRole("ADMIN");
}


}
16 changes: 0 additions & 16 deletions src/main/java/com/devsuperior/bds03/config/SecurityConfig.java

This file was deleted.

50 changes: 50 additions & 0 deletions src/main/java/com/devsuperior/bds03/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.devsuperior.bds03.config;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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 Environment env;

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailsService;

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

@Override
public void configure(WebSecurity web) throws Exception {
if(Arrays.asList(env.getActiveProfiles()).contains("test")) {
web.ignoring().antMatchers("/actuator/**");
}
}

@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public ResponseEntity<Page<EmployeeDTO>> findAll(Pageable pageable) {
}

@PostMapping
public ResponseEntity<EmployeeDTO> insert(@RequestBody EmployeeDTO dto) {
public ResponseEntity<EmployeeDTO> insert(@RequestBody @Valid EmployeeDTO dto) {
dto = service.insert(dto);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(dto.getId()).toUri();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.devsuperior.bds03.controllers.exceptions;

import java.io.Serializable;

public class FieldMessage implements Serializable{

private static final long serialVersionUID = 1L;

private String fieldName;
private String message;

public FieldMessage() {
}

public FieldMessage(String fieldName, String message) {
super();
this.fieldName = fieldName;
this.message = message;
}

public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.devsuperior.bds03.controllers.exceptions;

import java.time.Instant;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


@ControllerAdvice
public class ResourceExceptionHandler {


@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationError> validation(
MethodArgumentNotValidException ex, HttpServletRequest request){

HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
ValidationError error = new ValidationError();
error.setTimestamp(Instant.now());
error.setStatus(status.value());
error.setError("Validation exception");
error.setMessage(ex.getMessage());
error.setPath(request.getRequestURI());

for(FieldError field : ex.getBindingResult().getFieldErrors()) {
error.addError(field.getField(), field.getDefaultMessage());
}
return ResponseEntity.status(status).body(error);


}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.devsuperior.bds03.controllers.exceptions;

import java.io.Serializable;
import java.time.Instant;

public class StandardError implements Serializable {

private static final long serialVersionUID = 1L;

private Instant timestamp;
private Integer status;
private String error;
private String message;
private String path;

public StandardError() {
}

public Instant getTimestamp() {
return timestamp;
}

public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp;
}

public Integer getStatus() {
return status;
}

public void setStatus(Integer status) {
this.status = status;
}

public String getError() {
return error;
}

public void setError(String error) {
this.error = error;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getPath() {
return path;
}

public void setPath(String path) {
this.path = path;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.devsuperior.bds03.controllers.exceptions;

import java.util.ArrayList;
import java.util.List;

public class ValidationError extends StandardError {

private static final long serialVersionUID = 1L;
private List<FieldMessage> errors = new ArrayList<>();

public void addError(String fieldName, String message) {
errors.add(new FieldMessage(fieldName, message));
}

public List<FieldMessage> getErrors() {
return errors;
}

}
Loading