Skip to content

Commit

Permalink
feature/upgrade-spring-and-java (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
karloskelvinsantos authored May 23, 2024
1 parent 2f80660 commit 8cb8fc2
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 85 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"name": "Java",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/java:0-17",
"image": "mcr.microsoft.com/devcontainers/java:1-21",

"features": {
"ghcr.io/devcontainers/features/java:1": {
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ jobs:
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis

- name: Set up JDK 17
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: 17
java-version: 21
distribution: "temurin"

- name: Cache SonarCloud packages
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ In this project you can find an openapi [specification](./openapi.yaml) with all

## Dependencies
You need
- java 17 installed
- java 21 installed
- docker 20+ installed
- maven 3.8.5+ installed

Expand Down
8 changes: 4 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.11</version>
<version>3.2.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<groupId>br.com.itsmemario</groupId>
<artifactId>ecordel</artifactId>
<version>1.5.2</version>
<version>1.6.0</version>
<name>e-cordel</name>
<description>e-reader for cordels</description>

<properties>
<java.version>17</java.version>
<java.version>21</java.version>
<docker.image.prefix>itsmemario</docker.image.prefix>
<sonar.projectKey>e-cordel_ecordel-restapi</sonar.projectKey>
<sonar.organization>e-cordel</sonar.organization>
Expand All @@ -26,7 +26,7 @@
<commons-net.version>3.10.0</commons-net.version>
<jjwt.version>0.9.1</jjwt.version>
<lombok.version>1.18.32</lombok.version>
<testcontainers.version>1.19.7</testcontainers.version>
<testcontainers.version>1.19.8</testcontainers.version>
<mockftp.version>3.1.0</mockftp.version>
<commons-lang.version>2.6</commons-lang.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@

package br.com.itsmemario.ecordel.security;

import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
Expand All @@ -32,16 +32,14 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

private Logger logger = LoggerFactory.getLogger(AuthenticationController.class);
private final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);

private AuthenticationProvider provider;
private AuthenticationService authenticationService;
private final AuthenticationProvider provider;
private final AuthenticationService authenticationService;

@Autowired
public AuthenticationController(AuthenticationProvider provider, AuthenticationService authenticationService) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@

package br.com.itsmemario.ecordel.security;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.springframework.security.core.GrantedAuthority;

import jakarta.persistence.*;

@Entity
@Table(name = "cordel_authority")
Expand All @@ -31,7 +35,7 @@ public class CordelAuthority implements GrantedAuthority{
public static final String AUTHOR = "AUTHOR";

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String authority;

Expand Down
29 changes: 17 additions & 12 deletions src/main/java/br/com/itsmemario/ecordel/security/CordelUser.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,44 @@
package br.com.itsmemario.ecordel.security;

import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import jakarta.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Entity
@Table(name = "cordel_user")
public class CordelUser implements UserDetails {

public static final String USER_AUTHORITY_TABLE = "user_authority";

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@Getter
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private boolean enabled = true;

@ManyToMany(fetch=FetchType.EAGER)
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(
name = USER_AUTHORITY_TABLE,
joinColumns = @JoinColumn(name="user_id"),
inverseJoinColumns = @JoinColumn(name="authority_id")
)
private Set<CordelAuthority> authorities = new HashSet<>();
private final Set<CordelAuthority> authorities = new HashSet<>();

CordelUser() {}

Expand Down Expand Up @@ -72,12 +81,8 @@ public boolean isEnabled() {
return enabled;
}

public Long getId() {
return id;
}

public List<String> getAuthorityNames(){
return authorities.stream().map(CordelAuthority::getAuthority).collect(Collectors.toList());
public List<String> getAuthorityNames(){
return authorities.stream().map(CordelAuthority::getAuthority).toList();
}


Expand Down
12 changes: 3 additions & 9 deletions src/main/java/br/com/itsmemario/ecordel/security/LoginData.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

package br.com.itsmemario.ecordel.security;

import lombok.Getter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

@Getter
public class LoginData {

private String username;
Expand All @@ -32,15 +34,7 @@ public LoginData(String username, String password) {
this.password = password;
}

public String getUsername() {
return username;
}

public String getPassword() {
return password;
}

public UsernamePasswordAuthenticationToken toAuthenticationToken() {
public UsernamePasswordAuthenticationToken toAuthenticationToken() {
return new UsernamePasswordAuthenticationToken(username, password);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
Expand All @@ -52,25 +53,26 @@ public SecurityConfig(BCryptPasswordEncoder encoder, AuthenticationService authe

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()// TODO review
.authorizeHttpRequests()
.requestMatchers(HttpMethod.POST, "/auth").permitAll()
.requestMatchers(HttpMethod.GET, "/**").permitAll()
.requestMatchers(HttpMethod.POST, "/cordels/**").hasAnyAuthority(CordelAuthority.ADMIN, CordelAuthority.AUTHOR, CordelAuthority.EDITOR)
.requestMatchers(HttpMethod.PUT, "/cordels/**").hasAnyAuthority(CordelAuthority.ADMIN, CordelAuthority.AUTHOR, CordelAuthority.EDITOR)
.requestMatchers(HttpMethod.POST, "/authors/**").hasAnyAuthority(CordelAuthority.ADMIN)
.requestMatchers(HttpMethod.PUT, "/authors/**").hasAnyAuthority(CordelAuthority.ADMIN)
.anyRequest().authenticated().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(new TokenAuthenticationFilter(authenticationService), UsernamePasswordAuthenticationFilter.class);
http.cors(cors -> corsConfigurationSource())
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(req -> {
req.requestMatchers(HttpMethod.POST, "/auth").permitAll();
req.requestMatchers(HttpMethod.GET, "/**").permitAll();
req.requestMatchers(HttpMethod.POST, "/cordels/**").hasAnyAuthority(CordelAuthority.ADMIN, CordelAuthority.AUTHOR, CordelAuthority.EDITOR);
req.requestMatchers(HttpMethod.PUT, "/cordels/**").hasAnyAuthority(CordelAuthority.ADMIN, CordelAuthority.AUTHOR, CordelAuthority.EDITOR);
req.requestMatchers(HttpMethod.POST, "/authors/**").hasAnyAuthority(CordelAuthority.ADMIN);
req.requestMatchers(HttpMethod.PUT, "/authors/**").hasAnyAuthority(CordelAuthority.ADMIN);
req.anyRequest().authenticated();
})
.addFilterBefore(new TokenAuthenticationFilter(authenticationService), UsernamePasswordAuthenticationFilter.class);

return http.build();
}

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
return web -> web.ignoring()
.requestMatchers("/**.html", "/v2/api-docs", "/webjars/**", "/configuration/**", "/swagger-resources/**");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@

public class TokenAuthenticationFilter extends OncePerRequestFilter{

private final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class);
private final Logger tokenAuthLogger = LoggerFactory.getLogger(TokenAuthenticationFilter.class);

public static final String AUTHORIZATION = "Authorization";
private AuthenticationService authenticationService;
private final AuthenticationService authenticationService;

TokenAuthenticationFilter(AuthenticationService authenticationService) {
super();
Expand Down Expand Up @@ -76,7 +76,7 @@ private void authorizeRequestWithToken(String token) {
Optional<CordelUser> userFromToken = authenticationService.getUserFromToken(token);
if(userFromToken.isPresent()) {
CordelUser user = userFromToken.get();
logger.info("authorizing {}",user.getUsername());
tokenAuthLogger.info("authorizing {}",user.getUsername());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Expand Down
31 changes: 1 addition & 30 deletions src/main/java/br/com/itsmemario/ecordel/security/TokenDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,36 +17,7 @@

package br.com.itsmemario.ecordel.security;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class TokenDto {

private final String token;
private final String authenticationMethod;
private final Long expiresAt;

@JsonCreator
public TokenDto(@JsonProperty("token") String token,
@JsonProperty("authenticationMethod") String authenticationMethod,
@JsonProperty("expiresAt") Long expiresAt) {
super();
this.token = token;
this.authenticationMethod = authenticationMethod;
this.expiresAt = expiresAt;
}

public String getToken() {
return token;
}

public String getAuthenticationMethod() {
return authenticationMethod;
}

public Long getExpiresAt() {
return expiresAt;
}
public record TokenDto(String token, String authenticationMethod, Long expiresAt) {

@Override
public String toString() {
Expand Down
2 changes: 1 addition & 1 deletion system.properties
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@
#
#

java.runtime.version=17
java.runtime.version=21

0 comments on commit 8cb8fc2

Please sign in to comment.