use of com.auth0.android.jwt.Claim in project structr by structr.
the class JWTHelper method getUserForAccessTokenWithSecret.
private static Principal getUserForAccessTokenWithSecret(String token, PropertyKey<String> eMailKey) throws FrameworkException {
final String secret = Settings.JWTSecret.getValue();
Map<String, Claim> claims = validateTokenWithSecret(token, secret);
if (claims == null) {
return null;
}
Principal user = getPrincipalForTokenClaims(claims, eMailKey);
if (user == null) {
return null;
}
// Check if the access_token is still valid.
// If access_token isn't valid anymore, then either it timed out, or the user logged out.
String tokenReference = claims.getOrDefault("tokenId", new NullClaim()).asString();
if (validateTokenForUser(tokenReference, user)) {
return user;
}
return null;
}
use of com.auth0.android.jwt.Claim in project structr by structr.
the class JWTHelper method getPrincipalForTokenClaims.
private static Principal getPrincipalForTokenClaims(Map<String, Claim> claims, PropertyKey<String> eMailKey) throws FrameworkException {
final String instanceName = Settings.InstanceName.getValue();
Principal user = null;
String instance = claims.getOrDefault("instance", new NullClaim()).asString();
String uuid = claims.getOrDefault("uuid", new NullClaim()).asString();
String eMail = claims.getOrDefault("eMail", new NullClaim()).asString();
if (StringUtils.isEmpty(eMail)) {
eMail = claims.getOrDefault("email", new NullClaim()).asString();
}
// if the instance is the same that issued the token, we can lookup the user with uuid claim
if (StringUtils.equals(instance, instanceName)) {
user = StructrApp.getInstance().nodeQuery(Principal.class).and().or(NodeInterface.id, uuid).disableSorting().getFirst();
} else if (eMail != null && StringUtils.isNotEmpty(eMail)) {
user = StructrApp.getInstance().nodeQuery(Principal.class).and().or(eMailKey, eMail).disableSorting().getFirst();
}
return user;
}
use of com.auth0.android.jwt.Claim in project mycore by MyCoRe-Org.
the class MCRSessionFilter method filter.
@Override
public void filter(ContainerRequestContext requestContext) {
LOGGER.debug("Filter start.");
boolean isSecure = requestContext.getSecurityContext().isSecure();
if (MCRSessionMgr.hasCurrentSession()) {
throw new InternalServerErrorException("Session is already attached.");
}
MCRSessionMgr.unlock();
// bind to this request
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
currentSession.setCurrentIP(MCRFrontendUtil.getRemoteAddr(httpServletRequest));
MCRTransactionHelper.beginTransaction();
// 3 cases for authentication
Optional<MCRUserInformation> userInformation = Optional.empty();
String authorization = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// 1. no authentication
if (authorization == null) {
LOGGER.debug("No 'Authorization' header");
return;
}
// 2. Basic Authentification
String basicPrefix = "Basic ";
if (authorization.startsWith(basicPrefix)) {
LOGGER.debug("Using 'Basic' authentication.");
byte[] encodedAuth = authorization.substring(basicPrefix.length()).trim().getBytes(StandardCharsets.ISO_8859_1);
String userPwd = new String(Base64.getDecoder().decode(encodedAuth), StandardCharsets.ISO_8859_1);
if (userPwd.contains(":") && userPwd.length() > 1) {
String[] upSplit = userPwd.split(":");
String username = upSplit[0];
String password = upSplit[1];
userInformation = Optional.ofNullable(MCRUserManager.checkPassword(username, password)).map(MCRUserInformation.class::cast).map(Optional::of).orElseThrow(() -> {
LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
attrs.put("error", "invalid_login");
attrs.put("error_description", "Wrong login or password.");
return new NotAuthorizedException(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, MCRRestAPIUtil.getWWWAuthenticateHeader(null, attrs, app)).build());
});
}
}
// 3. JWT
String bearerPrefix = "Bearer ";
if (authorization.startsWith(bearerPrefix)) {
LOGGER.debug("Using 'JSON Web Token' authentication.");
// get JWT
String token = authorization.substring(bearerPrefix.length()).trim();
// validate against secret
try {
DecodedJWT jwt = JWT.require(MCRJWTUtil.getJWTAlgorithm()).build().verify(token);
// validate ip
checkIPClaim(jwt.getClaim(MCRJWTUtil.JWT_CLAIM_IP), MCRFrontendUtil.getRemoteAddr(httpServletRequest));
// validate in audience
Optional<String> audience = jwt.getAudience().stream().filter(s -> MCRJWTResource.AUDIENCE.equals(s) || MCRRestAPIAuthentication.AUDIENCE.equals(s)).findAny();
if (audience.isPresent()) {
switch(audience.get()) {
case MCRJWTResource.AUDIENCE:
MCRJWTResource.validate(token);
break;
case MCRRestAPIAuthentication.AUDIENCE:
requestContext.setProperty(PROP_RENEW_JWT, true);
MCRRestAPIAuthentication.validate(token);
break;
default:
LOGGER.warn("Cannot validate JWT for '{}' audience.", audience.get());
}
}
userInformation = Optional.of(new MCRJWTUserInformation(jwt));
if (!ALLOWED_JWT_SESSION_ATTRIBUTES.isEmpty()) {
for (Map.Entry<String, Claim> entry : jwt.getClaims().entrySet()) {
if (entry.getKey().startsWith(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX)) {
final String key = entry.getKey().substring(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX.length());
for (String prefix : ALLOWED_JWT_SESSION_ATTRIBUTES) {
if (key.startsWith(prefix)) {
currentSession.put(key, entry.getValue().asString());
break;
}
}
}
}
}
} catch (JWTVerificationException e) {
LOGGER.error(e.getMessage());
LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
attrs.put("error", "invalid_token");
attrs.put("error_description", e.getMessage());
throw new NotAuthorizedException(e.getMessage(), e, MCRRestAPIUtil.getWWWAuthenticateHeader("Bearer", attrs, app));
}
}
if (userInformation.isEmpty()) {
LOGGER.warn(() -> "Unsupported " + HttpHeaders.AUTHORIZATION + " header: " + authorization);
}
userInformation.ifPresent(ui -> {
currentSession.setUserInformation(ui);
requestContext.setSecurityContext(new MCRRestSecurityContext(ui, isSecure));
});
LOGGER.info("user detected: " + currentSession.getUserInformation().getUserID());
}
use of com.auth0.android.jwt.Claim in project sda-dropwizard-commons by SDA-SE.
the class AuthBuilderTest method shouldAddStringClaim.
@Test
public void shouldAddStringClaim() {
String token = authBuilder.addClaim("testKey", "hello").buildToken();
Claim claim = JWT.decode(token).getClaim("testKey");
assertThat(claim.asString()).isEqualTo("hello");
}
use of com.auth0.android.jwt.Claim in project sda-dropwizard-commons by SDA-SE.
the class AuthBuilderTest method shouldAddLongClaim.
@Test
public void shouldAddLongClaim() {
String token = authBuilder.addClaim("testKey", 2L + Integer.MAX_VALUE).buildToken();
Claim claim = JWT.decode(token).getClaim("testKey");
assertThat(claim.asLong()).isEqualTo(2147483649L);
}
Aggregations