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;
}
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);
}
}
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));
}
}
}
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);
}
}
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);
}
Aggregations