Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
1.9 kB
2
Indexable
Never
 public String convertWithToken(String token, UserEntity user) {

        try {

            Jws<Claims> claims = keycloakJwt.buildJwtParser().parseClaimsJws(token);

            log.info("Claim: {}", claims);

            String username = String.valueOf(claims.getBody().get(JwtConstant.PREFERRED_NAME_CLAIM)).toLowerCase();

            String email = String.valueOf(claims.getBody().get(JwtConstant.EMAIL_CLAIM)).toLowerCase();

            String givenName = String.valueOf(claims.getBody().get(JwtConstant.GIVEN_NAME_CLAIM)).toLowerCase();

            int issuedAt = Integer.parseInt(claims.getBody().get(JwtConstant.IAT_KEY_CLAIM).toString());

            int expiration = Integer.parseInt(claims.getBody().get(JwtConstant.EXP_KEY_CLAIM).toString());

            Date issuedAtTime = Date.from(Instant.ofEpochSecond(issuedAt));

            Date expirationTime = Date.from(Instant.ofEpochSecond(expiration));

            List<UserPermissionData> roleGroups = roleGroupService.getAllByUserId(user.getId());

            Set<String> roleGroupSet = roleGroups.stream().map(rg -> rg.getRoleGroupCode()).collect(Collectors.toSet());

            return internalJwt.buildJwtBuilder()
                    .setSubject(username)
                    .claim(JwtConstant.EMAIL_CLAIM, email)
                    .claim(JwtConstant.GIVEN_NAME_CLAIM, givenName)
                    .claim(JwtConstant.SUPPORT_BY_CLAIM, "")
                    .claim(JwtConstant.ROLE_GROUP_CLAIM, roleGroupSet)
                    .setIssuedAt(issuedAtTime)
                    .setExpiration(expirationTime)
                    .setIssuer(Constant.SYSTEM_CODE)
                    .compact();

        } catch (Exception e) {

            log.info("Exception: {}", e.getMessage());
            throw new BadRequestException(IAMErrorCode.JWT_CONVERT_ERROR);

        }

    }
Leave a Comment