Search in sources :

Example 6 with LoginSecurityContext

use of org.apache.cxf.security.LoginSecurityContext in project cxf by apache.

the class OAuthUtils method createSubject.

public static UserSubject createSubject(SecurityContext securityContext) {
    List<String> roleNames = Collections.emptyList();
    if (securityContext instanceof LoginSecurityContext) {
        roleNames = ((LoginSecurityContext) securityContext).getUserRoles().stream().map(Principal::getName).collect(toList());
    }
    UserSubject subject = new UserSubject(securityContext.getUserPrincipal().getName(), roleNames);
    Message m = JAXRSUtils.getCurrentMessage();
    if (m != null && m.get(AuthenticationMethod.class) != null) {
        subject.setAuthenticationMethod(m.get(AuthenticationMethod.class));
    }
    return subject;
}
Also used : UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) Message(org.apache.cxf.message.Message) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) AuthenticationMethod(org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Example 7 with LoginSecurityContext

use of org.apache.cxf.security.LoginSecurityContext in project camel by apache.

the class DefaultCxfRsBinding method populateExchangeFromCxfRsRequest.

public void populateExchangeFromCxfRsRequest(org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange, Method method, Object[] paramArray) {
    Message camelMessage = camelExchange.getIn();
    //Copy the CXF message header into the Camel inMessage
    org.apache.cxf.message.Message cxfMessage = cxfExchange.getInMessage();
    CxfHeaderHelper.copyHttpHeadersFromCxfToCamel(headerFilterStrategy, cxfMessage, camelMessage, camelExchange);
    // TODO move to CxfHeaderHelper and use header filter strategy and CXF_TO_CAMEL_HEADERS
    // setup the charset from content-type header
    setCharsetWithContentType(camelExchange);
    //copy the protocol header
    copyProtocolHeader(cxfMessage, camelMessage, camelMessage.getExchange());
    camelMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, method.getReturnType());
    camelMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, method.getGenericReturnType());
    copyOperationResourceInfoStack(cxfMessage, camelMessage);
    camelMessage.setHeader(CxfConstants.OPERATION_NAME, method.getName());
    camelMessage.setHeader(CxfConstants.CAMEL_CXF_MESSAGE, cxfMessage);
    camelMessage.setBody(new MessageContentsList(paramArray));
    // propagate the security subject from CXF security context
    SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
    if (securityContext instanceof LoginSecurityContext && ((LoginSecurityContext) securityContext).getSubject() != null) {
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, ((LoginSecurityContext) securityContext).getSubject());
    } else if (securityContext != null && securityContext.getUserPrincipal() != null) {
        Subject subject = new Subject();
        subject.getPrincipals().add(securityContext.getUserPrincipal());
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
    }
}
Also used : Message(org.apache.camel.Message) MessageContentsList(org.apache.cxf.message.MessageContentsList) SecurityContext(org.apache.cxf.security.SecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) Subject(javax.security.auth.Subject)

Example 8 with LoginSecurityContext

use of org.apache.cxf.security.LoginSecurityContext in project camel by apache.

the class DefaultCxfBinding method populateExchangeFromCxfRequest.

/**
     * This method is called by {@link CxfConsumer}.
     */
public void populateExchangeFromCxfRequest(org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange) {
    Method method = null;
    QName operationName = null;
    ExchangePattern mep = ExchangePattern.InOut;
    // extract binding operation information
    BindingOperationInfo boi = camelExchange.getProperty(BindingOperationInfo.class.getName(), BindingOperationInfo.class);
    if (boi != null) {
        Service service = cxfExchange.get(Service.class);
        if (service != null) {
            MethodDispatcher md = (MethodDispatcher) service.get(MethodDispatcher.class.getName());
            if (md != null) {
                method = md.getMethod(boi);
            }
        }
        if (boi.getOperationInfo().isOneWay()) {
            mep = ExchangePattern.InOnly;
        }
        operationName = boi.getName();
    }
    // set operation name in header
    if (operationName != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        }
    } else if (method != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, method.getName());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: {}={}", CxfConstants.OPERATION_NAME, method.getName());
        }
    }
    // set message exchange pattern
    camelExchange.setPattern(mep);
    LOG.trace("Set exchange MEP: {}", mep);
    // propagate headers
    Message cxfMessage = cxfExchange.getInMessage();
    propagateHeadersFromCxfToCamel(cxfMessage, camelExchange.getIn(), camelExchange);
    // propagate the security subject from CXF security context
    SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
    if (securityContext instanceof LoginSecurityContext && ((LoginSecurityContext) securityContext).getSubject() != null) {
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, ((LoginSecurityContext) securityContext).getSubject());
    } else if (securityContext != null) {
        Principal user = securityContext.getUserPrincipal();
        if (user != null) {
            Subject subject = new Subject();
            subject.getPrincipals().add(user);
            camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
        }
    }
    // Propagating properties from CXF Exchange to Camel Exchange has an  
    // side effect of copying reply side stuff when the producer is retried.
    // So, we do not want to do this.
    //camelExchange.getProperties().putAll(cxfExchange);
    // propagate request context
    Object value = cxfMessage.get(Client.REQUEST_CONTEXT);
    if (value != null && !headerFilterStrategy.applyFilterToExternalHeaders(Client.REQUEST_CONTEXT, value, camelExchange)) {
        camelExchange.getIn().setHeader(Client.REQUEST_CONTEXT, value);
        LOG.trace("Populate context from CXF message {} value={}", Client.REQUEST_CONTEXT, value);
    }
    // setup the charset from content-type header
    setCharsetWithContentType(camelExchange);
    // set body
    String encoding = (String) camelExchange.getProperty(Exchange.CHARSET_NAME);
    Object body = DefaultCxfBinding.getContentFromCxf(cxfMessage, camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class), encoding);
    if (body != null) {
        camelExchange.getIn().setBody(body);
    }
    // propagate attachments if the data format is not POJO        
    if (cxfMessage.getAttachments() != null && !camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class).equals(DataFormat.POJO)) {
        for (Attachment attachment : cxfMessage.getAttachments()) {
            camelExchange.getIn().addAttachmentObject(attachment.getId(), createCamelAttachment(attachment));
        }
    }
}
Also used : BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) Message(org.apache.cxf.message.Message) QName(javax.xml.namespace.QName) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) Service(org.apache.cxf.service.Service) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.cxf.message.Attachment) Method(java.lang.reflect.Method) Subject(javax.security.auth.Subject) ExchangePattern(org.apache.camel.ExchangePattern) SecurityContext(org.apache.cxf.security.SecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) MethodDispatcher(org.apache.cxf.service.invoker.MethodDispatcher) Principal(java.security.Principal)

Example 9 with LoginSecurityContext

use of org.apache.cxf.security.LoginSecurityContext in project cxf by apache.

the class AuthorizationRequestHandler method handle.

public Response handle(MessageContext mc, OAuthDataProvider dataProvider) {
    HttpServletRequest request = mc.getHttpServletRequest();
    try {
        OAuthMessage oAuthMessage = OAuthUtils.getOAuthMessage(mc, request, REQUIRED_PARAMETERS);
        new DefaultOAuthValidator().checkSingleParameter(oAuthMessage);
        RequestToken token = dataProvider.getRequestToken(oAuthMessage.getToken());
        if (token == null) {
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        String decision = oAuthMessage.getParameter(OAuthConstants.AUTHORIZATION_DECISION_KEY);
        OAuthAuthorizationData secData = new OAuthAuthorizationData();
        if (!compareRequestSessionTokens(request, oAuthMessage)) {
            if (decision != null) {
                // this is a user decision request, the session has expired or been possibly hijacked
                LOG.warning("Session authenticity token is missing or invalid");
                throw ExceptionUtils.toBadRequestException(null, null);
            }
            // assume it is an initial authorization request
            addAuthenticityTokenToSession(secData, request);
            return Response.ok(addAdditionalParams(secData, dataProvider, token)).build();
        }
        boolean allow = OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(decision);
        Map<String, String> queryParams = new HashMap<>();
        if (allow) {
            SecurityContext sc = (SecurityContext) mc.get(SecurityContext.class.getName());
            List<String> roleNames = Collections.emptyList();
            if (sc instanceof LoginSecurityContext) {
                roleNames = new ArrayList<>();
                Set<Principal> roles = ((LoginSecurityContext) sc).getUserRoles();
                for (Principal p : roles) {
                    roleNames.add(p.getName());
                }
            }
            token.setSubject(new UserSubject(sc.getUserPrincipal() == null ? null : sc.getUserPrincipal().getName(), roleNames));
            AuthorizationInput input = new AuthorizationInput();
            input.setToken(token);
            Set<OAuthPermission> approvedScopesSet = new HashSet<>();
            List<OAuthPermission> originalScopes = token.getScopes();
            for (OAuthPermission perm : originalScopes) {
                String param = oAuthMessage.getParameter(perm.getPermission() + "_status");
                if (param != null && OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(param)) {
                    approvedScopesSet.add(perm);
                }
            }
            List<OAuthPermission> approvedScopes = new LinkedList<OAuthPermission>(approvedScopesSet);
            if (approvedScopes.isEmpty()) {
                approvedScopes = originalScopes;
            } else if (approvedScopes.size() < originalScopes.size()) {
                for (OAuthPermission perm : originalScopes) {
                    if (perm.isDefault() && !approvedScopes.contains(perm)) {
                        approvedScopes.add(perm);
                    }
                }
            }
            input.setApprovedScopes(approvedScopes);
            String verifier = dataProvider.finalizeAuthorization(input);
            queryParams.put(OAuth.OAUTH_VERIFIER, verifier);
        } else {
            dataProvider.removeToken(token);
        }
        queryParams.put(OAuth.OAUTH_TOKEN, token.getTokenKey());
        if (token.getState() != null) {
            queryParams.put(OAuthConstants.X_OAUTH_STATE, token.getState());
        }
        String callbackValue = getCallbackValue(token);
        if (OAuthConstants.OAUTH_CALLBACK_OOB.equals(callbackValue)) {
            OOBAuthorizationResponse bean = convertQueryParamsToOOB(queryParams);
            return Response.ok().entity(bean).build();
        }
        URI callbackURI = buildCallbackURI(callbackValue, queryParams);
        return Response.seeOther(callbackURI).build();
    } catch (OAuthProblemException e) {
        LOG.log(Level.WARNING, "An OAuth related problem: {0}", new Object[] { e.fillInStackTrace() });
        int code = e.getHttpStatusCode();
        if (code == HttpServletResponse.SC_OK) {
            code = e.getProblem() == OAuth.Problems.CONSUMER_KEY_UNKNOWN ? 401 : 400;
        }
        return OAuthUtils.handleException(mc, e, code);
    } catch (OAuthServiceException e) {
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected internal server exception: {0}", new Object[] { e.fillInStackTrace() });
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : OAuthPermission(org.apache.cxf.rs.security.oauth.data.OAuthPermission) HashMap(java.util.HashMap) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) AuthorizationInput(org.apache.cxf.rs.security.oauth.data.AuthorizationInput) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSubject(org.apache.cxf.rs.security.oauth.data.UserSubject) RequestToken(org.apache.cxf.rs.security.oauth.data.RequestToken) HashSet(java.util.HashSet) OAuthMessage(net.oauth.OAuthMessage) LinkedList(java.util.LinkedList) OAuthProblemException(net.oauth.OAuthProblemException) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) IOException(java.io.IOException) OAuthProblemException(net.oauth.OAuthProblemException) SecurityContext(org.apache.cxf.security.SecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) DefaultOAuthValidator(org.apache.cxf.rs.security.oauth.provider.DefaultOAuthValidator) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth.data.OAuthAuthorizationData) Principal(java.security.Principal)

Example 10 with LoginSecurityContext

use of org.apache.cxf.security.LoginSecurityContext in project cxf by apache.

the class RolePrefixSecurityContextImplTest method testMultipleRoles.

@Test
public void testMultipleRoles() {
    Subject s = new Subject();
    Principal p = new SimplePrincipal("Barry");
    s.getPrincipals().add(p);
    Set<Principal> roles = new HashSet<>();
    roles.add(new SimplePrincipal("role_friend"));
    roles.add(new SimplePrincipal("role_admin"));
    s.getPrincipals().addAll(roles);
    LoginSecurityContext context = new RolePrefixSecurityContextImpl(s, "role_");
    assertTrue(context.isUserInRole("role_friend"));
    assertTrue(context.isUserInRole("role_admin"));
    assertFalse(context.isUserInRole("role_bar"));
    Set<Principal> roles2 = context.getUserRoles();
    assertEquals(roles2, roles);
}
Also used : LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) Subject(javax.security.auth.Subject) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

LoginSecurityContext (org.apache.cxf.security.LoginSecurityContext)11 Principal (java.security.Principal)10 Subject (javax.security.auth.Subject)6 SecurityContext (org.apache.cxf.security.SecurityContext)5 HashSet (java.util.HashSet)4 SimplePrincipal (org.apache.cxf.common.security.SimplePrincipal)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)2 GroupPrincipal (org.apache.cxf.common.security.GroupPrincipal)2 AccessDeniedException (org.apache.cxf.interceptor.security.AccessDeniedException)2 Message (org.apache.cxf.message.Message)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 URI (java.net.URI)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 X500Principal (javax.security.auth.x500.X500Principal)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 QName (javax.xml.namespace.QName)1 OAuthMessage (net.oauth.OAuthMessage)1