use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.
the class EndpointSessionHandler method onConnect.
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
ConfiguredServerEndpoint config = HandshakeUtil.getConfig(channel);
try {
if (container.isClosed()) {
//if the underlying container is closed we just reject
channel.sendClose();
channel.resumeReceives();
return;
}
InstanceFactory<?> endpointFactory = config.getEndpointFactory();
ServerEndpointConfig.Configurator configurator = config.getEndpointConfiguration().getConfigurator();
final InstanceHandle<?> instance;
DefaultContainerConfigurator.setCurrentInstanceFactory(endpointFactory);
final Object instanceFromConfigurator = configurator.getEndpointInstance(config.getEndpointConfiguration().getEndpointClass());
final InstanceHandle<?> factoryInstance = DefaultContainerConfigurator.clearCurrentInstanceFactory();
if (factoryInstance == null) {
instance = new ImmediateInstanceHandle<>(instanceFromConfigurator);
} else if (factoryInstance.getInstance() == instanceFromConfigurator) {
instance = factoryInstance;
} else {
//the default instance has been wrapped
instance = new InstanceHandle<Object>() {
@Override
public Object getInstance() {
return instanceFromConfigurator;
}
@Override
public void release() {
factoryInstance.release();
}
};
}
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
Principal principal = exchange.getAttachment(HandshakeUtil.PRINCIPAL);
if (principal == null) {
if (src.getServletRequest() instanceof HttpServletRequest) {
principal = ((HttpServletRequest) src.getServletRequest()).getUserPrincipal();
} else {
principal = src.getOriginalRequest().getUserPrincipal();
}
}
final InstanceHandle<Endpoint> endpointInstance;
if (config.getAnnotatedEndpointFactory() != null) {
final AnnotatedEndpoint annotated = config.getAnnotatedEndpointFactory().createInstance(instance);
endpointInstance = new InstanceHandle<Endpoint>() {
@Override
public Endpoint getInstance() {
return annotated;
}
@Override
public void release() {
instance.release();
}
};
} else {
endpointInstance = (InstanceHandle<Endpoint>) instance;
}
UndertowSession session = new UndertowSession(channel, URI.create(exchange.getRequestURI()), exchange.getAttachment(HandshakeUtil.PATH_PARAMS), exchange.getRequestParameters(), this, principal, endpointInstance, config.getEndpointConfiguration(), exchange.getQueryString(), config.getEncodingFactory().createEncoding(config.getEndpointConfiguration()), config, channel.getSubProtocol(), Collections.<Extension>emptyList(), null);
config.addOpenSession(session);
session.setMaxBinaryMessageBufferSize(getContainer().getDefaultMaxBinaryMessageBufferSize());
session.setMaxTextMessageBufferSize(getContainer().getDefaultMaxTextMessageBufferSize());
session.setMaxIdleTimeout(getContainer().getDefaultMaxSessionIdleTimeout());
session.getAsyncRemote().setSendTimeout(getContainer().getDefaultAsyncSendTimeout());
try {
endpointInstance.getInstance().onOpen(session, config.getEndpointConfiguration());
} catch (Exception e) {
endpointInstance.getInstance().onError(session, e);
IoUtils.safeClose(session);
}
channel.resumeReceives();
} catch (Exception e) {
JsrWebSocketLogger.REQUEST_LOGGER.endpointCreationFailed(e);
IoUtils.safeClose(channel);
}
}
use of io.undertow.servlet.handlers.ServletRequestContext in project wildfly by wildfly.
the class GlobalRequestControllerHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
RunResult result = entryPoint.beginRequest();
try {
if (result == RunResult.RUN) {
next.handleRequest(exchange);
} else {
boolean allowed = false;
for (Predicate allow : allowSuspendedRequests) {
if (allow.resolve(exchange)) {
allowed = true;
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (src != null) {
src.getServletRequest().setAttribute(ORG_WILDFLY_SUSPENDED, "true");
}
next.handleRequest(exchange);
break;
}
}
if (!allowed) {
exchange.setStatusCode(503);
exchange.endExchange();
}
}
} finally {
if (result == RunResult.RUN && (exchange.isComplete() || !exchange.isDispatched())) {
entryPoint.requestComplete();
} else if (result == RunResult.RUN) {
exchange.addExchangeCompleteListener(listener);
}
}
}
use of io.undertow.servlet.handlers.ServletRequestContext in project wildfly by wildfly.
the class JASPICAuthenticationMechanism method createMessageInfo.
private GenericMessageInfo createMessageInfo(final HttpServerExchange exchange, final SecurityContext securityContext) {
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
GenericMessageInfo messageInfo = new GenericMessageInfo();
messageInfo.setRequestMessage(servletRequestContext.getServletRequest());
messageInfo.setResponseMessage(servletRequestContext.getServletResponse());
messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", isMandatory(servletRequestContext).toString());
// additional context data, useful to provide access to Undertow resources during the modules processing
messageInfo.getMap().put(SECURITY_CONTEXT_ATTACHMENT_KEY, securityContext);
messageInfo.getMap().put(HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY, exchange);
return messageInfo;
}
use of io.undertow.servlet.handlers.ServletRequestContext in project wildfly by wildfly.
the class JASPICAuthenticationMechanism method authenticate.
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext sc) {
exchange.putAttachment(AUTH_RUN, true);
final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
final JASPIServerAuthenticationManager sam = createJASPIAuthenticationManager();
final GenericMessageInfo messageInfo = createMessageInfo(exchange, sc);
final String applicationIdentifier = buildApplicationIdentifier(requestContext);
final JASPICallbackHandler cbh = new JASPICallbackHandler();
exchange.putAttachment(JASPICContext.ATTACHMENT_KEY, new JASPICContext(messageInfo, sam, cbh));
UndertowLogger.ROOT_LOGGER.debugf("validateRequest for layer [%s] and applicationContextIdentifier [%s]", JASPI_HTTP_SERVLET_LAYER, applicationIdentifier);
Account cachedAccount = null;
final JASPICSecurityContext jaspicSecurityContext = (JASPICSecurityContext) exchange.getSecurityContext();
final AuthenticatedSessionManager sessionManager = exchange.getAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY);
if (sessionManager != null) {
AuthenticatedSessionManager.AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
if (authSession != null) {
cachedAccount = authSession.getAccount();
// SAM modules via request.getUserPrincipal().
if (cachedAccount != null) {
jaspicSecurityContext.setCachedAuthenticatedAccount(cachedAccount);
}
}
}
AuthenticationMechanismOutcome outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
Account authenticatedAccount = null;
boolean isValid = sam.isValid(messageInfo, new Subject(), JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, cbh);
jaspicSecurityContext.setCachedAuthenticatedAccount(null);
if (isValid) {
// The CBH filled in the JBOSS SecurityContext, we need to create an Undertow account based on that
org.jboss.security.SecurityContext jbossSct = SecurityActions.getSecurityContext();
authenticatedAccount = createAccount(cachedAccount, jbossSct);
updateSubjectRoles(jbossSct);
}
// authType resolution (check message info first, then check for the configured auth method, then use mech-specific name).
String authType = (String) messageInfo.getMap().get(JASPI_AUTH_TYPE);
if (authType == null)
authType = this.configuredAuthMethod != null ? this.configuredAuthMethod : MECHANISM_NAME;
if (isValid && authenticatedAccount != null) {
outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
Object registerObj = messageInfo.getMap().get(JASPI_REGISTER_SESSION);
boolean cache = false;
if (registerObj != null && (registerObj instanceof String)) {
cache = Boolean.valueOf((String) registerObj);
}
sc.authenticationComplete(authenticatedAccount, authType, cache);
} else if (isValid && authenticatedAccount == null && !isMandatory(requestContext)) {
outcome = AuthenticationMechanismOutcome.NOT_ATTEMPTED;
} else {
outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
sc.authenticationFailed("JASPIC authentication failed.", authType);
// make sure we don't return status OK if the AuthException was thrown
if (wasAuthExceptionThrown(exchange) && !statusIndicatesError(exchange)) {
exchange.setResponseCode(DEFAULT_ERROR_CODE);
}
}
// A SAM can wrap the HTTP request/response objects - update the servlet request context with the values found in the message info.
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
servletRequestContext.setServletRequest((HttpServletRequest) messageInfo.getRequestMessage());
servletRequestContext.setServletResponse((HttpServletResponse) messageInfo.getResponseMessage());
return outcome;
}
use of io.undertow.servlet.handlers.ServletRequestContext in project wildfly by wildfly.
the class JASPICSecurityContext method buildMessageInfo.
/**
* <p>
* Builds the {@code MessageInfo} instance for the {@code cleanSubject()} call.
* </p>
*
* @return the constructed {@code MessageInfo} object.
*/
private MessageInfo buildMessageInfo() {
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
GenericMessageInfo messageInfo = new GenericMessageInfo();
messageInfo.setRequestMessage(servletRequestContext.getServletRequest());
messageInfo.setResponseMessage(servletRequestContext.getServletResponse());
// when calling cleanSubject, isMandatory must be set to true.
messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", "true");
return messageInfo;
}
Aggregations