org.apache.cxf.configuration.security.AuthorizationPolicy Java Examples

The following examples show how to use org.apache.cxf.configuration.security.AuthorizationPolicy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UndertowHTTPDestinationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void verifyRequestHeaders() throws Exception {
    Map<String, List<String>> requestHeaders =
        CastUtils.cast((Map<?, ?>)inMessage.get(Message.PROTOCOL_HEADERS));
    assertNotNull("expected request headers",
                  requestHeaders);
    List<String> values = requestHeaders.get("content-type");
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 2, values.size());
    assertTrue("expected value", values.contains("text/xml"));
    assertTrue("expected value", values.contains("charset=utf8"));
    values = requestHeaders.get(AUTH_HEADER);
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 1, values.size());
    assertTrue("expected value", values.contains(BASIC_AUTH));

    AuthorizationPolicy authpolicy =
        inMessage.get(AuthorizationPolicy.class);
    assertNotNull("Expected some auth tokens", policy);
    assertEquals("expected user",
                 USER,
                 authpolicy.getUserName());
    assertEquals("expected passwd",
                 PASSWD,
                 authpolicy.getPassword());
}
 
Example #2
Source File: AuthPolicyValidatingInterceptorTest.java    From steady with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAuthorizationPolicy() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);
    
    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);
    
    in.handleMessage(message);
    
    assertTrue(validator.isValidated());
}
 
Example #3
Source File: WSDLGetAuthenticatorInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        String method = (String)message.get(Message.HTTP_REQUEST_METHOD);
        String query = (String)message.get(Message.QUERY_STRING);
        if (!"GET".equals(method) || StringUtils.isEmpty(query)) {
            return;
        }
        Endpoint endpoint = message.getExchange().getEndpoint();
        synchronized (endpoint) {
            if (!StringUtils.isEmpty(contextName)) {
                AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
                if (policy == null) {
                    handle401response(message, endpoint);
                    return;
                }
                Subject subject = (Subject)authenticate(policy.getUserName(), policy.getPassword());
                if (subject == null) {
                    handle401response(message, endpoint);
                    return;
                }

            }

        }
    }
 
Example #4
Source File: AbstractSpnegoAuthSupplier.java    From cxf with Apache License 2.0 6 votes vote down vote up
public String getAuthorization(AuthorizationPolicy authPolicy,
                               URI currentURI,
                               Message message) {
    if (!HttpAuthHeader.AUTH_TYPE_NEGOTIATE.equals(authPolicy.getAuthorizationType())) {
        return null;
    }
    try {
        String spn = getCompleteServicePrincipalName(currentURI);

        boolean useKerberosOid = MessageUtils.getContextualBoolean(message, PROPERTY_USE_KERBEROS_OID);
        Oid oid = new Oid(useKerberosOid ? KERBEROS_OID : SPNEGO_OID);

        byte[] token = getToken(authPolicy, spn, oid, message);
        return HttpAuthHeader.AUTH_TYPE_NEGOTIATE + " " + Base64Utility.encode(token);
    } catch (LoginException | GSSException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #5
Source File: AuthPolicyValidatingInterceptorTest.java    From steady with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAuthorizationPolicy() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);
    
    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);
    
    in.handleMessage(message);
    
    assertTrue(validator.isValidated());
}
 
Example #6
Source File: HttpConduitConfigurationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void verifyConduit(HTTPConduit conduit) {
    AuthorizationPolicy authp = conduit.getAuthorization();
    assertNotNull(authp);
    assertEquals("Betty", authp.getUserName());
    assertEquals("password", authp.getPassword());
    TLSClientParameters tlscps = conduit.getTlsClientParameters();
    assertNotNull(tlscps);
    assertTrue(tlscps.isDisableCNCheck());
    assertEquals(3600000, tlscps.getSslCacheTimeout());

    KeyManager[] kms = tlscps.getKeyManagers();
    assertTrue(kms != null && kms.length == 1);
    assertTrue(kms[0] instanceof X509KeyManager);

    TrustManager[] tms = tlscps.getTrustManagers();
    assertTrue(tms != null && tms.length == 1);
    assertTrue(tms[0] instanceof X509TrustManager);

    FiltersType csfs = tlscps.getCipherSuitesFilter();
    assertNotNull(csfs);
    assertEquals(1, csfs.getInclude().size());
    assertEquals(1, csfs.getExclude().size());
    HTTPClientPolicy clientPolicy = conduit.getClient();
    assertEquals(10240, clientPolicy.getChunkLength());
}
 
Example #7
Source File: AuthPolicyValidatingInterceptorTest.java    From steady with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAuthorizationPolicy() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);
    
    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);
    
    in.handleMessage(message);
    
    assertTrue(validator.isValidated());
}
 
Example #8
Source File: AuthPolicyValidatingInterceptorTest.java    From steady with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAuthorizationPolicy() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);
    
    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);
    
    in.handleMessage(message);
    
    assertTrue(validator.isValidated());
}
 
Example #9
Source File: BearerAuthSupplier.java    From cxf with Apache License 2.0 6 votes vote down vote up
public String getAuthorization(AuthorizationPolicy authPolicy,
                               URI currentURI,
                               Message message,
                               String fullHeader) {
    if (getClientAccessToken().getTokenKey() == null) {
        return null;
    }


    if (fullHeader == null) {
        // regular authorization
        if (refreshEarly) {
            refreshAccessTokenIfExpired(authPolicy);
        }
        return createAuthorizationHeader();
    }
    // the last call resulted in 401, trying to refresh the token(s)
    if (refreshAccessToken(authPolicy)) {
        return createAuthorizationHeader();
    }
    return null;
}
 
Example #10
Source File: XACMLAuthenticationInterceptor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * isUserPermitted requests received at the ml endpoint, using HTTP basic-auth headers as the authentication
 * mechanism. This method returns a null value which indicates that the request to be processed.
 */
public boolean handleRequest(Message message, ClassResourceInfo resourceInfo) {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Authenticating request: " + message.getId()));
    }
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    if (policy == null) {
        logger.error("Authentication failed: Basic authentication header is missing");
        return false;
    }
    Object certObject = null;
    String username = StringUtils.trim(policy.getUserName());
    if (StringUtils.isEmpty(username)) {
        logger.error("Username cannot be null/empty.");
        return false;
    }
    return isUserPermitted(username, (String) message.get(Message.REQUEST_URI),
            (String) message.get(Message.HTTP_REQUEST_METHOD), null);
}
 
Example #11
Source File: CodeAuthSupplier.java    From cxf with Apache License 2.0 6 votes vote down vote up
public String getAuthorization(AuthorizationPolicy authPolicy,
                               URI currentURI,
                               Message message,
                               String fullHeader) {
    if (code != null) {
        synchronized (tokenSupplier) {
            if (tokenSupplier.getClientAccessToken().getTokenKey() == null) {
                WebClient wc = tokenSupplier.createAccessTokenServiceClient();
                ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                tokenSupplier.getConsumer(),
                                                new AuthorizationCodeGrant(code));
                code = null;
                tokenSupplier.setClientAccessToken(at);
            }
        }
    }
    return tokenSupplier.getAuthorization(authPolicy, currentURI, message, fullHeader);
}
 
Example #12
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example #13
Source File: NettyHttpDestinationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void verifyRequestHeaders() throws Exception {
    Map<String, List<String>> requestHeaders =
        CastUtils.cast((Map<?, ?>)inMessage.get(Message.PROTOCOL_HEADERS));
    assertNotNull("expected request headers",
                  requestHeaders);
    List<String> values = requestHeaders.get("content-type");
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 2, values.size());
    assertTrue("expected value", values.contains("text/xml"));
    assertTrue("expected value", values.contains("charset=utf8"));
    values = requestHeaders.get(AUTH_HEADER);
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 1, values.size());
    assertTrue("expected value", values.contains(BASIC_AUTH));

    AuthorizationPolicy authpolicy =
        inMessage.get(AuthorizationPolicy.class);
    assertNotNull("Expected some auth tokens", policy);
    assertEquals("expected user",
                 USER,
                 authpolicy.getUserName());
    assertEquals("expected passwd",
                 PASSWD,
                 authpolicy.getPassword());
}
 
Example #14
Source File: WSS4JBasicAuthFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getUriInfo().getPath().contains(WellKnownService.WELL_KNOWN_PATH)) {
        return;
    }

    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example #15
Source File: DefaultLogEventMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getPrincipal(Message message) {
    String principal = getJAASPrincipal();
    if (principal != null) {
        return principal;
    }
    SecurityContext sc = message.get(SecurityContext.class);
    if (sc != null && sc.getUserPrincipal() != null) {
        return sc.getUserPrincipal().getName();
    }

    AuthorizationPolicy authPolicy = message.get(AuthorizationPolicy.class);
    if (authPolicy != null) {
        return authPolicy.getUserName();
    }
    return null;
}
 
Example #16
Source File: AuthPolicyValidatingInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoUsername() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);

    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);

    try {
        in.handleMessage(message);
        fail("Failure expected with no username");
    } catch (SecurityException ex) {
        // expected
    }
}
 
Example #17
Source File: AuthPolicyValidatingInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidUsernamePassword() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);

    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd2");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);

    in.handleMessage(message);

    assertFalse(validator.isValidated());
}
 
Example #18
Source File: AuthPolicyValidatingInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateAuthorizationPolicy() throws Exception {
    AuthPolicyValidatingInterceptor in = new AuthPolicyValidatingInterceptor();
    TestSTSTokenValidator validator = new TestSTSTokenValidator();
    in.setValidator(validator);

    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName("bob");
    policy.setPassword("pswd");
    Message message = new MessageImpl();
    message.put(AuthorizationPolicy.class, policy);

    in.handleMessage(message);

    assertTrue(validator.isValidated());
}
 
Example #19
Source File: JettyHTTPDestinationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void verifyRequestHeaders() throws Exception {
    Map<String, List<String>> requestHeaders =
        CastUtils.cast((Map<?, ?>)inMessage.get(Message.PROTOCOL_HEADERS));
    assertNotNull("expected request headers",
                  requestHeaders);
    List<String> values = requestHeaders.get("content-type");
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 2, values.size());
    assertTrue("expected value", values.contains("text/xml"));
    assertTrue("expected value", values.contains("charset=utf8"));
    values = requestHeaders.get(AUTH_HEADER);
    assertNotNull("expected field", values);
    assertEquals("unexpected values", 1, values.size());
    assertTrue("expected value", values.contains(BASIC_AUTH));

    AuthorizationPolicy authpolicy =
        inMessage.get(AuthorizationPolicy.class);
    assertNotNull("Expected some auth tokens", policy);
    assertEquals("expected user",
                 USER,
                 authpolicy.getUserName());
    assertEquals("expected passwd",
                 PASSWD,
                 authpolicy.getPassword());
}
 
Example #20
Source File: HTTPSConduitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * If we don't have the realm set, then we loop
 * through the realms.
 */
public String getAuthorization(
        AuthorizationPolicy authPolicy,
        URI     currentURI,
        Message message,
        String fullHeader
) {
    String reqestedRealm = new HttpAuthHeader(fullHeader).getRealm();
    if (realm != null && realm.equals(reqestedRealm)) {
        return createUserPass(user, pass);
    }
    if ("Andromeda".equals(reqestedRealm)) {
        // This will get us another 401 to Zorantius
        return createUserPass("Edward", "password");
    }
    if ("Zorantius".equals(reqestedRealm)) {
        // George will get us another 401 to Cronus
        return createUserPass("George", "password");
    }
    if ("Cronus".equals(reqestedRealm)) {
        // Mary will get us another 401 to Andromeda
        return createUserPass("Mary", "password");
    }
    return null;
}
 
Example #21
Source File: JAXRSJaasSecurityTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testJaasFilterAuthenticationFailure() throws Exception {
    String endpointAddress =
        "http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
    WebClient wc = WebClient.create(endpointAddress);
    AuthorizationPolicy pol = new AuthorizationPolicy();
    pol.setUserName("foo");
    pol.setPassword("bar1");
    WebClient.getConfig(wc).getHttpConduit().setAuthorization(pol);

    wc.accept("application/xml");

    //wc.header(HttpHeaders.AUTHORIZATION,
    //          "Basic " + base64Encode("foo" + ":" + "bar1"));
    Response r = wc.get();
    assertEquals(401, r.getStatus());
    Object wwwAuthHeader = r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
    assertNotNull(wwwAuthHeader);
    assertEquals("Basic", wwwAuthHeader.toString());
}
 
Example #22
Source File: WrappedMessageContext.java    From cxf with Apache License 2.0 5 votes vote down vote up
public final Object remove(Object key) {
    key = mapKey((String)key);
    scopes.remove(key);
    if (BindingProvider.PASSWORD_PROPERTY.equals(key)
        || BindingProvider.USERNAME_PROPERTY.equals(key)) {
        message.remove(AuthorizationPolicy.class.getName());
    }
    return message.remove(key);
}
 
Example #23
Source File: CustomAuthSupplier.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getAuthorization(AuthorizationPolicy  authPolicy,
                               URI currentURI,
                               Message message,
                               String fullHeader) {
    if (authPolicy.getAuthorizationType() != null && authPolicy.getAuthorization() != null) {
        return authPolicy.getAuthorizationType() + " " + authPolicy.getAuthorization();
    }
    return null;
}
 
Example #24
Source File: BasicAuthFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected UsernameToken convertPolicyToToken(AuthorizationPolicy policy)
    throws Exception {

    Document doc = DOMUtils.createDocument();
    UsernameToken token = new UsernameToken(false, doc,
                                            WSConstants.PASSWORD_TEXT);
    token.setName(policy.getUserName());
    token.setPassword(policy.getPassword());
    return token;
}
 
Example #25
Source File: ClientFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void applyProperties(Endpoint ep) {
    //Apply the AuthorizationPolicy to the endpointInfo
    Map<String, Object> props = this.getProperties();
    if (props != null && props.get(AuthorizationPolicy.class.getName()) != null) {
        AuthorizationPolicy ap = (AuthorizationPolicy)props.get(AuthorizationPolicy.class.getName());
        ep.getEndpointInfo().addExtensor(ap);
    }
}
 
Example #26
Source File: AuthPolicyValidatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            String password = null;
            if (policy != null) {
                name = policy.getUserName();
                password = policy.getPassword();
            }
            org.apache.cxf.common.i18n.Message errorMsg = 
                new org.apache.cxf.common.i18n.Message("NO_USER_PASSWORD", 
                                                       BUNDLE, 
                                                       name, password);
            LOG.warning(errorMsg.toString());
            throw new SecurityException(errorMsg.toString());
        }
        
        try {
            UsernameToken token = convertPolicyToToken(policy);
            Credential credential = new Credential();
            credential.setUsernametoken(token);
            validator.validateWithSTS(credential, message);
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
 
Example #27
Source File: BookServerThrottled.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public ThrottleResponse getThrottleResponse(String phase, Message m) {
    AuthorizationPolicy ap = m.get(AuthorizationPolicy.class);
    if (ap != null && "alice".equals(ap.getUserName())) {
        return null;
    }
    return new ThrottleResponse(503, 2000);
}
 
Example #28
Source File: JAXRSJaasSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testJaasFilterWebClientAuthorizationPolicy() throws Exception {
    String endpointAddress =
        "http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
    WebClient wc = WebClient.create(endpointAddress);
    AuthorizationPolicy pol = new AuthorizationPolicy();
    pol.setUserName("bob");
    pol.setPassword("bobspassword");
    WebClient.getConfig(wc).getHttpConduit().setAuthorization(pol);
    wc.accept("application/xml");
    Book book = wc.get(Book.class);
    assertEquals(123L, book.getId());
}
 
Example #29
Source File: BasicAuthenticationInterceptorTest.java    From dropwizard-jaxws with Apache License 2.0 5 votes vote down vote up
private Message createMessageWithUsernameAndPassword(String username, String password) {
    Message message = createEmptyMessage();

    AuthorizationPolicy policy = new AuthorizationPolicy();
    policy.setUserName(username);
    policy.setPassword(password);
    message.put(AuthorizationPolicy.class, policy);
    return message;
}
 
Example #30
Source File: HTTPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static void configureConduitFromEndpointInfo(HTTPConduit conduit,
        EndpointInfo endpointInfo) {
    if (conduit.getClient() == null) {
        conduit.setClient(endpointInfo.getTraversedExtensor(
                new HTTPClientPolicy(), HTTPClientPolicy.class));
    }
    if (conduit.getAuthorization() == null) {
        conduit.setAuthorization(endpointInfo.getTraversedExtensor(
                new AuthorizationPolicy(), AuthorizationPolicy.class));

    }
    if (conduit.getProxyAuthorization() == null) {
        conduit.setProxyAuthorization(endpointInfo.getTraversedExtensor(
                new ProxyAuthorizationPolicy(),
                ProxyAuthorizationPolicy.class));

    }
    if (conduit.getTlsClientParameters() == null) {
        conduit.setTlsClientParameters(endpointInfo.getTraversedExtensor(
                null, TLSClientParameters.class));
    }
    if (conduit.getTrustDecider() == null) {
        conduit.setTrustDecider(endpointInfo.getTraversedExtensor(null,
                MessageTrustDecider.class));
    }
    if (conduit.getAuthSupplier() == null) {
        conduit.setAuthSupplier(endpointInfo.getTraversedExtensor(null,
                HttpAuthSupplier.class));
    }
}