Search in sources :

Example 46 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class HTTPConduitTest method testAuthPolicyFromEndpointInfo.

@Test
public void testAuthPolicyFromEndpointInfo() throws Exception {
    Bus bus = new ExtensionManagerBus();
    EndpointInfo ei = new EndpointInfo();
    AuthorizationPolicy ap = new AuthorizationPolicy();
    ap.setPassword("password");
    ap.setUserName("testUser");
    ei.addExtensor(ap);
    ei.setAddress("http://nowhere.com/bar/foo");
    HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null);
    conduit.finalizeConfig();
    Message message = getNewMessage();
    // Test call
    conduit.prepare(message);
    Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    assertNotNull("Authorization Header should exist", headers.get("Authorization"));
    assertEquals("Unexpected Authorization Token", DefaultBasicAuthSupplier.getBasicAuthHeader("testUser", "password"), headers.get("Authorization").get(0));
}
Also used : Bus(org.apache.cxf.Bus) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) EndpointInfo(org.apache.cxf.service.model.EndpointInfo) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Message(org.apache.cxf.message.Message) ArrayList(java.util.ArrayList) List(java.util.List) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) Test(org.junit.Test)

Example 47 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class DigestAuthSupplierTest method testEncode.

@Test
public void testEncode() throws Exception {
    String origNonce = "MTI0ODg3OTc5NzE2OTplZGUyYTg0Yzk2NTFkY2YyNjc1Y2JjZjU2MTUzZmQyYw==";
    String fullHeader = "Digest realm=\"MyCompany realm.\", qop=\"auth\"," + "nonce=\"" + origNonce + "\"";
    /**
     * Initialize DigestAuthSupplier that always uses the same cnonce so we always
     * get the same response
     */
    DigestAuthSupplier authSupplier = new DigestAuthSupplier() {

        @Override
        public String createCnonce() {
            return "27db039b76362f3d55da10652baee38c";
        }
    };
    AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy();
    authorizationPolicy.setUserName("testUser");
    authorizationPolicy.setPassword("testPassword");
    URI uri = new URI("http://myserver");
    Message message = new MessageImpl();
    String authToken = authSupplier.getAuthorization(authorizationPolicy, uri, message, fullHeader);
    HttpAuthHeader authHeader = new HttpAuthHeader(authToken);
    assertTrue(authHeader.authTypeIsDigest());
    Map<String, String> params = authHeader.getParams();
    Map<String, String> expectedParams = new HashMap<>();
    expectedParams.put("response", "28e616b6868f60aaf9b19bb5b172f076");
    expectedParams.put("cnonce", "27db039b76362f3d55da10652baee38c");
    expectedParams.put("username", "testUser");
    expectedParams.put("nc", "00000001");
    expectedParams.put("nonce", origNonce);
    expectedParams.put("realm", "MyCompany realm.");
    expectedParams.put("qop", "auth");
    expectedParams.put("uri", "");
    expectedParams.put("algorithm", "MD5");
    assertEquals(expectedParams, params);
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Message(org.apache.cxf.message.Message) HashMap(java.util.HashMap) URI(java.net.URI) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 48 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class DefaultLogEventMapper method getPrincipal.

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;
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) SecurityContext(org.apache.cxf.security.SecurityContext)

Example 49 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class AbstractHTTPDestination method setupMessage.

protected void setupMessage(final Message inMessage, final ServletConfig config, final ServletContext context, final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    setupContinuation(inMessage, req, resp);
    final Exchange exchange = inMessage.getExchange();
    DelegatingInputStream in = new DelegatingInputStream(req.getInputStream()) {

        public void cacheInput() {
            if (!cached && (exchange.isOneWay() || isWSAddressingReplyToSpecified(exchange))) {
                // For one-ways and WS-Addressing invocations with ReplyTo address,
                // we need to cache the values of the HttpServletRequest
                // so they can be queried later for things like paths and schemes
                // and such like that.
                // Please note, exchange used to always get the "current" message
                exchange.getInMessage().put(HTTP_REQUEST, new HttpServletRequestSnapshot(req));
            }
            super.cacheInput();
        }

        private boolean isWSAddressingReplyToSpecified(Exchange ex) {
            AddressingProperties map = ContextUtils.retrieveMAPs(ex.getInMessage(), false, false, false);
            return map != null && !ContextUtils.isGenericAddress(map.getReplyTo());
        }
    };
    inMessage.setContent(DelegatingInputStream.class, in);
    inMessage.setContent(InputStream.class, in);
    inMessage.put(HTTP_REQUEST, req);
    inMessage.put(HTTP_RESPONSE, resp);
    inMessage.put(HTTP_CONTEXT, context);
    inMessage.put(HTTP_CONFIG, config);
    inMessage.put(HTTP_CONTEXT_MATCH_STRATEGY, contextMatchStrategy);
    inMessage.put(Message.HTTP_REQUEST_METHOD, req.getMethod());
    String requestURI = req.getRequestURI();
    inMessage.put(Message.REQUEST_URI, requestURI);
    String requestURL = req.getRequestURL().toString();
    inMessage.put(Message.REQUEST_URL, requestURL);
    String contextPath = req.getContextPath();
    if (contextPath == null) {
        contextPath = "";
    }
    String servletPath = req.getServletPath();
    if (servletPath == null) {
        servletPath = "";
    }
    String contextServletPath = contextPath + servletPath;
    String pathInfo = req.getPathInfo();
    if (pathInfo != null) {
        inMessage.put(Message.PATH_INFO, contextServletPath + pathInfo);
    } else {
        inMessage.put(Message.PATH_INFO, requestURI);
    }
    if (!StringUtils.isEmpty(requestURI)) {
        int index = requestURL.indexOf(requestURI);
        if (index > 0) {
            // Can be useful for referencing resources with URIs not covered by CXFServlet.
            // For example, if we a have web application name 'app' and CXFServlet listening
            // on "/services/*" then having HTTP_BASE_PATH pointing to say
            // http://localhost:8080/app will make it easy to refer to non CXF resources
            String schemaInfo = requestURL.substring(0, index);
            String basePathWithContextOnly = schemaInfo + contextPath;
            inMessage.put(HTTP_BASE_PATH, basePathWithContextOnly);
        }
    } else if (!StringUtils.isEmpty(servletPath) && requestURL.endsWith(servletPath)) {
        int index = requestURL.lastIndexOf(servletPath);
        if (index > 0) {
            inMessage.put(HTTP_BASE_PATH, requestURL.substring(0, index));
        }
    }
    String contentType = req.getContentType();
    inMessage.put(Message.CONTENT_TYPE, contentType);
    setEncoding(inMessage, req, contentType);
    inMessage.put(Message.QUERY_STRING, req.getQueryString());
    inMessage.put(Message.ACCEPT_CONTENT_TYPE, req.getHeader("Accept"));
    String basePath = getBasePath(contextServletPath);
    if (!StringUtils.isEmpty(basePath)) {
        inMessage.put(Message.BASE_PATH, basePath);
    }
    inMessage.put(Message.FIXED_PARAMETER_ORDER, isFixedParameterOrder());
    inMessage.put(Message.ASYNC_POST_RESPONSE_DISPATCH, Boolean.TRUE);
    SecurityContext httpSecurityContext = new SecurityContext() {

        public Principal getUserPrincipal() {
            return req.getUserPrincipal();
        }

        public boolean isUserInRole(String role) {
            return req.isUserInRole(role);
        }
    };
    inMessage.put(SecurityContext.class, httpSecurityContext);
    Headers headers = new Headers(inMessage);
    headers.copyFromRequest(req);
    String credentials = headers.getAuthorization();
    AuthorizationPolicy authPolicy = getAuthorizationPolicyFromMessage(credentials, httpSecurityContext);
    inMessage.put(AuthorizationPolicy.class, authPolicy);
    propogateSecureSession(req, inMessage);
    inMessage.put(CertConstraints.class.getName(), certConstraints);
    inMessage.put(Message.IN_INTERCEPTORS, Arrays.asList(new Interceptor[] { CertConstraintsInterceptor.INSTANCE }));
}
Also used : Exchange(org.apache.cxf.message.Exchange) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) DelegatingInputStream(org.apache.cxf.io.DelegatingInputStream) SecurityContext(org.apache.cxf.security.SecurityContext) CertConstraints(org.apache.cxf.transport.https.CertConstraints) AddressingProperties(org.apache.cxf.ws.addressing.AddressingProperties) CertConstraintsInterceptor(org.apache.cxf.transport.https.CertConstraintsInterceptor) Interceptor(org.apache.cxf.interceptor.Interceptor)

Example 50 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class AbstractHTTPDestination method getAuthorizationPolicyFromMessage.

private AuthorizationPolicy getAuthorizationPolicyFromMessage(String credentials, SecurityContext sc) {
    if (credentials == null || StringUtils.isEmpty(credentials.trim())) {
        return null;
    }
    final String[] creds = credentials.split(" ");
    String authType = creds[0];
    if ("Basic".equals(authType) && creds.length == 2) {
        String authEncoded = creds[1];
        try {
            byte[] authBytes = Base64Utility.decode(authEncoded);
            if (authBytes == null) {
                throw new Base64Exception(new Throwable("Invalid Base64 data."));
            }
            String authDecoded = decodeBasicAuthWithIso8859 ? new String(authBytes, StandardCharsets.ISO_8859_1) : new String(authBytes);
            int idx = authDecoded.indexOf(':');
            final String username;
            String password = null;
            if (idx == -1) {
                username = authDecoded;
            } else {
                username = authDecoded.substring(0, idx);
                if (idx < (authDecoded.length() - 1)) {
                    password = authDecoded.substring(idx + 1);
                }
            }
            AuthorizationPolicy policy = sc.getUserPrincipal() == null ? new AuthorizationPolicy() : new PrincipalAuthorizationPolicy(sc);
            policy.setUserName(username);
            policy.setPassword(password);
            policy.setAuthorizationType(authType);
            return policy;
        } catch (Base64Exception ex) {
        // Invalid authentication => treat as not authenticated or use the Principal
        }
    }
    if (sc.getUserPrincipal() != null) {
        AuthorizationPolicy policy = new PrincipalAuthorizationPolicy(sc);
        policy.setAuthorization(credentials);
        policy.setAuthorizationType(authType);
        return policy;
    }
    return null;
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Base64Exception(org.apache.cxf.common.util.Base64Exception)

Aggregations

AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)86 Message (org.apache.cxf.message.Message)25 Test (org.junit.Test)22 HTTPConduit (org.apache.cxf.transport.http.HTTPConduit)16 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)11 Client (org.apache.cxf.endpoint.Client)11 List (java.util.List)9 HTTPClientPolicy (org.apache.cxf.transports.http.configuration.HTTPClientPolicy)9 URL (java.net.URL)7 HashMap (java.util.HashMap)7 ProxyAuthorizationPolicy (org.apache.cxf.configuration.security.ProxyAuthorizationPolicy)7 Map (java.util.Map)6 SecurityContext (org.apache.cxf.security.SecurityContext)6 Bus (org.apache.cxf.Bus)5 TLSClientParameters (org.apache.cxf.configuration.jsse.TLSClientParameters)5 WebClient (org.apache.cxf.jaxrs.client.WebClient)5 MessageImpl (org.apache.cxf.message.MessageImpl)5 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)5 Principal (java.security.Principal)4