use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.
the class OidcRealm method doGetAuthenticationInfo.
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// token is guaranteed to be of type OidcAuthenticationToken by the supports() method
OidcAuthenticationToken oidcAuthenticationToken = (OidcAuthenticationToken) authenticationToken;
OidcCredentials credentials = (OidcCredentials) oidcAuthenticationToken.getCredentials();
OidcConfiguration oidcConfiguration = oidcHandlerConfiguration.getOidcConfiguration();
OIDCProviderMetadata oidcProviderMetadata = oidcConfiguration.findProviderMetadata();
WebContext webContext = (WebContext) oidcAuthenticationToken.getContext();
OidcClient<OidcConfiguration> oidcClient = oidcHandlerConfiguration.getOidcClient(webContext.getFullRequestURL());
int connectTimeout = oidcHandlerConfiguration.getConnectTimeout();
int readTimeout = oidcHandlerConfiguration.getReadTimeout();
try {
OidcCredentialsResolver oidcCredentialsResolver = new OidcCredentialsResolver(oidcConfiguration, oidcClient, oidcProviderMetadata, connectTimeout, readTimeout);
oidcCredentialsResolver.resolveIdToken(credentials, webContext);
} catch (TechnicalException e) {
throw new AuthenticationException(e);
}
// problem getting id token, invalidate credentials
if (credentials.getIdToken() == null) {
webContext.getSessionStore().destroySession(webContext);
String msg = String.format("Could not fetch id token with Oidc credentials (%s). " + "This may be due to the credentials expiring. " + "Invalidating session in order to acquire valid credentials.", credentials);
LOGGER.warn(msg);
throw new AuthenticationException(msg);
}
OidcProfileCreator oidcProfileCreator = new CustomOidcProfileCreator(oidcConfiguration, oidcClient);
Optional<UserProfile> userProfile = oidcProfileCreator.create(credentials, webContext);
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
simpleAuthenticationInfo.setCredentials(credentials);
if (userProfile.isPresent()) {
OidcProfile oidcProfile = (OidcProfile) userProfile.get();
simpleAuthenticationInfo.setPrincipals(createPrincipalCollectionFromCredentials(oidcProfile));
} else {
simpleAuthenticationInfo.setPrincipals(new SimplePrincipalCollection());
}
return simpleAuthenticationInfo;
}
use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.
the class OidcRealm method supports.
/**
* Determine if the supplied token is supported by this realm.
*/
@Override
public boolean supports(AuthenticationToken token) {
if (!(token instanceof OidcAuthenticationToken)) {
LOGGER.debug("The supplied authentication token is not an instance of SessionToken or OidcAuthenticationToken. Sending back not supported.");
return false;
}
OidcAuthenticationToken oidcToken = (OidcAuthenticationToken) token;
OidcCredentials credentials = (OidcCredentials) oidcToken.getCredentials();
if (credentials == null || (credentials.getCode() == null && credentials.getAccessToken() == null && credentials.getIdToken() == null)) {
LOGGER.debug("The supplied authentication token has null/empty credentials. Sending back no supported.");
return false;
}
WebContext webContext = (WebContext) oidcToken.getContext();
if (webContext == null) {
LOGGER.debug("The supplied authentication token has null web context. Sending back not supported.");
return false;
}
LOGGER.debug("Token {} is supported by {}.", token.getClass(), OidcRealm.class.getName());
return true;
}
use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.
the class CustomOAuthCredentialsExtractor method getOauthCredentialsAsOidcCredentials.
public OidcCredentials getOauthCredentialsAsOidcCredentials(final WebContext context) {
OidcCredentials credentials = new OidcCredentials();
try {
final String codeParam = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE).orElse(null);
if (codeParam != null) {
credentials.setCode(new AuthorizationCode(URLDecoder.decode(codeParam, StandardCharsets.UTF_8.name())));
} else {
LOGGER.debug("No OAuth2 code found on request.");
}
final String accessTokenParam = context.getRequestParameter("access_token").orElse(null);
final String accessTokenHeader = getAccessTokenFromHeader(context);
final String accessToken = accessTokenParam != null ? accessTokenParam : accessTokenHeader;
if (isNotBlank(accessToken)) {
credentials.setAccessToken(new BearerAccessToken(URLDecoder.decode(accessToken, StandardCharsets.UTF_8.name())));
} else {
LOGGER.debug("No OAuth2 access token found on request.");
}
} catch (UnsupportedEncodingException e) {
LOGGER.debug("Error decoding the authorization code/access token from url parameters.", e);
}
return credentials;
}
use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.
the class OAuthHandler method getNormalizedToken.
@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, SecurityFilterChain chain, boolean resolve) throws AuthenticationFailureException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (httpRequest.getMethod().equals("HEAD")) {
return processHeadRequest(httpResponse);
}
JEESessionStore sessionStore = new JEESessionStore();
JEEContext jeeContext = new JEEContext(httpRequest, httpResponse, sessionStore);
// time to try and pull credentials off of the request
LOGGER.debug("Doing OAuth authentication and authorization for path {}.", httpRequest.getContextPath());
OidcCredentials credentials;
StringBuffer requestUrlBuffer = httpRequest.getRequestURL();
requestUrlBuffer.append(httpRequest.getQueryString() == null ? "" : "?" + httpRequest.getQueryString());
String ipAddress = httpRequest.getRemoteAddr();
boolean isMachine = userAgentIsNotBrowser(httpRequest);
// machine to machine, check for Client Credentials Flow credentials
if (isMachine) {
try {
credentials = getCredentialsFromRequest(jeeContext);
} catch (IllegalArgumentException e) {
LOGGER.error("Problem with the OAuth Handler's OAuthHandlerConfiguration. " + "Check the OAuth Handler Configuration in the admin console.", e);
return noActionResult;
} catch (OAuthCredentialsException e) {
LOGGER.error("Problem extracting credentials from machine to machine request. " + "See OAuth2's \"Client Credential Flow\" for more information.", e);
return noActionResult;
}
} else {
LOGGER.info("The OAuth Handler does not handle user agent requests. Continuing to other handlers.");
return noActionResult;
}
// if the request has credentials, process it
if (credentials.getCode() != null || credentials.getAccessToken() != null || credentials.getIdToken() != null) {
LOGGER.info("Oidc credentials found/retrieved. Saving to session and continuing filter chain.");
OidcAuthenticationToken token = new OidcAuthenticationToken(credentials, jeeContext, ipAddress);
HandlerResult handlerResult = new HandlerResultImpl(Status.COMPLETED, token);
handlerResult.setSource(SOURCE);
return handlerResult;
} else {
LOGGER.info("No credentials found on user-agent request. " + "This handler does not support the acquisition of user agent credentials. Continuing to other handlers.");
return noActionResult;
}
}
use of org.pac4j.oidc.credentials.OidcCredentials in project ddf by codice.
the class OidcRealmTest method setup.
@Before
public void setup() throws Exception {
realm = new OidcRealm();
// Generate the RSA key pair
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair keyPair = gen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
invalidAlgorithm = Algorithm.HMAC256("WRONG");
JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
OIDCProviderMetadata oidcProviderMetadata = mock(OIDCProviderMetadata.class);
when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
Resource resource = new Resource(jwk, APPLICATION_JSON);
when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
OidcConfiguration configuration = mock(OidcConfiguration.class);
when(configuration.getClientId()).thenReturn("ddf-client");
when(configuration.getSecret()).thenReturn("secret");
when(configuration.isUseNonce()).thenReturn(true);
when(configuration.getResponseType()).thenReturn("code");
when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
OidcHandlerConfiguration handlerConfiguration = mock(OidcHandlerConfiguration.class);
when(handlerConfiguration.getOidcConfiguration()).thenReturn(configuration);
when(handlerConfiguration.getOidcClient(any())).thenReturn(mock(OidcClient.class));
realm.setOidcHandlerConfiguration(handlerConfiguration);
realm.setUsernameAttributeList(Collections.singletonList("preferred_username"));
JWT jwt = mock(JWT.class);
AccessToken accessToken = new BearerAccessToken(getAccessTokenBuilder().sign(validAlgorithm));
AuthorizationCode authorizationCode = new AuthorizationCode();
WebContext webContext = getWebContext();
oidcCredentials = mock(OidcCredentials.class);
when(oidcCredentials.getIdToken()).thenReturn(jwt);
when(oidcCredentials.getIdToken()).thenReturn(jwt);
when(oidcCredentials.getAccessToken()).thenReturn(accessToken);
when(oidcCredentials.getCode()).thenReturn(authorizationCode);
authenticationToken = mock(OidcAuthenticationToken.class);
when(authenticationToken.getCredentials()).thenReturn(oidcCredentials);
when(authenticationToken.getContext()).thenReturn(webContext);
}
Aggregations