use of org.jose4j.jwt.JwtClaims in project cas by apereo.
the class OidcIdTokenGeneratorService method generate.
/**
* Generate string.
*
* @param request the request
* @param response the response
* @param accessTokenId the access token id
* @param timeout the timeout
* @param responseType the response type
* @param registeredService the registered service
* @return the string
* @throws Exception the exception
*/
public String generate(final HttpServletRequest request, final HttpServletResponse response, final AccessToken accessTokenId, final long timeout, final OAuth20ResponseTypes responseType, final OAuthRegisteredService registeredService) throws Exception {
if (!(registeredService instanceof OidcRegisteredService)) {
throw new IllegalArgumentException("Registered service instance is not an OIDC service");
}
final OidcRegisteredService oidcRegisteredService = (OidcRegisteredService) registeredService;
final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
final Optional<UserProfile> profile = manager.get(true);
LOGGER.debug("Attempting to produce claims for the id token [{}]", accessTokenId);
final JwtClaims claims = produceIdTokenClaims(request, accessTokenId, timeout, oidcRegisteredService, profile.get(), context, responseType);
LOGGER.debug("Produce claims for the id token [{}] as [{}]", accessTokenId, claims);
return this.signingService.encode(oidcRegisteredService, claims);
}
use of org.jose4j.jwt.JwtClaims in project cas by apereo.
the class BasePasswordManagementService method createToken.
@Override
public String createToken(final String to) {
try {
final String token = UUID.randomUUID().toString();
final JwtClaims claims = new JwtClaims();
claims.setJwtId(token);
claims.setIssuer(issuer);
claims.setAudience(issuer);
claims.setExpirationTimeMinutesInTheFuture(properties.getReset().getExpirationMinutes());
claims.setIssuedAtToNow();
final ClientInfo holder = ClientInfoHolder.getClientInfo();
claims.setStringClaim("origin", holder.getServerIpAddress());
claims.setStringClaim("client", holder.getClientIpAddress());
claims.setSubject(to);
final String json = claims.toJson();
return this.cipherExecutor.encode(json);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
use of org.jose4j.jwt.JwtClaims in project light-portal by networknt.
the class JwtToken method handle.
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
((Map<String, Object>) input).forEach((k, v) -> claims.setClaim(k, v));
String jwt = "";
try {
jwt = JwtIssuer.getJwt(claims);
} catch (JoseException e) {
logger.error("JoseException:", e);
}
return NioUtils.toByteBuffer(jwt);
}
use of org.jose4j.jwt.JwtClaims in project stdlib by petergeneric.
the class JwtCreationRestServiceImpl method getResult.
@Override
public String getResult(String token, final String secret, final String payload, final String op) {
final TemplateCall template = templater.template(PREFIX + "jwt_generated.html");
final Long expireTime;
if (token == null) {
try {
JwtClaims claims = JwtClaims.parse(payload);
if (claims.getExpirationTime() != null)
expireTime = claims.getExpirationTime().getValueInMillis();
else
expireTime = null;
token = createJWT(secret, payload);
} catch (InvalidJwtException | MalformedClaimException | JoseException e) {
throw new RuntimeException(e);
}
} else {
// User has provided a JWT. We should simply parse it and extract the expiry time (for the cookie)
try {
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
final JwtClaims claims = jwtConsumer.processToClaims(token);
if (claims.getExpirationTime() != null)
expireTime = claims.getExpirationTime().getValueInMillis();
else
expireTime = null;
} catch (InvalidJwtException | MalformedClaimException e) {
throw new RuntimeException(e);
}
}
final boolean save = StringUtils.equalsIgnoreCase("save", op);
// Optionally save as a cookie
if (save) {
Cookie cookie = new Cookie(cookieName, token);
// Set the cookie path based on the webapp endpoint path
cookie.setPath(webappEndpoint.getPath());
// If the webapp has an https endpoint (or if we were accessed by HTTPS) then set the cookie as a secure cookie
cookie.setSecure(HttpCallContext.get().getRequest().isSecure() || StringUtils.equalsIgnoreCase("https", webappEndpoint.getScheme()));
// Expire the cookie 1 minute before the token expires
if (expireTime != null)
cookie.setMaxAge(expireTime.intValue() - 60);
// Kill the current session (just in case it's associated with a job manager login)
final HttpSession session = HttpCallContext.get().getRequest().getSession(false);
if (session != null) {
session.invalidate();
}
// Now add the JWT cookie
HttpCallContext.get().getResponse().addCookie(cookie);
}
template.set("saved", save);
template.set("token", token);
return template.process();
}
use of org.jose4j.jwt.JwtClaims in project blockchain-java-api-client by astarlabs.
the class Token method sign.
public static String sign(String key) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String decoded = new String(Hex.decode(key));
String replaced = decoded.replaceAll("-----BEGIN RSA PRIVATE KEY-----", "").replaceAll("-----END RSA PRIVATE KEY-----", "").replaceAll("\\s", "");
byte[] encodedPrivateKey = Base64.getDecoder().decode(replaced);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
PrivateKey privKey = kf.generatePrivate(keySpec);
JwtClaims claims = new JwtClaims();
claims.setExpirationTimeMinutesInTheFuture(10);
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(2);
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(privKey);
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String innerJwt = jws.getCompactSerialization();
return innerJwt;
}
Aggregations