Hinzufügen von Spring Security Login und Registierung. Basis implementierung von User und zugehörige DatenTransferObjekte.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package SuMoC.backend.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
|
||||
private static final String SECURITY_SCHEME_NAME = "bearerAuth";
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("SuMoC API")
|
||||
.version("1.0")
|
||||
.description("API-Dokumentation für SuMoC"))
|
||||
.addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME))
|
||||
.components(new io.swagger.v3.oas.models.Components()
|
||||
.addSecuritySchemes(SECURITY_SCHEME_NAME,
|
||||
new SecurityScheme()
|
||||
.name(SECURITY_SCHEME_NAME)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.mapper;
|
||||
|
||||
|
||||
import SuMoC.backend.models.User;
|
||||
import SuMoC.backend.models.dto.UserDTO;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface UserMapper {
|
||||
UserDTO toUserDTO(User user);
|
||||
|
||||
User toUser(UserDTO userDTO);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package SuMoC.backend.models;
|
||||
|
||||
public enum RoleName {
|
||||
USER,
|
||||
ADMIN,
|
||||
MODERATOR,
|
||||
SENSOR
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package SuMoC.backend.models;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String username;
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
|
||||
@ElementCollection(targetClass = RoleName.class, fetch = FetchType.EAGER)
|
||||
@Enumerated(EnumType.STRING)
|
||||
@CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
|
||||
@Column(name = "role")
|
||||
private Set<RoleName> roles;
|
||||
|
||||
|
||||
|
||||
public User() {}
|
||||
|
||||
public User(String username, String email, String password, Set<RoleName> roles) {
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
// Getter & Setter
|
||||
public Long getId() { return id; }
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String email) { this.email = email; }
|
||||
public String getPassword() { return password; }
|
||||
public void setPassword(String password) { this.password = password; }
|
||||
public Set<RoleName> getRoles() { return roles; }
|
||||
public String getRolesString() { return roles.toString(); }
|
||||
public void setRoles(Set<RoleName> roles) { this.roles = roles; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.models.dto;
|
||||
|
||||
import SuMoC.backend.models.RoleName;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class UserDTO {
|
||||
private Long userId;
|
||||
private String username;
|
||||
private Set<RoleName> authorities;
|
||||
|
||||
public UserDTO(Long userId, String username, Set<RoleName> authorities){
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public Set<RoleName> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public void setAuthorities(Set<RoleName> authorities) {
|
||||
this.authorities = authorities;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.repositories;
|
||||
|
||||
import SuMoC.backend.models.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
Optional<User> findByUsername(String username);
|
||||
Optional<User> findByEmail(String email);
|
||||
boolean existsByUsername(String username);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package SuMoC.backend.security;
|
||||
|
||||
|
||||
import SuMoC.backend.security.utils.RSAKeyProperties;
|
||||
import com.nimbusds.jose.jwk.JWK;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration {
|
||||
|
||||
private final RSAKeyProperties keys;
|
||||
|
||||
public SecurityConfiguration(RSAKeyProperties keys){
|
||||
this.keys = keys;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder(){
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(UserDetailsService detailsService){
|
||||
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
|
||||
daoProvider.setUserDetailsService(detailsService);
|
||||
daoProvider.setPasswordEncoder(passwordEncoder());
|
||||
return new ProviderManager(daoProvider);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
config.setAllowedOrigins(List.of("http://localhost:4200")); // dein Angular-Origin
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
config.setAllowCredentials(true); // wichtig für Authorization-Header
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.cors(withDefaults())
|
||||
//.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) //allows Access To ALL APIs, Security is off
|
||||
.authorizeHttpRequests(auth -> {
|
||||
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
|
||||
auth.requestMatchers("/auth/user/**").permitAll();
|
||||
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
||||
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
||||
auth.requestMatchers(AUTH_WHITELIST).permitAll();
|
||||
//auth.requestMatchers("/error").permitAll();
|
||||
auth.anyRequest().authenticated();
|
||||
|
||||
}
|
||||
) //TODO:might be Wrong Configuration, rn working fine.
|
||||
.oauth2ResourceServer((OAuth2ServerConfigurer) -> {
|
||||
OAuth2ServerConfigurer.jwt(jwtConfigurer -> {
|
||||
jwtConfigurer.decoder(this.jwtDecoder());
|
||||
jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter());
|
||||
});
|
||||
})
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
return http.build();
|
||||
}
|
||||
|
||||
private static final String[] AUTH_WHITELIST = {
|
||||
"/api/v1/auth/**",
|
||||
"/v3/api-docs/**",
|
||||
"/v3/api-docs.yaml",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
};
|
||||
|
||||
@Bean
|
||||
public JwtDecoder jwtDecoder(){
|
||||
return NimbusJwtDecoder.withPublicKey(keys.getPublicKey()).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtEncoder jwtEncoder(){
|
||||
JWK jwk = new RSAKey.Builder(keys.getPublicKey()).privateKey(keys.getPrivateKey()).build();
|
||||
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
|
||||
|
||||
return new NimbusJwtEncoder(jwks);
|
||||
}
|
||||
|
||||
@Bean
|
||||
// for spring security, so it can correctly identifiy Roles (identifies roles via "ROLE_[role]")
|
||||
public JwtAuthenticationConverter jwtAuthenticationConverter(){
|
||||
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
|
||||
|
||||
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
|
||||
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
|
||||
|
||||
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
|
||||
|
||||
jwtConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
|
||||
|
||||
return jwtConverter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package SuMoC.backend.security.controller;
|
||||
|
||||
|
||||
import SuMoC.backend.security.models.LoginResponseDTO;
|
||||
import SuMoC.backend.security.models.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.models.UserRegistrationDTO;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth/user")
|
||||
public class UserAuthenticationController {
|
||||
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@Autowired
|
||||
public UserAuthenticationController(AuthenticationService authenticationService){
|
||||
this.authenticationService = authenticationService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registriert einen neuen Benutzer
|
||||
*
|
||||
* @param registrationDTO Daten des zu registrierenden Benutzers
|
||||
* @return UserDTO mit den registrierten Benutzerdaten
|
||||
*/
|
||||
@Operation(summary = "Registriert einen neuen Benutzer", description = "Erstellt einen neuen Benutzer und gibt die Benutzerdaten zurück")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Benutzer erfolgreich registriert",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PostMapping("/registration")
|
||||
public ResponseEntity<LoginResponseDTO> registerUser(@RequestBody UserRegistrationDTO registrationDTO) {
|
||||
|
||||
System.out.println("###################### Register Request #####################");
|
||||
System.out.println(registrationDTO.getUsername() + " " + registrationDTO.getPassword() + " " + registrationDTO.getEmail());
|
||||
return new ResponseEntity<>(authenticationService.registerUser(registrationDTO), HttpStatus.OK);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentifiziert einen Benutzer und gibt ein JWT zurück
|
||||
*
|
||||
* @param auth Anmeldedaten des Benutzers
|
||||
* @return LoginResponseDTO mit JWT und Benutzerdaten
|
||||
*/
|
||||
@Operation(summary = "Authentifiziert einen Benutzer", description = "Prüft den Benutzernamen und das Passwort und gibt ein JWT zurück")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Erfolgreiche Anmeldung",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
||||
@ApiResponse(responseCode = "401", description = "Ungültiger Benutzername oder Passwort",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<LoginResponseDTO> login(@RequestBody UserAuthenticationPairDTO auth) {
|
||||
LoginResponseDTO responseDTO = authenticationService.login(auth);
|
||||
|
||||
if(responseDTO.getUserDTO() == null) {
|
||||
return new ResponseEntity<>(responseDTO, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.security.models;
|
||||
|
||||
import SuMoC.backend.models.dto.UserDTO;
|
||||
|
||||
public class LoginResponseDTO {
|
||||
|
||||
//TODO: Change to needed UserInformation
|
||||
private UserDTO userDTO;
|
||||
private String jwt;
|
||||
|
||||
public LoginResponseDTO(UserDTO userDTO, String jwt){
|
||||
this.userDTO = userDTO;
|
||||
this.jwt = jwt;
|
||||
}
|
||||
|
||||
public UserDTO getUserDTO() {
|
||||
return userDTO;
|
||||
}
|
||||
|
||||
public void setUserDTO(UserDTO userDTO) {
|
||||
this.userDTO = userDTO;
|
||||
}
|
||||
|
||||
public String getJwt() {
|
||||
return jwt;
|
||||
}
|
||||
|
||||
public void setJwt(String jwt) {
|
||||
this.jwt = jwt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package SuMoC.backend.security.models;
|
||||
|
||||
public class UserAuthenticationPairDTO {
|
||||
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
public UserAuthenticationPairDTO(String email, String password){
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package SuMoC.backend.security.models;
|
||||
|
||||
public class UserRegistrationDTO {
|
||||
|
||||
private String username;
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
public UserRegistrationDTO(String username, String email, String password){
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package SuMoC.backend.security.services;
|
||||
|
||||
import SuMoC.backend.mapper.UserMapper;
|
||||
import SuMoC.backend.models.RoleName;
|
||||
import SuMoC.backend.models.User;
|
||||
import SuMoC.backend.models.dto.UserDTO;
|
||||
|
||||
import SuMoC.backend.repositories.UserRepository;
|
||||
import SuMoC.backend.security.models.LoginResponseDTO;
|
||||
import SuMoC.backend.security.models.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.models.UserRegistrationDTO;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class AuthenticationService {
|
||||
|
||||
private UserRepository userRepository;
|
||||
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
private TokenService tokenService;
|
||||
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder,
|
||||
AuthenticationManager authenticationManager, TokenService tokenService,
|
||||
UserMapper userMapper) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.tokenService = tokenService;
|
||||
this.userMapper = userMapper;
|
||||
}
|
||||
|
||||
public LoginResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
|
||||
|
||||
try {
|
||||
// Prüfen, ob der Benutzername bereits existiert
|
||||
if (userRepository.existsByUsername(registrationDTO.getUsername())) {
|
||||
throw new IllegalArgumentException("Benutzername ist bereits vergeben");
|
||||
}
|
||||
|
||||
//
|
||||
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
||||
if (!registrationDTO.getEmail().matches(emailRegex)) {
|
||||
throw new IllegalArgumentException("Ungültige E-Mail-Adresse");
|
||||
}
|
||||
|
||||
// Passwort verschlüsseln
|
||||
String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword());
|
||||
|
||||
// Rolle "USER" zuweisen
|
||||
Set<RoleName> roles = new HashSet<>();
|
||||
roles.add(RoleName.USER);
|
||||
|
||||
// Neuen Benutzer erstellen und speichern
|
||||
User user = new User(registrationDTO.getUsername(), registrationDTO.getEmail(), encodedPassword, roles);
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail(), registrationDTO.getPassword()));
|
||||
|
||||
|
||||
return loginResponseDTO;
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.err.println("Registration error: " + e.getMessage());
|
||||
return new LoginResponseDTO(null, "");
|
||||
}
|
||||
}
|
||||
|
||||
public LoginResponseDTO login(UserAuthenticationPairDTO authPairDTO) {
|
||||
// System.out.println(" ##################### Login Request ##################### ");
|
||||
// System.out.println(authPairDTO);
|
||||
// System.out.println(authPairDTO.getEmail());
|
||||
// System.out.println(authPairDTO.getPassword());
|
||||
try {
|
||||
|
||||
Authentication auth = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail(), authPairDTO.getPassword())
|
||||
);
|
||||
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail()).get();
|
||||
UserDTO userDTO = new UserDTO(user.getId(), user.getUsername(), user.getRoles());
|
||||
|
||||
String token = tokenService.generateUserJwt(auth, userDTO);
|
||||
|
||||
return new LoginResponseDTO(userDTO, token);
|
||||
|
||||
} catch (AuthenticationException e) {
|
||||
System.out.println("AuthenticationException: " + e.getMessage());
|
||||
return new LoginResponseDTO(null, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package SuMoC.backend.security.services;
|
||||
|
||||
import SuMoC.backend.models.dto.UserDTO;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class TokenService {
|
||||
|
||||
private JwtEncoder jwtEncoder;
|
||||
private JwtDecoder jwtDecoder;
|
||||
|
||||
@Autowired
|
||||
public TokenService(JwtEncoder jwtEncoder, JwtDecoder jwtDecoder){
|
||||
this.jwtEncoder = jwtEncoder;
|
||||
this.jwtDecoder = jwtDecoder;
|
||||
}
|
||||
|
||||
//TODO: Tokens could have a TTL
|
||||
public String generateUserJwt(Authentication auth, UserDTO userDTO){
|
||||
|
||||
System.out.println(auth.getName());
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
List<String> roles = auth.getAuthorities().stream()
|
||||
.map(authority -> authority.getAuthority().replace("ROLE_", "")) // <- WICHTIG!
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//CLAIMS define the Payload of the JWT, stores user Data etc. Payload is not encrypted, so no secret data shall be saved stored in a jwt
|
||||
JwtClaimsSet claims = JwtClaimsSet.builder()
|
||||
.issuer("self")
|
||||
.issuedAt(now)
|
||||
.subject(auth.getName())
|
||||
.claim("roles",roles)
|
||||
.claim("userId", userDTO.getId())
|
||||
.claim("username", userDTO.getUsername())
|
||||
.build();
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
|
||||
//TODO: change return type
|
||||
public void decodeJwt(String jwt){
|
||||
System.out.println("###############DECODED JWT##################");
|
||||
System.out.println(jwtDecoder.decode(jwt).getClaims());
|
||||
System.out.println("############################################");
|
||||
}
|
||||
|
||||
public Integer getUserIdFromToken(String jwt){
|
||||
return Math.toIntExact(jwtDecoder.decode(jwt).getClaim("userId"));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package SuMoC.backend.security.services;
|
||||
|
||||
|
||||
import SuMoC.backend.models.User;
|
||||
import SuMoC.backend.repositories.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class Userservice implements UserDetailsService {
|
||||
|
||||
private PasswordEncoder encoder;
|
||||
|
||||
private UserRepository userRepository;
|
||||
|
||||
|
||||
@Autowired
|
||||
public Userservice(PasswordEncoder encoder, UserRepository userRepository){
|
||||
this.encoder = encoder;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||
// Jetzt suchen wir nach der E-Mail-Adresse
|
||||
User user = userRepository.findByEmail(email)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("user not found with email: " + email));
|
||||
|
||||
// Mappen des Users auf Spring Security UserDetails
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
user.getEmail(),
|
||||
user.getPassword(),
|
||||
user.getRoles().stream()
|
||||
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.name()))
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public Optional<User> getUserById(Long id){
|
||||
return userRepository.findById(id);
|
||||
}
|
||||
|
||||
public Optional<User> getUserByUsername(String username){
|
||||
return userRepository.findByUsername(username);
|
||||
}
|
||||
|
||||
public void saveUser(User user){
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public boolean doesUserExist(Long userId){
|
||||
return this.userRepository.findById(userId).isPresent();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.security.utils;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
|
||||
public class KeyGeneratorUtility {
|
||||
|
||||
public static KeyPair generateRsaKey(){
|
||||
|
||||
KeyPair keyPair;
|
||||
|
||||
try{
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(2048);
|
||||
keyPair = keyPairGenerator.generateKeyPair();
|
||||
} catch (Exception e){
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
return keyPair;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package SuMoC.backend.security.utils;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
|
||||
@Component
|
||||
public class RSAKeyProperties {
|
||||
|
||||
private RSAPublicKey publicKey;
|
||||
private RSAPrivateKey privateKey;
|
||||
|
||||
public RSAKeyProperties(){
|
||||
KeyPair pair = KeyGeneratorUtility.generateRsaKey();
|
||||
this.publicKey = (RSAPublicKey) pair.getPublic();
|
||||
this.privateKey = (RSAPrivateKey) pair.getPrivate();
|
||||
}
|
||||
|
||||
public RSAPublicKey getPublicKey() {
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
public void setPublicKey(RSAPublicKey publicKey) {
|
||||
this.publicKey = publicKey;
|
||||
}
|
||||
|
||||
public RSAPrivateKey getPrivateKey() {
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public void setPrivateKey(RSAPrivateKey privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user