Add JWT authentication
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.faf223.expensetrackerfaf.config;
|
||||
|
||||
import com.faf223.expensetrackerfaf.repository.CredentialRepository;
|
||||
import com.faf223.expensetrackerfaf.repository.UserRepository;
|
||||
import com.faf223.expensetrackerfaf.security.PersonDetails;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -17,17 +18,18 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
@Configuration
|
||||
public class ApplicationConfig {
|
||||
|
||||
private final UserRepository repository;
|
||||
private final UserRepository userRepository;
|
||||
private final CredentialRepository credentialRepository;
|
||||
|
||||
@Autowired
|
||||
public ApplicationConfig(UserRepository repository) {
|
||||
this.repository = repository;
|
||||
public ApplicationConfig(UserRepository userRepository, CredentialRepository credentialRepository) {
|
||||
this.userRepository = userRepository;
|
||||
this.credentialRepository = credentialRepository;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
return username -> new PersonDetails(repository.findByEmail(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found")));
|
||||
return username -> new PersonDetails(credentialRepository.findByEmail(username).orElseThrow((() -> new UsernameNotFoundException("User not found"))));
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -20,7 +20,6 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserDetailsService userDetailsService;
|
||||
private final TokenRepository tokenRepository;
|
||||
|
||||
public JwtAuthenticationFilter(JwtService jwtService, UserDetailsService userDetailsService) {
|
||||
this.jwtService = jwtService;
|
||||
@@ -48,18 +47,11 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
userEmail = jwtService.extractUsername(jwt);
|
||||
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
|
||||
var isTokenValid = tokenRepository.findByToken(jwt)
|
||||
.map(t -> !t.isExpired() && !t.isRevoked())
|
||||
.orElse(false);
|
||||
if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) {
|
||||
if (jwtService.isTokenValid(jwt, userDetails)) {
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
userDetails,
|
||||
null,
|
||||
userDetails.getAuthorities()
|
||||
);
|
||||
authToken.setDetails(
|
||||
new WebAuthenticationDetailsSource().buildDetails(request)
|
||||
);
|
||||
userDetails, null, userDetails.getAuthorities());
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource()
|
||||
.buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,17 +45,7 @@ public class JwtService {
|
||||
return buildToken(extraClaims, userDetails, jwtExpiration);
|
||||
}
|
||||
|
||||
public String generateRefreshToken(
|
||||
UserDetails userDetails
|
||||
) {
|
||||
return buildToken(new HashMap<>(), userDetails, refreshExpiration);
|
||||
}
|
||||
|
||||
private String buildToken(
|
||||
Map<String, Object> extraClaims,
|
||||
UserDetails userDetails,
|
||||
long expiration
|
||||
) {
|
||||
private String buildToken(Map<String, Object> extraClaims, UserDetails userDetails, long expiration) {
|
||||
return Jwts
|
||||
.builder()
|
||||
.setClaims(extraClaims)
|
||||
|
||||
@@ -28,7 +28,7 @@ public class SecurityConfiguration {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("").permitAll()
|
||||
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
|
||||
@@ -13,10 +13,10 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor
|
||||
public class RegisterRequest {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
private String email;
|
||||
private String firstname; // Change field name to match JSON
|
||||
private String lastname; // Change field name to match JSON
|
||||
private String username; // Change field name to match JSON
|
||||
private String email; // Change field name to match JSON
|
||||
private String password;
|
||||
private Role role;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package com.faf223.expensetrackerfaf.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Entity(name = "credentials")
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Credential {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@@ -16,5 +20,16 @@ public class Credential {
|
||||
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Role role;
|
||||
|
||||
public Credential(User user, String email, String password) {
|
||||
this.user = user;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
|
||||
this.role = Role.USER;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
package com.faf223.expensetrackerfaf.model;
|
||||
|
||||
public enum Role {
|
||||
UNREGISTERED, REGISTERED, ADMIN;
|
||||
USER, ADMIN
|
||||
}
|
||||
|
||||
@@ -9,28 +9,32 @@ import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Entity(name = "users")
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "User")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String email;
|
||||
private String password;
|
||||
@Column(name = "user_uuid")
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private String userUuid;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Role role;
|
||||
@Column(name = "name")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "surname")
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "username")
|
||||
private String username;
|
||||
|
||||
@Transient
|
||||
private String password;
|
||||
|
||||
@OneToMany(mappedBy = "user")
|
||||
private List<Expense> expenses;
|
||||
|
||||
@OneToMany(mappedBy = "user")
|
||||
private List<Income> incomes;
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ import com.faf223.expensetrackerfaf.model.Credential;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CredentialRepository extends JpaRepository<Credential, Long> {
|
||||
Optional<Credential> findByEmail(String email);
|
||||
}
|
||||
@@ -3,8 +3,5 @@ package com.faf223.expensetrackerfaf.repository;
|
||||
import com.faf223.expensetrackerfaf.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
Optional<User> findByEmail(String username);
|
||||
public interface UserRepository extends JpaRepository<User, String> {
|
||||
}
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
package com.faf223.expensetrackerfaf.security;
|
||||
|
||||
import com.faf223.expensetrackerfaf.model.Role;
|
||||
import com.faf223.expensetrackerfaf.model.User;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import lombok.AllArgsConstructor;
|
||||
import com.faf223.expensetrackerfaf.model.Credential;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
@@ -18,31 +14,28 @@ import java.util.List;
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor(force = true)
|
||||
@AllArgsConstructor
|
||||
//@AllArgsConstructor
|
||||
public class PersonDetails implements UserDetails {
|
||||
|
||||
private final User user;
|
||||
private final Credential credential;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Role role;
|
||||
|
||||
public PersonDetails(User user) {
|
||||
this.user = user;
|
||||
public PersonDetails(Credential credential) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return List.of(new SimpleGrantedAuthority(role.name()));
|
||||
return List.of(new SimpleGrantedAuthority(credential.getRole().name()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return user.getPassword();
|
||||
return credential.getPassword();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return user.getEmail();
|
||||
return credential.getEmail();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -4,42 +4,62 @@ import com.faf223.expensetrackerfaf.config.JwtService;
|
||||
import com.faf223.expensetrackerfaf.controller.auth.AuthenticationRequest;
|
||||
import com.faf223.expensetrackerfaf.controller.auth.AuthenticationResponse;
|
||||
import com.faf223.expensetrackerfaf.controller.auth.RegisterRequest;
|
||||
import com.faf223.expensetrackerfaf.model.Role;
|
||||
import com.faf223.expensetrackerfaf.model.Credential;
|
||||
import com.faf223.expensetrackerfaf.model.User;
|
||||
import com.faf223.expensetrackerfaf.repository.CredentialRepository;
|
||||
import com.faf223.expensetrackerfaf.repository.UserRepository;
|
||||
import com.faf223.expensetrackerfaf.security.PersonDetails;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private final UserRepository repository;
|
||||
private final UserRepository userRepository;
|
||||
private final CredentialRepository credentialRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
|
||||
public AuthenticationService(UserRepository repository, PasswordEncoder passwordEncoder, JwtService jwtService) {
|
||||
this.repository = repository;
|
||||
public AuthenticationService(UserRepository repository, CredentialRepository credentialRepository, PasswordEncoder passwordEncoder, JwtService jwtService, AuthenticationManager authenticationManager) {
|
||||
this.userRepository = repository;
|
||||
this.credentialRepository = credentialRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtService = jwtService;
|
||||
}
|
||||
|
||||
public AuthenticationResponse authenticate(AuthenticationRequest request) {
|
||||
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
public AuthenticationResponse register(RegisterRequest request) {
|
||||
|
||||
User user = User.builder()
|
||||
.firstName(request.getFirstName())
|
||||
.lastName(request.getLastName())
|
||||
.email(request.getEmail())
|
||||
.firstName(request.getFirstname())
|
||||
.lastName(request.getLastname())
|
||||
.password(passwordEncoder.encode(request.getPassword()))
|
||||
.role(request.getRole())
|
||||
.username(request.getUsername())
|
||||
.build();
|
||||
repository.save(user);
|
||||
String jwtToken = jwtService.generateToken(new PersonDetails(user));
|
||||
System.out.println(user);
|
||||
userRepository.save(user);
|
||||
Credential credential = new Credential(user, request.getEmail(), passwordEncoder.encode(request.getPassword()));
|
||||
credentialRepository.save(credential);
|
||||
|
||||
String jwtToken = jwtService.generateToken(new PersonDetails(credential));
|
||||
return AuthenticationResponse.builder()
|
||||
.token(jwtToken)
|
||||
.build();
|
||||
}
|
||||
|
||||
public AuthenticationResponse authenticate(AuthenticationRequest request) {
|
||||
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
|
||||
|
||||
Credential credential = credentialRepository.findByEmail(request.getEmail()).orElseThrow((() -> new UsernameNotFoundException("User not found")));
|
||||
|
||||
String jwtToken = jwtService.generateToken(new PersonDetails(credential));
|
||||
return AuthenticationResponse.builder()
|
||||
.token(jwtToken)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user