Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Final #3

Open
wants to merge 2 commits into
base: final
Choose a base branch
from
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
7 changes: 1 addition & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
Expand Down Expand Up @@ -70,6 +64,7 @@
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>

</dependencies>

<build>
Expand Down
29 changes: 29 additions & 0 deletions src/main/java/com/devsuperior/bds03/config/AppConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,41 @@
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

<<<<<<< HEAD
//classe de configuração, para manter alguma configuração, manter um component e etc
@Configuration
public class AppConfig {

//coloando valores definidos na propriedade
=======
@Configuration
public class AppConfig {

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

@Bean
<<<<<<< HEAD
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}

//bean para token jwt
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();//instancia o objeto
tokenConverter.setSigningKey(jwtSecret); //faz o registro no token
return tokenConverter;
}

//bean para token jwt
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());//
}

=======
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Expand All @@ -29,4 +57,5 @@ public JwtAccessTokenConverter accessTokenConverter() {
public JwtTokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,33 @@
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
<<<<<<< HEAD
@EnableAuthorizationServer
=======
@EnableAuthorizationServer
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

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

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

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

@Autowired
private BCryptPasswordEncoder passwordEnconder;

@Autowired
private JwtAccessTokenConverter accessTokenConverter;

@Autowired
private JwtTokenStore tokenStore;

=======

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;
Expand All @@ -35,6 +57,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
@Autowired
private JwtTokenStore tokenStore;

>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
@Autowired
private AuthenticationManager authenticationManager;

Expand All @@ -45,19 +68,36 @@ public void configure(AuthorizationServerSecurityConfigurer security) throws Exc

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

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
<<<<<<< HEAD

endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter);
}

=======

endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter);
}
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Autowired
private JwtTokenStore tokenStore;
<<<<<<< HEAD

private static final String[] PUBLIC = { "/oauth/token", "/h2-console/**" };
private static final String[] OPERATOR_GET = { "/departments/**", "/employees/**" };

=======

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

private static final String[] OPERATOR_GET = { "/departments/**", "/employees/**" };

>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
Expand All @@ -34,6 +41,18 @@ public void configure(ResourceServerSecurityConfigurer resources) throws Excepti
@Override
public void configure(HttpSecurity http) throws Exception {

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

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

=======
// H2
if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
http.headers().frameOptions().disable();
Expand All @@ -44,4 +63,5 @@ public void configure(HttpSecurity http) throws Exception {
.antMatchers(HttpMethod.GET, OPERATOR_GET).hasAnyRole("OPERATOR", "ADMIN")
.anyRequest().hasAnyRole("ADMIN");
}
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
23 changes: 23 additions & 0 deletions src/main/java/com/devsuperior/bds03/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,50 @@

@Configuration
@EnableWebSecurity
<<<<<<< HEAD
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
private BCryptPasswordEncoder passwordeEnconder;
=======
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder passwordEncoder;
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1

@Autowired
private UserDetailsService userDetailsService;

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

}

=======
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

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

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


=======
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ public ResponseEntity<Page<EmployeeDTO>> findAll(Pageable pageable) {
}

@PostMapping
<<<<<<< HEAD
public ResponseEntity<EmployeeDTO> insert(@Valid @RequestBody EmployeeDTO dto) {
=======
public ResponseEntity<EmployeeDTO> insert(@RequestBody @Valid EmployeeDTO dto) {
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
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
Expand Up @@ -3,16 +3,27 @@
import java.io.Serializable;

public class FieldMessage implements Serializable {
<<<<<<< HEAD

private static final long serialVersionUID = 1L;

=======
private static final long serialVersionUID = 1L;

>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
private String fieldName;
private String message;

public FieldMessage() {
}
<<<<<<< HEAD

public FieldMessage(String fieldName, String message) {
=======

public FieldMessage(String fieldName, String message) {
super();
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
this.fieldName = fieldName;
this.message = message;
}
Expand All @@ -32,4 +43,9 @@ public String getMessage() {
public void setMessage(String message) {
this.message = message;
}
<<<<<<< HEAD


=======
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,30 @@
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

<<<<<<< HEAD
@ControllerAdvice // permiti que a classe intercepte exceções
public class ResourceExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationError> validation(MethodArgumentNotValidException e, HttpServletRequest req) {
HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY; // 422 ele diz que alguma entidade nao foi processada
// (@valid)
ValidationError err = new ValidationError();
err.setTimestamp(Instant.now()); // pega o instante atual
err.setStatus(status.value()); // Erro de requisição
err.setError("Validation exceção");
err.setMessage(e.getMessage());// pega a mensagem do erro
err.setPath(req.getRequestURI());// pega o caminho requisitado

for (FieldError f : e.getBindingResult().getFieldErrors()) {
err.addErrors(f.getField(), f.getDefaultMessage());
}

// customiza o que vamos retornar
return ResponseEntity.status(status).body(err);
}

=======
@ControllerAdvice
public class ResourceExceptionHandler {

Expand All @@ -30,4 +54,5 @@ public ResponseEntity<ValidationError> validation(MethodArgumentNotValidExceptio

return ResponseEntity.status(status).body(err);
}
>>>>>>> e86b783781f59ad361e28764d7ea73cc3d8a2ed1
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.devsuperior.bds03.controllers.exceptions;

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

public class StandarError implements Serializable{

private static final long serialVersionUID = 1L;


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

public StandarError() {

}

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;
}


}
Loading