use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.
the class JoseClientCodeStateManager method toRedirectState.
@Override
public MultivaluedMap<String, String> toRedirectState(MessageContext mc, MultivaluedMap<String, String> requestState) {
JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider();
JwsSignatureProvider theSigProvider = getInitializedSigProvider(theEncryptionProvider);
if (theEncryptionProvider == null && theSigProvider == null) {
throw new OAuthServiceException("The state can not be protected");
}
MultivaluedMap<String, String> redirectMap = new MetadataMap<String, String>();
if (generateNonce && theSigProvider != null) {
JwsCompactProducer nonceProducer = new JwsCompactProducer(OAuthUtils.generateRandomTokenKey());
String nonceParam = nonceProducer.signWith(theSigProvider);
requestState.putSingle(OAuthConstants.NONCE, nonceParam);
redirectMap.putSingle(OAuthConstants.NONCE, nonceParam);
}
Map<String, Object> stateMap = CastUtils.cast((Map<?, ?>) requestState);
String json = jsonp.toJson(stateMap);
String stateParam = null;
if (theSigProvider != null) {
JwsCompactProducer stateProducer = new JwsCompactProducer(json);
stateParam = stateProducer.signWith(theSigProvider);
}
if (theEncryptionProvider != null) {
stateParam = theEncryptionProvider.encrypt(StringUtils.toBytesUTF8(stateParam), null);
}
if (storeInSession) {
String sessionStateAttribute = OAuthUtils.generateRandomTokenKey();
OAuthUtils.setSessionToken(mc, stateParam, sessionStateAttribute, 0);
stateParam = sessionStateAttribute;
}
redirectMap.putSingle(OAuthConstants.STATE, stateParam);
return redirectMap;
}
use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.
the class OAuthClientUtils method getAccessToken.
/**
* Obtains the access token from OAuth AccessToken Service
* using the initialized web client
* @param accessTokenService the AccessToken client
* @param consumer {@link Consumer} representing the registered client.
* @param grant {@link AccessTokenGrant} grant
* @param extraParams extra parameters
* @param defaultTokenType default expected token type - some early
* well-known OAuth2 services do not return a required token_type parameter
* @param setAuthorizationHeader if set to true then HTTP Basic scheme
* will be used to pass client id and secret, otherwise they will
* be passed in the form payload
* @return {@link ClientAccessToken} access token
* @throws OAuthServiceException
*/
public static ClientAccessToken getAccessToken(WebClient accessTokenService, Consumer consumer, AccessTokenGrant grant, Map<String, String> extraParams, String defaultTokenType, boolean setAuthorizationHeader) throws OAuthServiceException {
if (accessTokenService == null) {
throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
Form form = new Form(grant.toMap());
if (extraParams != null) {
for (Map.Entry<String, String> entry : extraParams.entrySet()) {
form.param(entry.getKey(), entry.getValue());
}
}
if (consumer != null) {
boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
if (setAuthorizationHeader && secretAvailable) {
StringBuilder sb = new StringBuilder();
sb.append("Basic ");
try {
String data = consumer.getClientId() + ":" + consumer.getClientSecret();
sb.append(Base64Utility.encode(data.getBytes(StandardCharsets.UTF_8)));
} catch (Exception ex) {
throw new ProcessingException(ex);
}
accessTokenService.replaceHeader("Authorization", sb.toString());
} else {
form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
if (secretAvailable) {
form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
}
}
} else {
// in this case the AccessToken service is expected to find a mapping between
// the authenticated credentials and the client registration id
}
Response response = accessTokenService.form(form);
Map<String, String> map = null;
try {
map = new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity());
} catch (IOException ex) {
throw new ResponseProcessingException(response, ex);
}
if (200 == response.getStatus()) {
ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
if (token == null) {
throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
return token;
} else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY), map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
throw new OAuthServiceException(error);
}
throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.
the class AccessTokenValidatorClient method validateAccessToken.
public AccessTokenValidation validateAccessToken(MessageContext mc, String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps) throws OAuthServiceException {
WebClient client = WebClient.fromClient(tokenValidatorClient, true);
MultivaluedMap<String, String> props = new MetadataMap<String, String>();
props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_TYPE, authScheme);
props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_DATA, authSchemeData);
if (extraProps != null) {
props.putAll(extraProps);
}
try {
return client.post(props, AccessTokenValidation.class);
} catch (WebApplicationException ex) {
throw new OAuthServiceException(ex);
}
}
use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.
the class AuthorizationCodeGrantHandler method doCreateAccessToken.
private ServerAccessToken doCreateAccessToken(Client client, ServerAuthorizationCodeGrant grant, String requestedGrant, String codeVerifier, List<String> audiences) {
if (grant.isPreauthorizedTokenAvailable()) {
ServerAccessToken token = getPreAuthorizedToken(client, grant.getSubject(), requestedGrant, grant.getRequestedScopes(), getAudiences(client, grant.getAudience()));
if (token != null) {
if (grant.getNonce() != null) {
JAXRSUtils.getCurrentMessage().getExchange().put(OAuthConstants.NONCE, grant.getNonce());
}
return token;
}
// creating a completely new token can be wrong - though this needs to be reviewed
throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
}
if (!client.getAllowedGrantTypes().isEmpty() && !client.getAllowedGrantTypes().contains(requestedGrant)) {
throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
}
// Delegate to the data provider to create the one
AccessTokenRegistration reg = new AccessTokenRegistration();
reg.setGrantCode(grant.getCode());
reg.setClient(client);
reg.setGrantType(requestedGrant);
reg.setSubject(grant.getSubject());
reg.setRequestedScope(grant.getRequestedScopes());
reg.setNonce(grant.getNonce());
if (grant.getApprovedScopes() != null) {
reg.setApprovedScope(grant.getApprovedScopes());
} else {
reg.setApprovedScope(Collections.emptyList());
}
reg.setAudiences(audiences);
reg.setResponseType(grant.getResponseType());
reg.setClientCodeVerifier(codeVerifier);
reg.getExtraProperties().putAll(grant.getExtraProperties());
return getDataProvider().createAccessToken(reg);
}
use of org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException in project cxf by apache.
the class AuthorizationCodeGrantHandler method createAccessToken.
public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params) throws OAuthServiceException {
// Get the grant representation from the provider
String codeValue = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
ServerAuthorizationCodeGrant grant = ((AuthorizationCodeDataProvider) getDataProvider()).removeCodeGrant(codeValue);
if (grant == null) {
return null;
}
// check it has not expired, the client ids are the same
if (OAuthUtils.isExpired(grant.getIssuedAt(), grant.getExpiresIn())) {
throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
}
if (!grant.getClient().getClientId().equals(client.getClientId())) {
throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
}
// redirect URIs must match too
String expectedRedirectUri = grant.getRedirectUri();
String providedRedirectUri = params.getFirst(OAuthConstants.REDIRECT_URI);
if (providedRedirectUri != null) {
if (expectedRedirectUri == null || !providedRedirectUri.equals(expectedRedirectUri)) {
throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
}
} else if (expectedRedirectUri == null && !isCanSupportPublicClients() || expectedRedirectUri != null && (client.getRedirectUris().size() != 1 || !client.getRedirectUris().contains(expectedRedirectUri))) {
throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
}
String clientCodeVerifier = params.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER);
String clientCodeChallenge = grant.getClientCodeChallenge();
if (!compareCodeVerifierWithChallenge(client, clientCodeVerifier, clientCodeChallenge)) {
throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
}
List<String> audiences = getAudiences(client, params, grant.getAudience());
return doCreateAccessToken(client, grant, getSingleGrantType(), clientCodeVerifier, audiences);
}
Aggregations