use of com.auth0.android.jwt.Claim in project commons by mosip.
the class TokenHandlerUtil method isValidBearerToken.
/**
* Validates the token offline based on the Oauth2 standards.
*
* @param accessToken
* - Bearer token
* @param issuerUrl
* - issuer URL to be read from the properties,
* @param clientId
* - client Id to be read from the properties
* @return Boolean
*/
public static boolean isValidBearerToken(String accessToken, String issuerUrl, String clientId) {
try {
DecodedJWT decodedJWT = decodedTokens.get(accessToken);
if (decodedJWT == null) {
decodedJWT = JWT.decode(accessToken);
decodedTokens.put(accessToken, decodedJWT);
}
Map<String, Claim> claims = decodedJWT.getClaims();
LocalDateTime expiryTime = DateUtils.convertUTCToLocalDateTime(DateUtils.getUTCTimeFromDate(decodedJWT.getExpiresAt()));
if (!decodedJWT.getIssuer().equals(issuerUrl)) {
return false;
} else if (!DateUtils.before(DateUtils.getUTCCurrentDateTime(), expiryTime)) {
return false;
} else if (!claims.get("clientId").asString().equals(clientId)) {
return false;
} else {
return true;
}
} catch (JWTDecodeException e) {
LOGGER.error("JWT DECODE EXCEPTION ::".concat(e.getMessage()).concat(ExceptionUtils.getStackTrace(e)));
return false;
} catch (Exception e) {
LOGGER.error(e.getMessage().concat(ExceptionUtils.getStackTrace(e)));
return false;
}
}
use of com.auth0.android.jwt.Claim in project edge-cloud-sampleapps by mobiledgex.
the class RegisterClientTest method registerClientTest.
@Test
public void registerClientTest() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
MatchingEngine me = new MatchingEngine(context);
me.setUseWifiOnly(useWifiOnly);
me.setMatchingEngineLocationAllowed(true);
me.setAllowSwitchIfNoSubscriberInfo(true);
AppClient.RegisterClientReply reply = null;
String appName = applicationName;
try {
Location location = getTestLocation(47.6062, 122.3321);
AppClient.RegisterClientRequest request = me.createDefaultRegisterClientRequest(context, organizationName).setAppName(applicationName).setAppVers(appVersion).setCellId(getCellId(context, me)).build();
if (useHostOverride) {
reply = me.registerClient(request, hostOverride, portOverride, GRPC_TIMEOUT_MS);
} else {
reply = me.registerClient(request, me.generateDmeHostAddress(), me.getPort(), GRPC_TIMEOUT_MS);
}
JWT jwt = null;
try {
jwt = new JWT(reply.getSessionCookie());
} catch (DecodeException e) {
Log.e(TAG, Log.getStackTraceString(e));
assertFalse("registerClientTest: DecodeException!", true);
}
// Validate JWT
// 10 seconds leeway
boolean isExpired = jwt.isExpired(10);
assertTrue(!isExpired);
Log.i(TAG, "Claims count: " + jwt.getClaims().keySet().size());
for (String key : jwt.getClaims().keySet()) {
Claim claim = jwt.getClaims().get(key);
Log.i(TAG, "key: " + key + " Claim: " + claim.asString());
}
Claim c = jwt.getClaim("key");
JsonObject claimJson = c.asObject(JsonObject.class);
String orgName = claimJson.get("orgname").getAsString();
assertEquals("orgname doesn't match!", "MobiledgeX", orgName);
Log.i(TAG, "registerReply.getSessionCookie()=" + reply.getSessionCookie());
assertTrue(reply != null);
assertTrue(reply.getStatus() == AppClient.ReplyStatus.RS_SUCCESS);
assertTrue(!reply.getUniqueId().isEmpty());
assertTrue(reply.getSessionCookie().length() > 0);
} catch (PackageManager.NameNotFoundException nnfe) {
Log.e(TAG, Log.getStackTraceString(nnfe));
assertFalse("ExecutionException registering using PackageManager.", true);
} catch (DmeDnsException dde) {
Log.e(TAG, Log.getStackTraceString(dde));
assertFalse("registerClientTest: DmeDnsException!", true);
} catch (ExecutionException ee) {
Log.e(TAG, Log.getStackTraceString(ee));
assertFalse("registerClientTest: ExecutionException!", true);
} catch (StatusRuntimeException sre) {
Log.e(TAG, Log.getStackTraceString(sre));
assertFalse("registerClientTest: StatusRuntimeException!", true);
} catch (InterruptedException ie) {
Log.e(TAG, Log.getStackTraceString(ie));
assertFalse("registerClientTest: InterruptedException!", true);
}
Log.i(TAG, "registerClientTest reply: " + reply.toString());
assertEquals(0, reply.getVer());
assertEquals(AppClient.ReplyStatus.RS_SUCCESS, reply.getStatus());
}
use of com.auth0.android.jwt.Claim in project simple-jwt by vorbote.
the class AccessKeyUtil method Info.
/**
* Decode the token, and you can easily get some info from
* this token.
*
* @param token The token.
* @return The decoded jwt token.
* @throws com.auth0.jwt.exceptions.AlgorithmMismatchException If the algorithm stated in the token's
* header it's not equal to the one
* defined in the JWTVerifier.
* @throws com.auth0.jwt.exceptions.SignatureVerificationException If the signature is invalid.
* @throws com.auth0.jwt.exceptions.TokenExpiredException If the token has expired.
* @throws com.auth0.jwt.exceptions.InvalidClaimException If a claim contained a different value
* than the expected one.
* @throws com.auth0.jwt.exceptions.JWTVerificationException If any of the verification steps fail
* @see JWTVerifier#verify(String)
*/
public DecodedJWT Info(String token) {
JWTVerifier verifier;
switch(algorithm) {
case HS256:
verifier = JWT.require(Algorithm.HMAC256(secret)).build();
break;
case HS384:
verifier = JWT.require(Algorithm.HMAC384(secret)).build();
break;
case HS512:
verifier = JWT.require(Algorithm.HMAC512(secret)).build();
break;
default:
// 这里理论上应该抛出异常的,但是实在是懒得做了,就先这样吧。
// 至于其他的算法,后续再考虑加上。
verifier = JWT.require(Algorithm.HMAC256(secret)).build();
log.error("This algorithm is not supported yet, will use HMAC256 by default.");
}
return verifier.verify(token);
}
use of com.auth0.android.jwt.Claim in project jpsonic by tesshucom.
the class JWTAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication auth) {
JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
if (!(authentication.getCredentials() instanceof String)) {
LOG.error("Credentials not present");
return null;
}
String rawToken = (String) auth.getCredentials();
DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
authentication.setAuthenticated(true);
// TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
LOG.warn("BYPASSING AUTH FOR WEB-INF page");
} else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication.getRequestedPath() + ". They are valid for " + path.asString());
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
use of com.auth0.android.jwt.Claim in project jpsonic by tesshucom.
the class JWTSecurityServiceTest method testAddJWTToken.
// false positive
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
@Test
void testAddJWTToken() {
// Originally Parameterized was used. If possible, it is better to rewrite to the new
// spring-method.
Arrays.asList(new Object[][] { { "http://localhost:8080/jpsonic/stream?id=4", "/jpsonic/stream?id=4" }, { "/jpsonic/stream?id=4", "/jpsonic/stream?id=4" } }).forEach(o -> {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(o[0].toString());
String actualUri = jwtSecurityService.addJWTToken(builder).build().toUriString();
String jwtToken = UriComponentsBuilder.fromUriString(actualUri).build().getQueryParams().getFirst(JWTSecurityService.JWT_PARAM_NAME);
Algorithm algorithm = JWTSecurityService.getAlgorithm(settingsService.getJWTKey());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT verify = verifier.verify(jwtToken);
Claim claim = verify.getClaim(JWTSecurityService.CLAIM_PATH);
assertEquals(o[1], claim.asString());
});
}
Aggregations