Skip to content

Commit af5c91a

Browse files
feat: Add Token Bearer!
1 parent d8e8dac commit af5c91a

File tree

11 files changed

+150
-31
lines changed

11 files changed

+150
-31
lines changed

pom.xml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,13 @@
7070
<artifactId>spring-boot-starter-data-jpa</artifactId>
7171
</dependency>
7272

73+
<!-- JWT Dependencies -->
7374
<dependency>
74-
<groupId>io.jsonwebtoken</groupId>
75-
<artifactId>jjwt</artifactId>
76-
<version>0.12.6</version>
75+
<groupId>com.auth0</groupId>
76+
<artifactId>java-jwt</artifactId>
77+
<version>4.5.0</version>
7778
</dependency>
78-
79+
7980
<dependency>
8081
<groupId>org.springframework.boot</groupId>
8182
<artifactId>spring-boot-starter-validation</artifactId>

src/main/java/com/helper/vavahelper/controllers/AuthenticationController.java

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,46 +5,56 @@
55
import org.springframework.security.authentication.AuthenticationManager;
66
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
77
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
8-
import org.springframework.web.bind.annotation.GetMapping;
8+
import org.springframework.web.bind.annotation.CrossOrigin;
99
import org.springframework.web.bind.annotation.PostMapping;
1010
import org.springframework.web.bind.annotation.RequestBody;
1111
import org.springframework.web.bind.annotation.RequestMapping;
1212
import org.springframework.web.bind.annotation.RestController;
1313

14-
import com.helper.vavahelper.models.User.AuthenticationDTO;
14+
import com.helper.vavahelper.infra.security.TokenService;
1515
import com.helper.vavahelper.models.User.User;
16-
import com.helper.vavahelper.models.User.UserRegisterDTO;
16+
import com.helper.vavahelper.models.User.UserRole;
17+
import com.helper.vavahelper.models.User.body.AuthenticationDTO;
18+
import com.helper.vavahelper.models.User.body.LoginResponseDTO;
19+
import com.helper.vavahelper.models.User.body.UserRegisterDTO;
1720
import com.helper.vavahelper.repositories.UserRepository;
1821

1922
import jakarta.validation.Valid;
2023

2124
@RestController
2225
@RequestMapping("auth")
26+
@CrossOrigin(origins = "*")
2327
public class AuthenticationController {
24-
25-
@Autowired
26-
public UserRepository userRepository;
28+
@Autowired
29+
private AuthenticationManager authenticationManager;
2730

2831
@Autowired
29-
public AuthenticationManager authenticationManager;
30-
32+
private TokenService tokenService;
33+
34+
@Autowired
35+
private UserRepository repository;
36+
3137
@PostMapping("/login")
32-
public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data){
38+
public ResponseEntity<LoginResponseDTO> postMethodLogin(@RequestBody @Valid AuthenticationDTO data) {
3339
var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.password());
3440
var auth = this.authenticationManager.authenticate(usernamePassword);
3541

36-
return ResponseEntity.ok().build();
42+
var token = tokenService.generateToken((User)auth.getPrincipal());
43+
44+
return ResponseEntity.ok(new LoginResponseDTO(token));
3745
}
3846

3947
@PostMapping("/register")
40-
public ResponseEntity register(@RequestBody @Valid UserRegisterDTO data){
41-
if(this.userRepository.findByLogin(data.login()) != null) return ResponseEntity.badRequest().build();
48+
public ResponseEntity<String> postMethodRegister(@RequestBody @Valid UserRegisterDTO data){
4249

43-
String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
44-
User newUser = new User(data.login(), encryptedPassword, data.role());
50+
if(repository.findByLogin(data.login()) != null) return ResponseEntity
51+
.badRequest().body("Username already taken.");
4552

46-
this.userRepository.save(newUser);
53+
String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
54+
UserRole role = (data.role() == null) ? UserRole.USER : data.role();
4755

48-
return ResponseEntity.ok().build();
56+
User newUser = new User(data.login(), encryptedPassword, role);
57+
this.repository.save(newUser);
58+
return ResponseEntity.ok("User registered successfully.");
4959
}
5060
}

src/main/java/com/helper/vavahelper/infra/security/SecurityConfiguration.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ public class SecurityConfiguration {
1919
@Bean
2020
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
2121
return httpSecurity
22+
.cors(cors -> cors.and())
2223
.csrf(csrf -> csrf.disable())
2324
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
2425
.authorizeHttpRequests(authorize -> authorize
25-
.requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
26-
.requestMatchers(HttpMethod.POST, "/auth/register").permitAll()
26+
.requestMatchers(HttpMethod.POST, "auth/**").permitAll()
2727
.requestMatchers("/h2/**").permitAll()
2828
.anyRequest().authenticated()
2929
)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.helper.vavahelper.infra.security;
2+
3+
import jakarta.servlet.FilterChain;
4+
import jakarta.servlet.ServletException;
5+
import jakarta.servlet.http.HttpServletRequest;
6+
import jakarta.servlet.http.HttpServletResponse;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
9+
import org.springframework.security.core.context.SecurityContextHolder;
10+
import org.springframework.security.core.userdetails.UserDetails;
11+
import org.springframework.stereotype.Component;
12+
import org.springframework.web.filter.OncePerRequestFilter;
13+
14+
import com.helper.vavahelper.repositories.UserRepository;
15+
16+
import java.io.IOException;
17+
@Component
18+
public class SecurityFilter extends OncePerRequestFilter{
19+
@Autowired
20+
TokenService tokenService;
21+
22+
@Autowired
23+
UserRepository userRepository;
24+
25+
@Override
26+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
27+
var token = this.recoverToken(request);
28+
if(token != null){
29+
var login = tokenService.validateToken(token);
30+
UserDetails user = userRepository.findByLogin(login);
31+
32+
var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
33+
SecurityContextHolder.getContext().setAuthentication(authentication);
34+
}
35+
filterChain.doFilter(request, response);
36+
}
37+
38+
private String recoverToken(HttpServletRequest request){
39+
var authHeader = request.getHeader("Authorization");
40+
if(authHeader == null) return null;
41+
return authHeader.replace("Bearer ", "");
42+
}
43+
}
44+
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.helper.vavahelper.infra.security;
2+
3+
import java.time.Instant;
4+
import java.time.LocalDateTime;
5+
import java.time.ZoneOffset;
6+
7+
import org.springframework.beans.factory.annotation.Value;
8+
9+
import org.springframework.stereotype.Service;
10+
11+
import com.auth0.jwt.JWT;
12+
import com.auth0.jwt.algorithms.Algorithm;
13+
import com.auth0.jwt.exceptions.JWTCreationException;
14+
import com.auth0.jwt.exceptions.JWTVerificationException;
15+
import com.helper.vavahelper.models.User.User;
16+
17+
18+
19+
@Service
20+
public class TokenService {
21+
22+
@Value("${api.security.token.secret}")
23+
private String secret;
24+
25+
26+
public String generateToken(User user){
27+
try {
28+
Algorithm algorithm = Algorithm.HMAC256(secret);
29+
String token = JWT.create()
30+
.withIssuer("auth-api")
31+
.withSubject(user.getUsername())
32+
.withExpiresAt(getExpirationDate())
33+
.sign(algorithm);
34+
return token;
35+
} catch (JWTCreationException e) {
36+
throw new RuntimeException("Error while generating token.", e);
37+
}
38+
}
39+
40+
public String validateToken(String token){
41+
try {
42+
Algorithm algorithm = Algorithm.HMAC256(secret);
43+
return JWT.require(algorithm)
44+
.withIssuer("auth-api")
45+
.build()
46+
.verify(token)
47+
.getSubject();
48+
} catch (JWTVerificationException exception){
49+
return "";
50+
}
51+
}
52+
53+
private Instant getExpirationDate(){
54+
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
55+
}
56+
}

src/main/java/com/helper/vavahelper/models/User/User.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ public class User implements UserDetails {
2424
@Id
2525
@GeneratedValue(strategy = GenerationType.UUID)
2626
private String id;
27+
private UserRole role;
2728
private String login;
2829
private String password;
29-
private UserRole role;
30-
30+
3131
//Constructor
3232
public User(String login, String password, UserRole role){
3333
this.login = login;

src/main/java/com/helper/vavahelper/models/User/UserRegisterDTO.java

Lines changed: 0 additions & 5 deletions
This file was deleted.

src/main/java/com/helper/vavahelper/models/User/AuthenticationDTO.java renamed to src/main/java/com/helper/vavahelper/models/User/body/AuthenticationDTO.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.helper.vavahelper.models.User;
1+
package com.helper.vavahelper.models.User.body;
22

33
public record AuthenticationDTO(String login, String password) {
44

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package com.helper.vavahelper.models.User.body;
2+
3+
//Token Response:
4+
public record LoginResponseDTO(String token) {}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.helper.vavahelper.models.User.body;
2+
3+
import com.helper.vavahelper.models.User.UserRole;
4+
5+
public record UserRegisterDTO(String login, String password, UserRole role) {
6+
7+
}

0 commit comments

Comments
 (0)