/** * Get the enterprise token witch can used to invoke admin api,such as managing departments and groups * * @param enterpriseId Your enterprise id * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60) * @return Detailed user access information * @throws YfyException */ public YfyAuthFinish getEnterpriseToken(long enterpriseId, int expirationTimeSeconds) throws YfyException { Claims claims = new DefaultClaims(); claims.put("yifangyun_sub_type", "enterprise"); claims.setSubject(String.valueOf(enterpriseId)); claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds)); claims.setIssuedAt(new Date()); claims.setId(getGeneratedJwtId(16)); final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact(); return YfyRequestUtil.doPostInAuth( requestConfig, YfyAppInfo.getHost().getAuth(), "oauth/token", new HashMap<String, String>() {{ put("grant_type", "jwt"); put("assertion", compactJws); }}, YfyAuthFinish.class); }
/** * Get the user token witch can used to invoke personal api,such as get folder information * * @param userId The user you want to operate with * @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60) * @return Detailed user access information * @throws YfyException */ public YfyAuthFinish getUserToken(long userId, int expirationTimeSeconds) throws YfyException { Claims claims = new DefaultClaims(); claims.put("yifangyun_sub_type", "user"); claims.setSubject(String.valueOf(userId)); claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds)); claims.setIssuedAt(new Date()); claims.setId(getGeneratedJwtId(16)); final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact(); return YfyRequestUtil.doPostInAuth( requestConfig, YfyAppInfo.getHost().getAuth(), "oauth/token", new HashMap<String, String>() {{ put("grant_type", "jwt"); put("assertion", compactJws); }}, YfyAuthFinish.class); }
@Test public void generates_credentials_file_for_valid_token() throws Exception { when(lambdaAuthorizer.getClaims(eq("test-user"), eq("token"))) .thenReturn(new DefaultClaims()); when(temporaryCredentialsProvider.getFederatedTokenFor(eq("test-user"))) .thenReturn(validCredentials()); lambdaHandler.handleRequest(jsonPayloadAsStream("test-user", "token"), outputStream, context); String credentialsFile = outputStream.toString(); assertThat(credentialsFile, containsString("expectedRegion")); assertThat(credentialsFile, containsString("expectedBucket")); assertThat(credentialsFile, containsString("expectedUser"+"/")); assertThat(credentialsFile, containsString("expectedKeyId")); assertThat(credentialsFile, containsString("expectedSecretKey")); assertThat(credentialsFile, containsString("expectedSessionToken")); }
/** * Generate a new JWT for the given user * * @param secretBytes The JWT secret as byte array * @param user The user to encode the token for * @return The generated token as string */ public String generateAuthorizationToken(@NotNull byte[] secretBytes, @NotNull User user) { Claims claims = new DefaultClaims(); claims.put(CLAIMS_TOKEN_TYPE, TokenType.AUTH); if (user.isCaster()) { claims.put(CLAIMS_USER_TYPE, TokenUserType.CASTER); } else if (user.isModerator()) { claims.put(CLAIMS_USER_TYPE, TokenUserType.MODERATOR); } else { throw new IllegalStateException("User \"" + user.getDisplayName() + "\" is not a caster nor a moderator"); } return generateToken(secretBytes, claims, user, authTokenExpiry); }
private Claims getClaims() { Map map = new HashMap<String ,String>() {{ put("GUAC_ID", "12345"); put("guac.hostname", "192.168.42.2"); put("guac.protocol", "vnc"); put("guac.password", "123456"); }}; return new DefaultClaims(map); }
final protected Claims createClaimsFromToken(String token) { try { DefaultClaims claims = (DefaultClaims)Jwts.parser() .setSigningKey(jwtConfig.getSigningKey()) .parse(token) .getBody(); return claims; } catch (Exception e) { throw new ServiceException(JwtErrors.CM_ERROR_TOKEN, e); } }
/** * Performs local and Keycloak accounts linking * * @return typically Response that redirect user for OAuth provider site */ @GET @Path("authenticate") public Response authenticate( @Required @QueryParam("oauth_provider") String oauthProvider, @Required @QueryParam("redirect_after_login") String redirectAfterLogin, @Context HttpServletRequest request) throws ForbiddenException, BadRequestException { Jwt jwtToken = (Jwt) request.getAttribute("token"); if (jwtToken == null) { throw new BadRequestException("No token provided."); } DefaultClaims claims = (DefaultClaims) jwtToken.getBody(); final String clientId = claims.getAudience(); final String nonce = UUID.randomUUID().toString(); final String sessionState = claims.get("session_state", String.class); MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } final String input = nonce + sessionState + clientId + oauthProvider; byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8)); final String hash = Base64.getUrlEncoder().encodeToString(check); request.getSession().setAttribute("hash", hash); // TODO: for what? String accountLinkUrl = UriBuilder.fromUri(keycloakConfiguration.get().get(AUTH_SERVER_URL_SETTING)) .path("/realms/{realm}/broker/{provider}/link") .queryParam("nonce", nonce) .queryParam("hash", hash) .queryParam("client_id", clientId) .queryParam("redirect_uri", redirectAfterLogin) .build(keycloakConfiguration.get().get(REALM_SETTING), oauthProvider) .toString(); return Response.temporaryRedirect(URI.create(accountLinkUrl)).build(); }
public String generateRefreshToken(byte[] secretBytes, User user) { DefaultClaims claims = new DefaultClaims(); claims.put(CLAIMS_TOKEN_TYPE, TokenType.REFRESH); return generateToken(secretBytes, claims, user, refreshTokenExpiry); }
/** * Returns a new {@link Claims} instance to be used as a JWT body. * * @return a new {@link Claims} instance to be used as a JWT body. */ public static Claims claims() { return new DefaultClaims(); }