Hinzufügen von Spring Security Login und Registierung. Basis implementierung von User und zugehörige DatenTransferObjekte.

This commit is contained in:
2025-11-12 21:59:31 +01:00
parent 2c7874f02d
commit 6b10aafbd3
18 changed files with 806 additions and 2 deletions
@@ -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"));
}
}