use of org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD in project cxf by apache.
the class JAXRSOAuth2Test method testBasicAuthClientCred.
@Test
public void testBasicAuthClientCred() throws Exception {
String address = "https://localhost:" + PORT + "/oauth2/token";
WebClient wc = createWebClient(address);
ClientCredentialsGrant grant = new ClientCredentialsGrant();
// Pass client_id & client_secret as form properties
// (instead WebClient can be initialized with username & password)
grant.setClientId("bob");
grant.setClientSecret("bobPassword");
try {
OAuthClientUtils.getAccessToken(wc, grant);
fail("Form based authentication is not supported");
} catch (OAuthServiceException ex) {
assertEquals(OAuthConstants.UNAUTHORIZED_CLIENT, ex.getError().getError());
}
ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer("bob", "bobPassword"), new ClientCredentialsGrant(), true);
assertNotNull(at.getTokenKey());
}
use of org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD in project meecrowave by apache.
the class OAuth2Configurer method preCompute.
// TODO: still some missing configuration for jwt etc to add/wire from OAuth2Options
@PostConstruct
private void preCompute() {
configuration = builder.getExtension(OAuth2Options.class);
AbstractOAuthDataProvider provider;
switch(configuration.getProvider().toLowerCase(ENGLISH)) {
case "jpa":
{
if (!configuration.isAuthorizationCodeSupport()) {
// else use code impl
final JPAOAuthDataProvider jpaProvider = new JPAOAuthDataProvider();
jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
provider = jpaProvider;
break;
}
}
case "jpa-code":
{
final JPACodeDataProvider jpaProvider = new JPACodeDataProvider();
jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
provider = jpaProvider;
break;
}
case "jcache":
if (!configuration.isAuthorizationCodeSupport()) {
// else use code impl
jCacheConfigurer.doSetup(configuration);
try {
provider = new JCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus, configuration.isJcacheStoreJwtKeyOnly());
} catch (final Exception e) {
throw new IllegalStateException(e);
}
break;
}
case "jcache-code":
jCacheConfigurer.doSetup(configuration);
try {
provider = new JCacheCodeDataProvider(configuration, bus);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
break;
case // not sure it makes sense since we have jcache but this one is cheap to support
"ehcache":
provider = new DefaultEHCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus);
break;
case "encrypted":
if (!configuration.isAuthorizationCodeSupport()) {
// else use code impl
provider = new DefaultEncryptingOAuthDataProvider(new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo()));
break;
}
case "encrypted-code":
provider = new DefaultEncryptingCodeDataProvider(new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo()));
break;
default:
throw new IllegalArgumentException("Unsupported oauth2 provider: " + configuration.getProvider());
}
final RefreshTokenGrantHandler refreshTokenGrantHandler = new RefreshTokenGrantHandler();
refreshTokenGrantHandler.setDataProvider(provider);
refreshTokenGrantHandler.setUseAllClientScopes(configuration.isUseAllClientScopes());
refreshTokenGrantHandler.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
final ResourceOwnerLoginHandler loginHandler = configuration.isJaas() ? new JAASResourceOwnerLoginHandler() : (client, name, password) -> {
try {
request.login(name, password);
try {
final Principal pcp = request.getUserPrincipal();
final List<String> roles = GenericPrincipal.class.isInstance(pcp) ? new ArrayList<>(asList(GenericPrincipal.class.cast(pcp).getRoles())) : Collections.<String>emptyList();
final UserSubject userSubject = new UserSubject(name, roles);
userSubject.setAuthenticationMethod(PASSWORD);
return userSubject;
} finally {
request.logout();
}
} catch (final ServletException e) {
throw new AuthenticationException(e.getMessage());
}
};
final List<AccessTokenGrantHandler> handlers = new ArrayList<>();
handlers.add(refreshTokenGrantHandler);
handlers.add(new ClientCredentialsGrantHandler());
handlers.add(new ResourceOwnerGrantHandler() {
{
setLoginHandler(loginHandler);
}
});
handlers.add(new AuthorizationCodeGrantHandler());
handlers.add(new JwtBearerGrantHandler());
provider.setUseJwtFormatForAccessTokens(configuration.isUseJwtFormatForAccessTokens());
provider.setAccessTokenLifetime(configuration.getAccessTokenLifetime());
provider.setRefreshTokenLifetime(configuration.getRefreshTokenLifetime());
provider.setRecycleRefreshTokens(configuration.isRecycleRefreshTokens());
provider.setSupportPreauthorizedTokens(configuration.isSupportPreauthorizedTokens());
ofNullable(configuration.getRequiredScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setRequiredScopes);
ofNullable(configuration.getDefaultScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setDefaultScopes);
ofNullable(configuration.getInvisibleToClientScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setInvisibleToClientScopes);
ofNullable(configuration.getJwtAccessTokenClaimMap()).map(s -> new Properties() {
{
try {
load(new StringReader(s));
} catch (IOException e) {
throw new IllegalArgumentException("Bad claim map configuration, use properties syntax");
}
}
}).ifPresent(m -> provider.setJwtAccessTokenClaimMap(new HashMap<>(Map.class.cast(m))));
final OAuthDataProvider dataProvider;
if (configuration.isRefreshToken()) {
dataProvider = new RefreshTokenEnabledProvider(provider);
if (provider.getInvisibleToClientScopes() == null) {
provider.setInvisibleToClientScopes(new ArrayList<>());
}
provider.getInvisibleToClientScopes().add(OAuthConstants.REFRESH_TOKEN_SCOPE);
} else {
dataProvider = provider;
}
handlers.stream().filter(AbstractGrantHandler.class::isInstance).forEach(h -> {
final AbstractGrantHandler handler = AbstractGrantHandler.class.cast(h);
handler.setDataProvider(dataProvider);
handler.setCanSupportPublicClients(configuration.isCanSupportPublicClients());
handler.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
});
abstractTokenServiceConsumer = s -> {
// this is used @RequestScoped so ensure it is not slow for no reason
s.setCanSupportPublicClients(configuration.isCanSupportPublicClients());
s.setBlockUnsecureRequests(configuration.isBlockUnsecureRequests());
s.setWriteCustomErrors(configuration.isWriteCustomErrors());
s.setWriteOptionalParameters(configuration.isWriteOptionalParameters());
s.setDataProvider(dataProvider);
};
tokenServiceConsumer = s -> {
// this is used @RequestScoped so ensure it is not slow for no reason
abstractTokenServiceConsumer.accept(s);
s.setGrantHandlers(handlers);
};
final List<String> noConsentScopes = ofNullable(configuration.getScopesRequiringNoConsent()).map(s -> asList(s.split(","))).orElse(null);
// we prefix them oauth2.cxf. but otherwise it is the plain cxf config
final Map<String, String> contextualProperties = ofNullable(builder.getProperties()).map(Properties::stringPropertyNames).orElse(emptySet()).stream().filter(s -> s.startsWith("oauth2.cxf.rs.security.")).collect(toMap(s -> s.substring("oauth2.cxf.".length()), s -> builder.getProperties().getProperty(s)));
final JoseSessionTokenProvider sessionAuthenticityTokenProvider = new JoseSessionTokenProvider() {
private int maxDefaultSessionInterval;
private boolean jweRequired;
private JweEncryptionProvider jweEncryptor;
// workaround a NPE of 3.2.0 - https://issues.apache.org/jira/browse/CXF-7504
@Override
public String createSessionToken(final MessageContext mc, final MultivaluedMap<String, String> params, final UserSubject subject, final OAuthRedirectionState secData) {
String stateString = convertStateToString(secData);
final JwsSignatureProvider jws = getInitializedSigProvider();
final JweEncryptionProvider jwe = jweEncryptor == null ? JweUtils.loadEncryptionProvider(new JweHeaders(), jweRequired) : jweEncryptor;
if (jws == null && jwe == null) {
throw new OAuthServiceException("Session token can not be created");
}
if (jws != null) {
stateString = JwsUtils.sign(jws, stateString, null);
}
if (jwe != null) {
stateString = jwe.encrypt(StringUtils.toBytesUTF8(stateString), null);
}
return OAuthUtils.setSessionToken(mc, stateString, maxDefaultSessionInterval);
}
public void setJweEncryptor(final JweEncryptionProvider jweEncryptor) {
super.setJweEncryptor(jweEncryptor);
this.jweEncryptor = jweEncryptor;
}
@Override
public void setJweRequired(final boolean jweRequired) {
super.setJweRequired(jweRequired);
this.jweRequired = jweRequired;
}
@Override
public void setMaxDefaultSessionInterval(final int maxDefaultSessionInterval) {
super.setMaxDefaultSessionInterval(maxDefaultSessionInterval);
this.maxDefaultSessionInterval = maxDefaultSessionInterval;
}
};
sessionAuthenticityTokenProvider.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
// TODO: other configs
redirectionBasedGrantServiceConsumer = s -> {
s.setDataProvider(dataProvider);
s.setBlockUnsecureRequests(configuration.isBlockUnsecureRequests());
s.setWriteOptionalParameters(configuration.isWriteOptionalParameters());
s.setUseAllClientScopes(configuration.isUseAllClientScopes());
s.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
s.setUseRegisteredRedirectUriIfPossible(configuration.isUseRegisteredRedirectUriIfPossible());
s.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
s.setMatchRedirectUriWithApplicationUri(configuration.isMatchRedirectUriWithApplicationUri());
s.setScopesRequiringNoConsent(noConsentScopes);
s.setSessionAuthenticityTokenProvider(sessionAuthenticityTokenProvider);
// TODO: make it even more contextual, client based?
final Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
contextualProperties.forEach(currentMessage::put);
};
}
use of org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD in project meecrowave by apache.
the class OAuth2Test method getRefreshTokenNoClient.
@Test
public void getRefreshTokenNoClient() {
final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider());
try {
// password
final ClientAccessToken primary = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort()).path("oauth2/token").request(APPLICATION_JSON_TYPE).post(entity(new Form().param("grant_type", "password").param("username", "test").param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
// refresh
final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort()).path("oauth2/token").request(APPLICATION_JSON_TYPE).post(entity(new Form().param("grant_type", "refresh_token").param("refresh_token", primary.getRefreshToken()), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
assertNotNull(token);
assertEquals("Bearer", token.getTokenType());
assertNotNull(token.getTokenKey());
assertEquals(3600, token.getExpiresIn());
assertNotEquals(0, token.getIssuedAt());
assertNotNull(token.getRefreshToken());
} finally {
client.close();
}
}
use of org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD in project cxf by apache.
the class AbstractOAuthDataProvider method createClientCredentialsClient.
protected Client createClientCredentialsClient(String clientId, String password) {
if (authenticateUnregisteredClient(clientId, password)) {
Client c = new Client(clientId, password, true);
c.setAllowedGrantTypes(Collections.singletonList(OAuthConstants.CLIENT_CREDENTIALS_GRANT));
return c;
}
return null;
}
use of org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD in project cxf by apache.
the class UserInfoTest method testSignedUserInfo.
@org.junit.Test
public void testSignedUserInfo() throws Exception {
URL busFile = UserInfoTest.class.getResource("client.xml");
String address = "https://localhost:" + PORT + "/services/oidc";
WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
// Get Authorization Code
String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
assertNotNull(code);
// Now get the access token
client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
assertNotNull(accessToken.getTokenKey());
assertTrue(accessToken.getApprovedScope().contains("openid"));
String idToken = accessToken.getParameters().get("id_token");
assertNotNull(idToken);
validateIdToken(idToken, null);
// Now invoke on the UserInfo service with the access token
String userInfoAddress = "https://localhost:" + PORT + "/services/signed/userinfo";
WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(), busFile.toString());
userInfoClient.accept("application/jwt");
userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());
Response serviceResponse = userInfoClient.get();
assertEquals(serviceResponse.getStatus(), 200);
String token = serviceResponse.readEntity(String.class);
assertNotNull(token);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
JwtToken jwt = jwtConsumer.getJwtToken();
assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()), "password".toCharArray());
Certificate cert = keystore.getCertificate("alice");
Assert.assertNotNull(cert);
Assert.assertTrue(jwtConsumer.verifySignatureWith((X509Certificate) cert, SignatureAlgorithm.RS256));
}
Aggregations