package SuMoC.backend.security.services; import SuMoC.backend.user.dtos.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 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("privateName", userDTO.getPrivateName()) .build(); return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue(); } // Re-Authentification after change of email public String generateUserJwt(Authentication auth, UserDTO userDTO, String email){ System.out.println(auth.getName()); Instant now = Instant.now(); List 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(email) .claim("roles",roles) .claim("userId", userDTO.getId()) .claim("privateName", userDTO.getPrivateName()) .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")); } }