use of com.auth0.json.mgmt.Token in project gravitee-api-management by gravitee-io.
the class OAuth2AuthenticationResourceTest method verifyJwtToken.
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
TokenEntity responseToken = response.readEntity(TokenEntity.class);
assertEquals("BEARER", responseToken.getType().name());
String token = responseToken.getToken();
Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT jwt = jwtVerifier.verify(token);
assertEquals(jwt.getSubject(), "janedoe@example.com");
assertEquals(jwt.getClaim("firstname").asString(), "Jane");
assertEquals(jwt.getClaim("iss").asString(), "gravitee-management-auth");
assertEquals(jwt.getClaim("sub").asString(), "janedoe@example.com");
assertEquals(jwt.getClaim("email").asString(), "janedoe@example.com");
assertEquals(jwt.getClaim("lastname").asString(), "Doe");
}
use of com.auth0.json.mgmt.Token in project gravitee-api-management by gravitee-io.
the class AuthResource method login.
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
// JWT signer
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured environment role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final Token tokenEntity = new Token();
tokenEntity.setTokenType(TokenTypeEnum.BEARER);
tokenEntity.setToken(sign);
final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
servletResponse.addCookie(bearerCookie);
return ok(tokenEntity).build();
}
return ok().build();
}
use of com.auth0.json.mgmt.Token in project cx-flow by checkmarx-ltd.
the class GitHubAppAuthService method getJwt.
private String getJwt(String appId) {
// Check if current token is set and if it is verified
LocalDateTime currentDateTime = LocalDateTime.now(ZoneOffset.UTC);
if (this.jwt != null) {
DecodedJWT decodedJwt = JWT.decode(this.jwt);
Instant currentTime = currentDateTime.plusMinutes(1).toInstant(ZoneOffset.UTC);
if (currentTime.isBefore(decodedJwt.getExpiresAt().toInstant())) {
return this.jwt;
}
}
// If the jwt was null or expired, we hit this block to create new
// 10 minutes in future
LocalDateTime exp = currentDateTime.plusMinutes(10);
assert this.privateKey != null;
Algorithm algorithm = Algorithm.RSA256(null, this.privateKey);
// set the current token and return it
this.jwt = JWT.create().withIssuer(appId).withIssuedAt(Date.from(currentDateTime.toInstant(ZoneOffset.UTC))).withExpiresAt(Date.from(exp.toInstant(ZoneOffset.UTC))).sign(algorithm);
return this.jwt;
}
use of com.auth0.json.mgmt.Token in project chemvantage by chuckwight.
the class Token method doGet.
// This servlet is the OpenID Connection starting point for platforms to reach ChemVantage
// The servlet identifies the deployment corresponding to the request, and returns a Java Web Token
// containing information needed for the subsequent launch request or other service request.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer debug = new StringBuffer("Issuing auth token:<br>");
try {
// store parameters required by third-party initiated login procedure:
// this should be the platform_id URL (aud)
String platform_id = request.getParameter("iss");
debug.append("iss: " + platform_id + "<br>");
String login_hint = request.getParameter("login_hint");
debug.append("login_hint: " + login_hint + "<br>");
String target_link_uri = request.getParameter("target_link_uri");
debug.append("target_link_uri: " + target_link_uri + "<br>");
debug.append("parameters: " + request.getParameterMap().keySet().toString() + "<br>");
if (platform_id == null)
throw new Exception("Missing required iss parameter.");
if (login_hint == null)
throw new Exception("Missing required login_hint parameter.");
if (target_link_uri == null)
throw new Exception("Missing required target_link_uri parameter.");
String deployment_id = request.getParameter("lti_deployment_id");
debug.append("deployment_id: " + deployment_id + "<br>");
String client_id = request.getParameter("client_id");
debug.append("client_id: " + client_id + "<br>");
Deployment d = getDeployment(platform_id, deployment_id, client_id);
if (d == null)
throw new Exception("ChemVantage was unable to identify the deployment from your LMS. " + "Please check the registration to ensure the correct deployment_id and client_id. If your " + "platform registered multiple deployments with ChemVantage, it must provide the client_id " + "and/or deployment_id to uniquely identify one of them with each auth token request.<br/>" + "Contact admin@chemvantage.org for assistance.");
String redirect_uri = target_link_uri;
Date now = new Date();
// 5 minutes from now
Date exp = new Date(now.getTime() + 300000L);
String nonce = Nonce.generateNonce();
Algorithm algorithm = Algorithm.HMAC256(Subject.getHMAC256Secret());
debug.append("JWT algorithm loaded OK.<br>");
String iss = "https://" + request.getServerName();
String token = JWT.create().withIssuer(iss).withSubject(login_hint).withAudience(platform_id).withExpiresAt(exp).withIssuedAt(now).withClaim("nonce", nonce).withClaim("deployment_id", d.getDeploymentId()).withClaim("client_id", d.client_id).withClaim("redirect_uri", redirect_uri).sign(algorithm);
debug.append("JWT constructed and signed OK<br>");
String lti_message_hint = request.getParameter("lti_message_hint");
String oidc_auth_url = d.oidc_auth_url + "?response_type=id_token" + "&response_mode=form_post" + "&scope=openid" + "&prompt=none" + "&login_hint=" + login_hint + "&redirect_uri=" + redirect_uri + (lti_message_hint == null ? "" : "<i_message_hint=" + lti_message_hint) + "&client_id=" + d.client_id + "&state=" + token + "&nonce=" + nonce;
debug.append("Sending token: " + oidc_auth_url + "<p>");
response.sendRedirect(oidc_auth_url);
// d.claims = oidc_auth_url;
// ofy().save().entity(d);
} catch (Exception e) {
response.getWriter().println("<h3>Failed Auth Token</h3>" + e.toString() + " " + e.getMessage() + "<br>" + debug.toString());
}
}
use of com.auth0.json.mgmt.Token in project chemvantage by chuckwight.
the class LTILaunch method basicLtiLaunchRequest.
void basicLtiLaunchRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
// check for required LTI launch parameters:
try {
String lti_message_type = request.getParameter("lti_message_type");
if (lti_message_type == null || !"basic-lti-launch-request".contentEquals(lti_message_type)) {
doError(request, response, "Invalid lti_message_type parameter.", null, null);
return;
}
String lti_version = request.getParameter("lti_version");
if (lti_version == null) {
doError(request, response, "Missing lti_version parameter.", null, null);
return;
} else if (!lti_version.equals("LTI-1p0")) {
doError(request, response, "Invalid lti_version parameter.", null, null);
return;
}
String oauth_consumer_key = request.getParameter("oauth_consumer_key");
if (oauth_consumer_key == null) {
doError(request, response, "Missing oauth_consumer_key.", null, null);
return;
}
String resource_link_id = request.getParameter("resource_link_id");
if (resource_link_id == null) {
doError(request, response, "Missing resource_link_id.", null, null);
return;
}
Date now = new Date();
BLTIConsumer tc;
try {
tc = ofy().load().type(BLTIConsumer.class).id(oauth_consumer_key).safe();
if ("suspended".equals(tc.status)) {
response.getWriter().println(Subject.header("ChemVantage Account Management") + suspendedAccount(tc) + Subject.footer);
return;
} else if (tc.expires != null && tc.expires.before(now)) {
response.getWriter().println(Subject.header("ChemVantage Account Management") + expiredAccount(tc, request.getServerName()) + Subject.footer);
return;
}
if (tc.secret == null)
throw new Exception("Shared secret was not found in the ChemVantage database.");
// 24 hrs ago
Date yesterday = new Date(now.getTime() - 86400000L);
if (tc.lastLogin == null || tc.lastLogin.before(yesterday)) {
tc.lastLogin = now;
tc.launchParameters = request.getParameterMap();
try {
// this section synchronizes expiration dates from a single domain
String domain = new URL(tc.launchParameters.get("lis_outcome_service_url")[0]).getHost();
// domain may be null for instructors
if (domain != null)
tc.domain = domain;
if (tc.domain != null) {
// tc.domain may be null if grades are never returned to the LMS
List<BLTIConsumer> companions = ofy().load().type(BLTIConsumer.class).filter("domain", tc.domain).list();
companions.remove(tc);
for (BLTIConsumer tcc : companions) {
// assign the shortest expiration time found for this domain
if (tcc.expires != null && (tc.expires == null || tcc.expires.before(tc.expires)))
tc.expires = tcc.expires;
}
}
} catch (Exception e) {
}
// update the lastLogin value and possibly the domain and expires fields
ofy().save().entity(tc);
}
} catch (Exception e) {
String use = request.getServerName().contains("dev-vantage") ? "dev" : "prod";
throw new Exception("Invalid oauth_consumer_key. " + "Please verify that the oauth_consumer_key is entered into your LMS exactly as you are registered with ChemVantage. " + "If your account has been inactive for more than " + ("dev".equals(use) ? "30 days" : "six months") + ", it may have been " + "deleted in accordance with our <a href=https://www.chemvantage.org/About#privacy target=_blank>privacy policy</a>.<br/>" + "Please use the <a href=https://www.chemvantage.org/lti/registration target=_blank>ChemVantage Registration Page</a> " + "to reregister your LMS.");
}
OAuthMessage oam = OAuthServlet.getMessage(request, null);
OAuthValidator oav = new SimpleOAuthValidator();
OAuthConsumer cons = new OAuthConsumer("about:blank#OAuth+CallBack+NotUsed", oauth_consumer_key, tc.secret, null);
OAuthAccessor acc = new OAuthAccessor(cons);
OAuthSignatureMethod.getBaseString(oam);
if (!Nonce.isUnique(request.getParameter("oauth_nonce"), request.getParameter("oauth_timestamp")))
throw new Exception("Invalid nonce or timestamp.");
try {
oav.validateMessage(oam, acc);
} catch (Exception e) {
throw new Exception("OAuth validation failed, most likely due to an invalid shared_secret value in your LMS. Check carefully to eliminate leading or trailing blank spaces.");
}
// BLTI Launch message was validated successfully at this point
// debug.append("Basic LTI launch message validated...");
// Detect whether this is an anonymous LTI launch request per LTIv1p1p2. This is a security patch that
// prevents a cross-site request forgery threat applicable to versions of LTI released prior to v1.3.
// The launch procedure is for the TC to issue an anonymous BLTI launch request with no user information.
// The TP wraps the TC-defined platform_state into an encrypted JSON Web Token (JWT) and redircects the browser
// to the TC-specified relaunch_url with the original platform_state and the new tool_state parameters, where
// tool_state is the encrypted JWT. The TC then relaunches to the TP with the user information and the
// two state parameters, which must be verified by the TP to proceed with the launch. This security patch makes
// ChemVantage compliant with LTIv1p1p2. If the parameters are not included, the TP may proceed with a
// normal v1p0 BLTI launch; however this is subject to the following deprecation schedule:
// LTIv1p0 last certification 12/31/2019 and last market availability 12/31/2020
// LTIv1p1p2 last certification 06/30/2021 and last market availability 06/30/2022
String relaunch_url = request.getParameter("relaunch_url");
String platform_state = request.getParameter("platform_state");
String tool_state = request.getParameter("tool_state");
Algorithm algorithm = Algorithm.HMAC256(Subject.getHMAC256Secret());
if (tool_state != null && platform_state != null) {
// This is a LTIv1.1.2 relaunch response. Validate the tool_state value
try {
JWT.require(algorithm).withIssuer("https://www.chemvantage.org").withClaim("platform_state", platform_state).build().verify(tool_state);
if (tc.lti_version == null || !tc.lti_version.equals("LTI-1p1p2")) {
tc.lti_version = "LTI-1p1p2";
// should have to do this only once
ofy().save().entity(tc);
}
} catch (Exception e) {
throw new Exception("Tool state could not be validated.");
}
} else if (relaunch_url != null && platform_state != null) {
// Anonymous LRTIv1p1p2 launch request. Execute relaunch sequence:
try {
// 10 minutes from now
Date expires = new Date(new Date().getTime() + 600000);
tool_state = JWT.create().withIssuer("https://www.chemvantage.org").withClaim("platform_state", platform_state).withExpiresAt(expires).sign(algorithm);
response.sendRedirect(relaunch_url + "?platform_state=" + platform_state + "&tool_state=" + tool_state);
lti_version = "LTI-1p1p2_proposed";
} catch (Exception e) {
throw new Exception("Tool state JWT could not be created.");
}
// wait for relaunch from platform
return;
}
// End of LTIv1p1p2 section. Continue with normal LTI launch sequence
// Gather some information about the user
String userId = request.getParameter("user_id");
userId = oauth_consumer_key + ":" + (userId == null ? "" : userId);
// Process user information, provision a new user account if necessary, and store the userId in the user's session
User user = new User(userId);
// check if user has Instructor or Administrator role
String roles = request.getParameter("roles");
if (roles != null) {
roles = roles.toLowerCase();
user.setIsInstructor(roles.contains("instructor"));
user.setIsAdministrator(roles.contains("administrator"));
user.setIsTeachingAssistant(roles.contains("teachingassistant"));
}
// user information OK;
// debug.append("userId=" + userId + " and role=" + (user.isInstructor()?"Instructor":"Learner") + "...");
// Gather information that may be needed to return a score to the LMS:
String lis_result_sourcedid = request.getParameter("lis_result_sourcedid");
// debug.append("lis_result_sourcedid=" + lis_result_sourcedid + "...");
String lisOutcomeServiceUrl = request.getParameter("lis_outcome_service_url");
// debug.append("lis_outcome_service_url=" + lisOutcomeServiceUrl + "...");
// Use the resourceLinkId to find the assignment or create a new one:
Assignment myAssignment = null;
boolean saveAssignment = false;
try {
// load the requested Assignment entity if it exists
myAssignment = ofy().load().type(Assignment.class).filter("domain", oauth_consumer_key).filter("resourceLinkId", resource_link_id).first().safe();
if (lisOutcomeServiceUrl != null && !lisOutcomeServiceUrl.equals(myAssignment.lis_outcome_service_url)) {
myAssignment.lis_outcome_service_url = lisOutcomeServiceUrl;
saveAssignment = true;
}
if (saveAssignment)
ofy().save().entity(myAssignment);
} catch (Exception e) {
// or create a new one with the available information (but no assignmentType or topicIds)
myAssignment = new Assignment(oauth_consumer_key, resource_link_id, lisOutcomeServiceUrl, true);
// we'll need the new id value immediately
ofy().save().entity(myAssignment).now();
}
user.setAssignment(myAssignment.id, lis_result_sourcedid);
if (myAssignment.isValid()) {
// used for hashing userIds by Task queue
Queue queue = QueueFactory.getDefaultQueue();
queue.add(withUrl("/HashUserIds").param("sig", user.getTokenSignature()));
response.sendRedirect("/" + myAssignment.assignmentType + "?sig=" + user.getTokenSignature());
} else
response.getWriter().println(Subject.header("Select A ChemVantage Assignment") + pickResourceForm(user, myAssignment, -1) + Subject.footer);
return;
} catch (Exception e) {
doError(request, response, "LTI Launch failed. " + e.getMessage(), null, e);
}
}
Aggregations