use of com.auth0.android.jwt.JWT in project spring-learning by moon-zhou.
the class JwtUtil method sign.
/**
* 生成签名,15分钟后过期
*
* @param username
* @param userId
* @return
*/
public static String sign(String username, String userId, String password) {
// 过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(password);
// 设置头信息
HashMap<String, Object> header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");
// 附带username和userID生成签名
return JWT.create().withHeader(header).withClaim("userId", userId).withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
use of com.auth0.android.jwt.JWT in project spring-learning by moon-zhou.
the class JWTTest method testJWTVerify.
/**
* 验证JWT生成的token
*
* 为了方便测试,定义了类变量,整体用例可直接执行
*/
@Test
public void testJWTVerify() {
final JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
final DecodedJWT decodedJWT = jwtVerifier.verify(token);
int decodeUserId = decodedJWT.getClaim(USER_ID).asInt();
String decodeUserName = decodedJWT.getClaim(USER_NAME).asString();
System.out.println("用户Id:" + decodeUserId);
System.out.println("用户名:" + decodeUserName);
System.out.println("过期时间:" + decodedJWT.getExpiresAt());
Assertions.assertEquals(userId, decodeUserId);
Assertions.assertEquals(userName, decodeUserName);
}
use of com.auth0.android.jwt.JWT in project goobi-workflow by intranda.
the class Login method openIdLogin.
@POST
@Path("/openid")
@Operation(summary = "OpenID connect callback", description = "Verifies an openID claim and starts a session for the user")
@ApiResponse(responseCode = "200", description = "OK")
@ApiResponse(responseCode = "400", description = "Bad request")
@ApiResponse(responseCode = "500", description = "Internal error")
public void openIdLogin(@FormParam("error") String error, @FormParam("id_token") String idToken) throws IOException {
ConfigurationHelper config = ConfigurationHelper.getInstance();
String clientID = config.getOIDCClientID();
String nonce = (String) servletRequest.getSession().getAttribute("openIDNonce");
if (error == null) {
// no error - we should have a token. Verify it.
DecodedJWT jwt = JwtHelper.verifyOpenIdToken(idToken);
if (jwt != null) {
// now check if the nonce is the same as in the old session
if (nonce.equals(jwt.getClaim("nonce").asString()) && clientID.equals(jwt.getClaim("aud").asString())) {
// all OK, login the user
HttpSession session = servletRequest.getSession();
LoginBean userBean = Helper.getLoginBeanFromSession(session);
// get the user by the configured claim from the JWT
String login = jwt.getClaim(config.getOIDCIdClaim()).asString();
log.debug("logging in user " + login);
User user = UserManager.getUserBySsoId(login);
if (user == null) {
userBean.setSsoError("Could not find user in Goobi database. Please contact your admin to add your SSO ID to the database.");
servletResponse.sendRedirect("/goobi/uii/logout.xhtml");
return;
}
userBean.setSsoError(null);
user.lazyLoad();
userBean.setMyBenutzer(user);
userBean.setRoles(user.getAllUserRoles());
userBean.setMyBenutzer(user);
// add the user to the sessionform that holds information about all logged in users
sessionForm.updateSessionUserName(servletRequest.getSession(), user);
} else {
if (!nonce.equals(jwt.getClaim("nonce").asString())) {
log.error("nonce does not match. Not logging user in");
}
if (!clientID.equals(jwt.getClaim("aud").asString())) {
log.error("clientID does not match aud. Not logging user in");
}
}
} else {
log.error("could not verify JWT");
}
} else {
log.error(error);
}
servletResponse.sendRedirect("/goobi/index.xhtml");
}
use of com.auth0.android.jwt.JWT in project AuthGuard by AuthGuard.
the class JwtConfigParserTest method parseRsa512.
@Test
void parseRsa512() {
final String publicKeyPath = "src/test/resources/rsa512-public.pem";
final String privateKeyPath = "src/test/resources/rsa512-private.pem";
final Algorithm algorithm = JwtConfigParser.parseAlgorithm("RSA512", publicKeyPath, privateKeyPath);
final String jwt = JWT.create().withClaim("claim", "value").sign(algorithm);
algorithm.verify(JWT.decode(jwt));
}
use of com.auth0.android.jwt.JWT in project einstein-bot-sdk-java by forcedotcom.
the class JwtBearerOAuth method getToken.
@Override
public String getToken() {
Optional<String> token = cache.flatMap(c -> c.get(getCacheKey()));
if (token.isPresent()) {
logger.debug("Found cached OAuth token.");
return token.get();
}
logger.debug("Did not find OAuth token in cache. Will retrieve from OAuth server.");
Instant now = Instant.now();
String jwt = null;
try {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("alg", "RS256");
Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
jwt = JWT.create().withHeader(headers).withAudience(loginEndpoint).withExpiresAt(Date.from(now.plus(jwtExpiryMinutes, ChronoUnit.MINUTES))).withIssuer(connectedAppId).withSubject(userId).sign(algorithm);
logger.debug("Generated jwt: {} ", jwt);
} catch (JWTCreationException exception) {
// Invalid Signing configuration / Couldn't convert Claims.
throw new RuntimeException(exception);
}
String response = webClient.post().uri("/services/oauth2/token").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(BodyInserters.fromFormData("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer").with("assertion", jwt)).retrieve().bodyToMono(String.class).block();
String oAuthToken = null;
try {
ObjectNode node = new ObjectMapper().readValue(response, ObjectNode.class);
oAuthToken = node.get("access_token").asText();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
IntrospectionResult iResult = introspector.introspect(oAuthToken);
if (!iResult.isActive()) {
throw new RuntimeException("OAuth token is not active.");
}
Instant expiry = Instant.ofEpochSecond(iResult.getExp());
long ttl = Math.max(0, Instant.now().until(expiry, ChronoUnit.SECONDS) - 300);
if (cache.isPresent()) {
cache.get().set(getCacheKey(), oAuthToken, ttl);
}
return oAuthToken;
}
Aggregations