use of com.auth0.flickr2.domain.User in project drug-formulary-ri by HL7-DaVinci.
the class AuthUtils method authCodeIsValid.
/**
* Verify the authorization code provided in the POST request's claim to /token
* path
*
* @param code - the authorization code provided in the request
* @param baseUrl - this server base URL
* @param redirectURI - the requestor/client redirect URI provided in the POST
* request
* @param clientId - the client ID retrieved from the request's Authorization
* Header
* @return patientId if the authorization code is valid, otherwise null
*/
public static String authCodeIsValid(String code, String baseUrl, String redirectURI, String clientId) {
String patientId = null;
try {
Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(baseUrl).withAudience(baseUrl).withClaim(REDIRECT_URI_KEY, redirectURI).withClaim(CLIENT_ID_KEY, clientId).build();
DecodedJWT jwt = verifier.verify(code);
String username = jwt.getClaim("username").asString();
User user = User.getUser(username);
patientId = user != null ? user.getPatientId() : null;
} catch (SignatureVerificationException | InvalidClaimException e) {
logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Signature invalid or claim value invalid", e);
} catch (AlgorithmMismatchException e) {
logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Algorithm mismatch", e);
} catch (TokenExpiredException e) {
logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Token expired", e);
} catch (JWTVerificationException e) {
logger.log(Level.SEVERE, "TokenEndpoint::Authorization code is invalid: Please obtain a new code", e);
}
return patientId;
}
use of com.auth0.flickr2.domain.User 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.flickr2.domain.User in project auth0-java-mvc-common by auth0.
the class IdTokenVerifier method verify.
/**
* Verifies a provided ID Token follows the OIDC specification.
* See https://openid.net/specs/openid-connect-core-1_0-final.html#IDTokenValidation
*
* @param token the ID Token to verify.
* @param verifyOptions the verification options, like audience, issuer, algorithm.
* @throws TokenValidationException If the ID Token is null, its signing algorithm not supported, its signature invalid or one of its claim invalid.
*/
void verify(String token, Options verifyOptions) throws TokenValidationException {
Validate.notNull(verifyOptions);
if (isEmpty(token)) {
throw new TokenValidationException("ID token is required but missing");
}
DecodedJWT decoded = verifyOptions.verifier.verifySignature(token);
if (isEmpty(decoded.getIssuer())) {
throw new TokenValidationException("Issuer (iss) claim must be a string present in the ID token");
}
if (!decoded.getIssuer().equals(verifyOptions.issuer)) {
throw new TokenValidationException(String.format("Issuer (iss) claim mismatch in the ID token, expected \"%s\", found \"%s\"", verifyOptions.issuer, decoded.getIssuer()));
}
if (isEmpty(decoded.getSubject())) {
throw new TokenValidationException("Subject (sub) claim must be a string present in the ID token");
}
final List<String> audience = decoded.getAudience();
if (audience == null) {
throw new TokenValidationException("Audience (aud) claim must be a string or array of strings present in the ID token");
}
if (!audience.contains(verifyOptions.audience)) {
throw new TokenValidationException(String.format("Audience (aud) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.audience, decoded.getAudience()));
}
// validate org if set
if (verifyOptions.organization != null) {
String orgIdClaim = decoded.getClaim("org_id").asString();
if (isEmpty(orgIdClaim)) {
throw new TokenValidationException("Organization Id (org_id) claim must be a string present in the ID token");
}
if (!verifyOptions.organization.equals(orgIdClaim)) {
throw new TokenValidationException(String.format("Organization (org_id) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.organization, orgIdClaim));
}
}
final Calendar cal = Calendar.getInstance();
final Date now = verifyOptions.clock != null ? verifyOptions.clock : cal.getTime();
final int clockSkew = verifyOptions.clockSkew != null ? verifyOptions.clockSkew : DEFAULT_CLOCK_SKEW;
if (decoded.getExpiresAt() == null) {
throw new TokenValidationException("Expiration Time (exp) claim must be a number present in the ID token");
}
cal.setTime(decoded.getExpiresAt());
cal.add(Calendar.SECOND, clockSkew);
Date expDate = cal.getTime();
if (now.after(expDate)) {
throw new TokenValidationException(String.format("Expiration Time (exp) claim error in the ID token; current time (%d) is after expiration time (%d)", now.getTime() / 1000, expDate.getTime() / 1000));
}
if (decoded.getIssuedAt() == null) {
throw new TokenValidationException("Issued At (iat) claim must be a number present in the ID token");
}
cal.setTime(decoded.getIssuedAt());
cal.add(Calendar.SECOND, -1 * clockSkew);
if (verifyOptions.nonce != null) {
String nonceClaim = decoded.getClaim(NONCE_CLAIM).asString();
if (isEmpty(nonceClaim)) {
throw new TokenValidationException("Nonce (nonce) claim must be a string present in the ID token");
}
if (!verifyOptions.nonce.equals(nonceClaim)) {
throw new TokenValidationException(String.format("Nonce (nonce) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.nonce, nonceClaim));
}
}
if (audience.size() > 1) {
String azpClaim = decoded.getClaim(AZP_CLAIM).asString();
if (isEmpty(azpClaim)) {
throw new TokenValidationException("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
}
if (!verifyOptions.audience.equals(azpClaim)) {
throw new TokenValidationException(String.format("Authorized Party (azp) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.audience, azpClaim));
}
}
if (verifyOptions.maxAge != null) {
Date authTime = decoded.getClaim(AUTH_TIME_CLAIM).asDate();
if (authTime == null) {
throw new TokenValidationException("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");
}
cal.setTime(authTime);
cal.add(Calendar.SECOND, verifyOptions.maxAge);
cal.add(Calendar.SECOND, clockSkew);
Date authTimeDate = cal.getTime();
if (now.after(authTimeDate)) {
throw new TokenValidationException(String.format("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (%d) is after last auth at (%d)", now.getTime() / 1000, authTimeDate.getTime() / 1000));
}
}
}
use of com.auth0.flickr2.domain.User in project Blockchain_LSImmo3.0_Backend by medsaad2000.
the class JWTAuthorizationFilter method doFilterInternal.
// pour chaque requete envoyée par user cette methode va executée en premier
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, authorization");
response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, authorization");
response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,");
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
} else if (request.getRequestURI().equals("/login")) {
filterChain.doFilter(request, response);
return;
} else // ------ PUT, GET, POST ... requests ------
{
String jwtToken = request.getHeader(SecurityParams.JWT_HEADER_NAME);
if (jwtToken == null || !jwtToken.startsWith(SecurityParams.HEADER_PREFIX)) {
filterChain.doFilter(request, response);
return;
}
// ----- JWT decode ------- ----
// ----------- sign JWT ----------
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SecurityParams.SECRET)).build();
// ---- remove prefix---------
String jwt = jwtToken.substring(SecurityParams.HEADER_PREFIX.length());
DecodedJWT decodeJWT = verifier.verify(jwt);
// ----- get username --------
String username = decodeJWT.getSubject();
// ------ get roles -------------
List<String> roles = decodeJWT.getClaims().get("roles").asList(String.class);
// ------ convert roles into grantedAuthorities -------
Collection<GrantedAuthority> authorities = new ArrayList<>();
roles.forEach(rn -> {
authorities.add(new SimpleGrantedAuthority(rn));
});
// ---------- user authentication ----------
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(user);
filterChain.doFilter(request, response);
}
}
use of com.auth0.flickr2.domain.User in project Gestion_Employee_SpringBoot_Angular by ibrahimesseddyq.
the class AuthFilter method successfulAuthentication.
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
User user = (User) authentication.getPrincipal();
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
String accessToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 6 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
String refreshToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 8 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
// response.setHeader("access_token",accessToken);
// response.setHeader("refresh_token",refreshToken);
Map<String, String> tokens = new HashMap<>();
tokens.put("access_token", accessToken);
tokens.put("refresh_token", refreshToken);
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
Aggregations