use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.
the class CasRestAuthenticator method requestTicketGrantingTicket.
private String requestTicketGrantingTicket(final String username, final String password, final WebContext context) {
HttpURLConnection connection = null;
try {
connection = HttpUtils.openPostConnection(new URL(this.configuration.computeFinalRestUrl(context)));
final var payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username) + "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password);
final var out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
out.write(payload);
out.close();
final var locationHeader = connection.getHeaderField("location");
final var responseCode = connection.getResponseCode();
if (locationHeader != null && responseCode == HttpConstants.CREATED) {
return locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
}
logger.debug("Ticket granting ticket request failed: " + locationHeader + " " + responseCode + HttpUtils.buildHttpErrorMessage(connection));
return null;
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.
the class FacebookProfileDefinition method computeAppSecretProof.
/**
* The code in this method is based on this blog post:
* https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure
* and this answer: https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation
*
* @param url the URL to which we're adding the proof
* @param token the application token we pass back and forth
* @param configuration the current configuration
* @return URL with the appsecret_proof parameter added
*/
public String computeAppSecretProof(final String url, final OAuth2AccessToken token, final FacebookConfiguration configuration) {
try {
var sha256_HMAC = Mac.getInstance("HmacSHA256");
var secret_key = new SecretKeySpec(configuration.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
var proof = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(token.getAccessToken().getBytes(StandardCharsets.UTF_8)));
final var computedUrl = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
return computedUrl;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new TechnicalException("Unable to compute appsecret_proof", e);
}
}
use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.
the class AzureAdClient method getAccessTokenFromRefreshToken.
public String getAccessTokenFromRefreshToken(final AzureAdProfile azureAdProfile) {
final var azureConfig = (AzureAdOidcConfiguration) getConfiguration();
CommonHelper.assertTrue(CommonHelper.isNotBlank(azureConfig.getTenant()), "Tenant must be defined. Update your config.");
HttpURLConnection connection = null;
try {
final Map<String, String> headers = new HashMap<>();
headers.put(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.APPLICATION_FORM_ENCODED_HEADER_VALUE);
headers.put(HttpConstants.ACCEPT_HEADER, HttpConstants.APPLICATION_JSON);
connection = HttpUtils.openPostConnection(new URL("https://login.microsoftonline.com/" + azureConfig.getTenant() + "/oauth2/token"), headers);
final var out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
out.write(azureConfig.makeOauth2TokenRequest(azureAdProfile.getRefreshToken().getValue()));
out.close();
final var responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new TechnicalException("request for access token failed: " + HttpUtils.buildHttpErrorMessage(connection));
}
var body = HttpUtils.readBody(connection);
final Map<String, Object> res = objectMapper.readValue(body, typeRef);
return (String) res.get("access_token");
} catch (final IOException e) {
throw new TechnicalException(e);
} finally {
HttpUtils.closeConnection(connection);
}
}
use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.
the class OidcProfileCreator method create.
@Override
@SuppressWarnings("unchecked")
public Optional<UserProfile> create(final Credentials cred, final WebContext context, final SessionStore sessionStore) {
init();
final var credentials = (OidcCredentials) cred;
final var accessToken = credentials.getAccessToken();
// Create profile
final var profile = (OidcProfile) getProfileDefinition().newProfile();
profile.setAccessToken(accessToken);
final var idToken = credentials.getIdToken();
profile.setIdTokenString(idToken.getParsedString());
// Check if there is a refresh token
final var refreshToken = credentials.getRefreshToken();
if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
profile.setRefreshToken(refreshToken);
logger.debug("Refresh Token successful retrieved");
}
try {
final Nonce nonce;
if (configuration.isUseNonce()) {
nonce = new Nonce((String) sessionStore.get(context, client.getNonceSessionAttributeName()).orElse(null));
} else {
nonce = null;
}
// Check ID Token
final var claimsSet = configuration.findTokenValidator().validate(idToken, nonce);
assertNotNull("claimsSet", claimsSet);
profile.setId(ProfileHelper.sanitizeIdentifier(claimsSet.getSubject()));
// User Info request
if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), accessToken);
final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
configuration.configureHttpRequest(userInfoHttpRequest);
final var httpResponse = userInfoHttpRequest.send();
logger.debug("User info response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final var userInfoResponse = UserInfoResponse.parse(httpResponse);
if (userInfoResponse instanceof UserInfoErrorResponse) {
logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
} else {
final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
final JWTClaimsSet userInfoClaimsSet;
if (userInfoSuccessResponse.getUserInfo() != null) {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
} else {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
}
getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
}
}
// add attributes of the ID token if they don't already exist
for (final var entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
final var key = entry.getKey();
final var value = entry.getValue();
// it's not the subject and this attribute does not already exist, add it
if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
}
}
// session expiration with token behavior
profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
// keep the session ID if provided
final var sid = (String) claimsSet.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
if (isNotBlank(sid)) {
configuration.findLogoutHandler().recordSession(context, sessionStore, sid);
}
return Optional.of(profile);
} catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
throw new TechnicalException(e);
}
}
use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.
the class SAML2IdentityProviderMetadataResolverTest method resolveMetadataOverUrlWithHostnameVerifierFromConfig.
@Test
public void resolveMetadataOverUrlWithHostnameVerifierFromConfig() throws Exception {
var configuration = new SAML2Configuration();
configuration.setIdentityProviderMetadataResource(new UrlResource("https://self-signed.badssl.com"));
configuration.setHostnameVerifier((s, sslSession) -> true);
configuration.setSslSocketFactory(disabledSslContext().getSocketFactory());
metadataResolver = new SAML2IdentityProviderMetadataResolver(configuration);
try {
metadataResolver.init();
} catch (final TechnicalException e) {
assertEquals(XMLParserException.class, e.getCause().getClass());
}
}
Aggregations