use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.
the class HawkAccessTokenValidatorTest method testValidateAccessToken.
@Test
public void testValidateAccessToken() throws Exception {
HawkAccessToken macAccessToken = new HawkAccessToken(new Client("testClientId", "testClientSecret", true), HmacAlgorithm.HmacSHA256, -1);
HttpServletRequest httpRequest = mockHttpRequest();
UriInfo uriInfo = mockUriInfo();
EasyMock.expect(dataProvider.getAccessToken(macAccessToken.getTokenKey())).andReturn(macAccessToken);
EasyMock.expect(messageContext.getHttpServletRequest()).andReturn(httpRequest);
EasyMock.expect(messageContext.getUriInfo()).andReturn(uriInfo);
EasyMock.replay(dataProvider, messageContext, httpRequest, uriInfo);
String authData = getClientAuthHeader(macAccessToken);
AccessTokenValidation tokenValidation = validator.validateAccessToken(messageContext, OAuthConstants.HAWK_AUTHORIZATION_SCHEME, authData.split(" ")[1], null);
assertNotNull(tokenValidation);
EasyMock.verify(dataProvider, messageContext, httpRequest);
}
use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.
the class AccessTokenIntrospectionClient 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.TOKEN_ID, authSchemeData);
try {
TokenIntrospection response = client.post(props, TokenIntrospection.class);
return convertIntrospectionToValidation(response);
} catch (WebApplicationException ex) {
throw new OAuthServiceException(ex);
}
}
use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.
the class JwtAccessTokenValidator method convertClaimsToValidation.
private AccessTokenValidation convertClaimsToValidation(JwtClaims claims) {
AccessTokenValidation atv = new AccessTokenValidation();
atv.setInitialValidationSuccessful(true);
String clientId = claims.getStringProperty(OAuthConstants.CLIENT_ID);
if (clientId != null) {
atv.setClientId(clientId);
}
if (claims.getIssuedAt() != null) {
atv.setTokenIssuedAt(claims.getIssuedAt());
} else {
Instant now = Instant.now();
atv.setTokenIssuedAt(now.toEpochMilli());
}
if (claims.getExpiryTime() != null) {
atv.setTokenLifetime(claims.getExpiryTime() - atv.getTokenIssuedAt());
}
List<String> audiences = claims.getAudiences();
if (audiences != null && !audiences.isEmpty()) {
atv.setAudiences(claims.getAudiences());
}
if (claims.getIssuer() != null) {
atv.setTokenIssuer(claims.getIssuer());
}
Object scope = claims.getClaim(OAuthConstants.SCOPE);
if (scope != null) {
String[] scopes = scope instanceof String ? scope.toString().split(" ") : CastUtils.cast((List<?>) scope).toArray(new String[] {});
List<OAuthPermission> perms = new LinkedList<OAuthPermission>();
for (String s : scopes) {
if (!StringUtils.isEmpty(s)) {
perms.add(new OAuthPermission(s.trim()));
}
}
atv.setTokenScopes(perms);
}
String usernameClaimName = JwtTokenUtils.getClaimName(USERNAME_PROP, USERNAME_PROP, jwtAccessTokenClaimMap);
String username = claims.getStringProperty(usernameClaimName);
if (username != null) {
UserSubject userSubject = new UserSubject(username);
if (claims.getSubject() != null) {
userSubject.setId(claims.getSubject());
}
atv.setTokenSubject(userSubject);
} else if (claims.getSubject() != null) {
atv.setTokenSubject(new UserSubject(claims.getSubject()));
}
Map<String, String> extraProperties = CastUtils.cast((Map<?, ?>) claims.getClaim("extra_properties"));
if (extraProperties != null) {
atv.getExtraProps().putAll(extraProperties);
}
Map<String, Object> cnfClaim = CastUtils.cast((Map<?, ?>) claims.getClaim(JwtConstants.CLAIM_CONFIRMATION));
if (cnfClaim != null) {
Object certCnf = cnfClaim.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
if (certCnf != null) {
atv.getExtraProps().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf.toString());
}
}
return atv;
}
use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.
the class OAuthRequestFilter method validateRequest.
protected void validateRequest(Message m) {
if (isCorsRequest(m)) {
return;
}
// Get the scheme and its data, Bearer only is supported by default
// WWW-Authenticate with the list of supported schemes will be sent back
// if the scheme is not accepted
String[] authParts = getAuthorizationParts(m);
if (authParts.length < 2) {
throw ExceptionUtils.toForbiddenException(null, null);
}
String authScheme = authParts[0];
String authSchemeData = authParts[1];
// Get the access token
AccessTokenValidation accessTokenV = getAccessTokenValidation(authScheme, authSchemeData, null);
if (!accessTokenV.isInitialValidationSuccessful()) {
AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
}
// Check audiences
String validAudience = validateAudiences(accessTokenV.getAudiences());
// Check if token was issued by the supported issuer
if (issuer != null && !issuer.equals(accessTokenV.getTokenIssuer())) {
AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
}
// Find the scopes which match the current request
List<OAuthPermission> permissions = accessTokenV.getTokenScopes();
List<OAuthPermission> matchingPermissions = new ArrayList<>();
HttpServletRequest req = getMessageContext().getHttpServletRequest();
for (OAuthPermission perm : permissions) {
boolean uriOK = checkRequestURI(req, perm.getUris());
boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
boolean scopeOk = checkScopeProperty(perm.getPermission());
if (uriOK && verbOK && scopeOk) {
matchingPermissions.add(perm);
}
}
if (!permissions.isEmpty() && matchingPermissions.isEmpty() || allPermissionsMatch && (matchingPermissions.size() != permissions.size()) || !requiredScopes.isEmpty() && requiredScopes.size() != matchingPermissions.size()) {
String message = "Client has no valid permissions";
LOG.warning(message);
throw ExceptionUtils.toForbiddenException(null, null);
}
if (accessTokenV.getClientIpAddress() != null) {
String remoteAddress = getMessageContext().getHttpServletRequest().getRemoteAddr();
if (remoteAddress == null || accessTokenV.getClientIpAddress().equals(remoteAddress)) {
String message = "Client IP Address is invalid";
LOG.warning(message);
throw ExceptionUtils.toForbiddenException(null, null);
}
}
if (blockPublicClients && !accessTokenV.isClientConfidential()) {
String message = "Only Confidential Clients are supported";
LOG.warning(message);
throw ExceptionUtils.toForbiddenException(null, null);
}
if (am != null && !am.equals(accessTokenV.getTokenSubject().getAuthenticationMethod())) {
String message = "The token has been authorized by the resource owner " + "using an unsupported authentication method";
LOG.warning(message);
throw ExceptionUtils.toNotAuthorizedException(null, null);
}
// Check Client Certificate Binding if any
String certThumbprint = accessTokenV.getExtraProps().get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
if (certThumbprint != null) {
TLSSessionInfo tlsInfo = getTlsSessionInfo();
X509Certificate cert = tlsInfo == null ? null : OAuthUtils.getRootTLSCertificate(tlsInfo);
if (cert == null || !OAuthUtils.compareCertificateThumbprints(cert, certThumbprint)) {
throw ExceptionUtils.toNotAuthorizedException(null, null);
}
}
// Create the security context and make it available on the message
SecurityContext sc = createSecurityContext(req, accessTokenV);
m.put(SecurityContext.class, sc);
// Also set the OAuthContext
OAuthContext oauthContext = new OAuthContext(accessTokenV.getTokenSubject(), accessTokenV.getClientSubject(), matchingPermissions, accessTokenV.getTokenGrantType());
oauthContext.setClientId(accessTokenV.getClientId());
oauthContext.setClientConfidential(accessTokenV.isClientConfidential());
oauthContext.setTokenKey(accessTokenV.getTokenKey());
oauthContext.setTokenAudience(validAudience);
oauthContext.setTokenIssuer(accessTokenV.getTokenIssuer());
oauthContext.setTokenRequestParts(authParts);
oauthContext.setTokenExtraProperties(accessTokenV.getExtraProps());
m.setContent(OAuthContext.class, oauthContext);
}
use of org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation in project cxf by apache.
the class AbstractHawkAccessTokenValidator method validateAccessToken.
public AccessTokenValidation validateAccessToken(MessageContext mc, String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps) throws OAuthServiceException {
Map<String, String> schemeParams = getSchemeParameters(authSchemeData);
AccessTokenValidation atv = getAccessTokenValidation(mc, authScheme, authSchemeData, extraProps, schemeParams);
if (isRemoteSignatureValidation()) {
return atv;
}
String macKey = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_KEY);
String macAlgo = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_ALGORITHM);
HttpRequestProperties httpProps = null;
if (extraProps != null && extraProps.containsKey(HTTP_VERB) && extraProps.containsKey(HTTP_URI)) {
httpProps = new HttpRequestProperties(URI.create(extraProps.getFirst(HTTP_URI)), extraProps.getFirst(HTTP_VERB));
} else {
httpProps = new HttpRequestProperties(mc.getUriInfo().getRequestUri(), mc.getHttpServletRequest().getMethod());
}
HawkAuthorizationScheme macAuthInfo = new HawkAuthorizationScheme(httpProps, schemeParams);
String normalizedString = macAuthInfo.getNormalizedRequestString();
try {
HmacAlgorithm hmacAlgo = HmacAlgorithm.toHmacAlgorithm(macAlgo);
byte[] serverMacData = HmacUtils.computeHmac(macKey, hmacAlgo.getJavaName(), normalizedString);
String clientMacString = schemeParams.get(OAuthConstants.HAWK_TOKEN_SIGNATURE);
byte[] clientMacData = Base64Utility.decode(clientMacString);
boolean validMac = MessageDigest.isEqual(serverMacData, clientMacData);
if (!validMac) {
AuthorizationUtils.throwAuthorizationFailure(Collections.singleton(OAuthConstants.HAWK_AUTHORIZATION_SCHEME));
}
} catch (Base64Exception e) {
throw new OAuthServiceException(OAuthConstants.SERVER_ERROR, e);
}
validateTimestampNonce(macKey, macAuthInfo.getTimestamp(), macAuthInfo.getNonce());
return atv;
}
Aggregations