org.jboss.resteasy.spi.HttpRequest Java Examples

The following examples show how to use org.jboss.resteasy.spi.HttpRequest. 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: BrowserHistoryHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Response saveResponseAndRedirect(KeycloakSession session, AuthenticationSessionModel authSession, Response response, boolean actionRequest, HttpRequest httpRequest) {
    if (!shouldReplaceBrowserHistory(actionRequest, httpRequest)) {
        return response;
    }

    // For now, handle just status 200 with String body. See if more is needed...
    if (response.getStatus() == 200) {
        Object entity = response.getEntity();
        if (entity instanceof String) {
            String responseString = (String) entity;
            authSession.setAuthNote(CACHED_RESPONSE, responseString);

            URI lastExecutionURL = new AuthenticationFlowURLHelper(session, session.getContext().getRealm(), session.getContext().getUri()).getLastExecutionUrl(authSession);

            if (logger.isTraceEnabled()) {
                logger.tracef("Saved response challenge and redirect to %s", lastExecutionURL);
            }

            return Response.status(302).location(lastExecutionURL).build();
        }
    }

    return response;
}
 
Example #2
Source File: MtlsHoKTokenUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static AccessToken.CertConf bindTokenWithClientCertificate(HttpRequest request, KeycloakSession session) {
    X509Certificate[] certs = getCertificateChain(request, session);

    if (certs == null || certs.length < 1) {
        logger.warnf("no client certificate available.");
        return null;
    }

    String DERX509Base64UrlEncoded = null;
    try {
        // On Certificate Chain, first entry is considered to be client certificate.
        DERX509Base64UrlEncoded = getCertificateThumbprintInSHA256DERX509Base64UrlEncoded(certs[0]);
        if (logger.isTraceEnabled()) dumpCertInfo(certs);
    } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
        // give up issuing MTLS HoK Token
        logger.warnf("give up issuing hok token. %s", e);
        return null;
    }

    AccessToken.CertConf certConf = new AccessToken.CertConf();
    certConf.setCertThumbprint(DERX509Base64UrlEncoded);
    return certConf;
}
 
Example #3
Source File: SynchronousDispatcherInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    HttpRequest request = (HttpRequest) allArguments[0];

    ContextCarrier contextCarrier = new ContextCarrier();
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        next.setHeadValue(request.getHttpHeaders().getHeaderString(next.getHeadKey()));
    }

    AbstractSpan span = ContextManager.createEntrySpan(request.getUri().getPath(), contextCarrier);
    Tags.URL.set(span, toPath(request.getUri().getRequestUri().toString()));
    Tags.HTTP.METHOD.set(span, request.getHttpMethod());
    span.setComponent(ComponentsDefine.RESTEASY);
    SpanLayer.asHttp(span);
}
 
Example #4
Source File: AbstractClientCertificateFromHttpHeadersLookup.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(HttpRequest httpRequest) throws GeneralSecurityException {
    List<X509Certificate> chain = new ArrayList<>();

    // Get the client certificate
    X509Certificate cert = getCertificateFromHttpHeader(httpRequest, sslClientCertHttpHeader);
    if (cert != null) {
        chain.add(cert);
        // Get the certificate of the client certificate chain
        for (int i = 0; i < certificateChainLength; i++) {
            try {
                String s = String.format("%s_%s", sslCertChainHttpHeaderPrefix, i);
                cert = getCertificateFromHttpHeader(httpRequest, s);
                if (cert != null) {
                    chain.add(cert);
                }
            }
            catch(GeneralSecurityException e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }
    return chain.toArray(new X509Certificate[0]);
}
 
Example #5
Source File: NginxProxySslClientCertificateLookup.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(HttpRequest httpRequest) throws GeneralSecurityException {
    List<X509Certificate> chain = new ArrayList<>();

    // Get the client certificate
    X509Certificate clientCert = getCertificateFromHttpHeader(httpRequest, sslClientCertHttpHeader);
    log.debugf("End user certificate found : Subject DN=[%s]  SerialNumber=[%s]", clientCert.getSubjectDN().toString(), clientCert.getSerialNumber().toString() );
    
    if (clientCert != null) {
        
    	// Rebuilding the end user certificate chain using Keycloak Truststore
        X509Certificate[] certChain = buildChain(clientCert);
        if ( certChain == null || certChain.length == 0 ) {
        	log.info("Impossible to rebuild end user cert chain : client certificate authentication will fail." );
        	chain.add(clientCert);
        } else {
        	for (X509Certificate cacert : certChain) {
        		chain.add(cacert);
        		log.debugf("Rebuilded user cert chain DN : %s", cacert.getSubjectDN().toString() );
        	}
        }
    }
    return chain.toArray(new X509Certificate[0]);
}
 
Example #6
Source File: SessionCodeChecks.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public SessionCodeChecks(RealmModel realm, UriInfo uriInfo, HttpRequest request, ClientConnection clientConnection, KeycloakSession session, EventBuilder event,
                         String authSessionId, String code, String execution, String clientId, String tabId, String flowPath) {
    this.realm = realm;
    this.uriInfo = uriInfo;
    this.request = request;
    this.clientConnection = clientConnection;
    this.session = session;
    this.event = event;

    this.code = code;
    this.execution = execution;
    this.clientId = clientId;
    this.tabId = tabId;
    this.flowPath = flowPath;
    this.authSessionId = authSessionId;
}
 
Example #7
Source File: NoCookieFlowRedirectAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    HttpRequest httpRequest = context.getHttpRequest();

    // only do redirects for GET requests
    if (HttpMethod.GET.equalsIgnoreCase(httpRequest.getHttpMethod())) {
        KeycloakUriInfo uriInfo = context.getSession().getContext().getUri();
        if (!uriInfo.getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
            Response response = Response.status(302).header(HttpHeaders.LOCATION, context.getRefreshUrl(true)).build();
            context.challenge(response);
            return;
        }
    }

    context.success();
}
 
Example #8
Source File: CdiPlugin.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Override
public void aroundRequest(HttpRequest req, RunnableWithException<IOException> continuation) throws IOException {
       BoundRequestContext cdiContext = CDI.current().select(BoundRequestContext.class).get();
       Map<String,Object> contextMap = new HashMap<String,Object>();
       cdiContext.associate(contextMap);
       cdiContext.activate();
       try {
       	// FIXME: associate CDI thread context on thread change, like Resteasy context?
       	continuation.run();
       }finally {
   		if(req.getAsyncContext().isSuspended()) {
   			req.getAsyncContext().getAsyncResponse().register((CompletionCallback)(t) -> {
       			cdiContext.invalidate();
       			cdiContext.deactivate();
       			cdiContext.dissociate(contextMap);
   			});
   		}else {
   			cdiContext.invalidate();
   			cdiContext.deactivate();
   			cdiContext.dissociate(contextMap);
   		}		
       }
}
 
Example #9
Source File: AuthorizeClientUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static AuthenticationProcessor getAuthenticationProcessor(KeycloakSession session, EventBuilder event) {
    RealmModel realm = session.getContext().getRealm();

    AuthenticationFlowModel clientAuthFlow = realm.getClientAuthenticationFlow();
    String flowId = clientAuthFlow.getId();

    AuthenticationProcessor processor = new AuthenticationProcessor();
    processor.setFlowId(flowId)
            .setConnection(session.getContext().getConnection())
            .setEventBuilder(event)
            .setRealm(realm)
            .setSession(session)
            .setUriInfo(session.getContext().getUri())
            .setRequest(session.getContext().getContextObject(HttpRequest.class));

    return processor;
}
 
Example #10
Source File: BrowserHistoryHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Response saveResponseAndRedirect(KeycloakSession session, AuthenticationSessionModel authSession, Response response, boolean actionRequest, HttpRequest httpRequest) {
    if (!shouldReplaceBrowserHistory(actionRequest, httpRequest)) {
        return response;
    }

    // For now, handle just status 200 with String body. See if more is needed...
    Object entity = response.getEntity();
    if (entity != null && entity instanceof String) {
        String responseString = (String) entity;

        URI lastExecutionURL = new AuthenticationFlowURLHelper(session, session.getContext().getRealm(), session.getContext().getUri()).getLastExecutionUrl(authSession);

        // Inject javascript for history "replaceState"
        String responseWithJavascript = responseWithJavascript(responseString, lastExecutionURL.toString());

        return Response.fromResponse(response).entity(responseWithJavascript).build();
    }


    return response;
}
 
Example #11
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession,
                                                   ClientSessionContext clientSessionCtx,
                                            HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,
                                            EventBuilder event, AuthenticationSessionModel authSession) {
    LoginProtocol protocolImpl = session.getProvider(LoginProtocol.class, authSession.getProtocol());
    protocolImpl.setRealm(realm)
            .setHttpHeaders(request.getHttpHeaders())
            .setUriInfo(uriInfo)
            .setEventBuilder(event);
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession, protocolImpl);

}
 
Example #12
Source File: SynchronousDispatcherExceptionInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    if (ContextManager.isActive() && !((HttpRequest) allArguments[0]).getAsyncContext().isSuspended()) {
        ContextManager.activeSpan().errorOccurred().log((Throwable) allArguments[2]);
    }
}
 
Example #13
Source File: AbstractClientCertificateFromHttpHeadersLookup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected X509Certificate getCertificateFromHttpHeader(HttpRequest request, String httpHeader) throws GeneralSecurityException {

        String encodedCertificate = getHeaderValue(request, httpHeader);

        // Remove double quotes
        encodedCertificate = trimDoubleQuotes(encodedCertificate);

        if (encodedCertificate == null ||
                encodedCertificate.trim().length() == 0) {
            logger.warnf("HTTP header \"%s\" is empty", httpHeader);
            return null;
        }

        try {
            X509Certificate cert = decodeCertificateFromPem(encodedCertificate);
            if (cert == null) {
                logger.warnf("HTTP header \"%s\" does not contain a valid x.509 certificate\n%s",
                        httpHeader, encodedCertificate);
            } else {
                logger.debugf("Found a valid x.509 certificate in \"%s\" HTTP header",
                        httpHeader);
            }
            return cert;
        }
        catch(PemException e) {
            logger.error(e.getMessage(), e);
            throw new GeneralSecurityException(e);
        }
    }
 
Example #14
Source File: PluginRequestDispatcher.java    From redpipe with Apache License 2.0 5 votes vote down vote up
private void service(int i, Context context, HttpServerRequest req, HttpServerResponse resp, HttpRequest vertxReq,
		HttpResponse vertxResp, boolean handleNotFound) throws IOException {
	if(i < plugins.size())
		plugins.get(i).aroundRequest(vertxReq, () -> service(i+1, context, req, resp, vertxReq, vertxResp, handleNotFound));
	else
		super.service(context, req, resp, vertxReq, vertxResp, handleNotFound);
}
 
Example #15
Source File: LinkedAccountsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public LinkedAccountsResource(KeycloakSession session, 
                              HttpRequest request, 
                              ClientModel client,
                              Auth auth, 
                              EventBuilder event, 
                              UserModel user) {
    this.session = session;
    this.request = request;
    this.client = client;
    this.auth = auth;
    this.event = event;
    this.user = user;
    realm = session.getContext().getRealm();
}
 
Example #16
Source File: BrowserHistoryHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean shouldReplaceBrowserHistory(boolean actionRequest, HttpRequest httpRequest) {
    if (actionRequest) {
        return true;
    }

    Boolean flowChanged = (Boolean) httpRequest.getAttribute(SHOULD_UPDATE_BROWSER_HISTORY);
    return (flowChanged != null && flowChanged);
}
 
Example #17
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String nextRequiredAction(final KeycloakSession session, final AuthenticationSessionModel authSession,
                                        final ClientConnection clientConnection,
                                        final HttpRequest request, final UriInfo uriInfo, final EventBuilder event) {
    final RealmModel realm = authSession.getRealm();
    final UserModel user = authSession.getAuthenticatedUser();
    final ClientModel client = authSession.getClient();

    evaluateRequiredActionTriggers(session, authSession, clientConnection, request, uriInfo, event, realm, user);

    if (!user.getRequiredActions().isEmpty()) {
        return user.getRequiredActions().iterator().next();
    }
    if (!authSession.getRequiredActions().isEmpty()) {
        return authSession.getRequiredActions().iterator().next();
    }

    String kcAction = authSession.getClientNote(Constants.KC_ACTION);
    if (kcAction != null) {
        return kcAction;
    }

    if (client.isConsentRequired()) {

        UserConsentModel grantedConsent = getEffectiveGrantedConsent(session, authSession);

        // See if any clientScopes need to be approved on consent screen
        List<ClientScopeModel> clientScopesToApprove = getClientScopesToApproveOnConsentScreen(realm, grantedConsent, authSession);
        if (!clientScopesToApprove.isEmpty()) {
            return CommonClientSessionModel.Action.OAUTH_GRANT.name();
        }

        String consentDetail = (grantedConsent != null) ? Details.CONSENT_VALUE_PERSISTED_CONSENT : Details.CONSENT_VALUE_NO_CONSENT_REQUIRED;
        event.detail(Details.CONSENT, consentDetail);
    } else {
        event.detail(Details.CONSENT, Details.CONSENT_VALUE_NO_CONSENT_REQUIRED);
    }
    return null;

}
 
Example #18
Source File: SessionResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SessionResource(KeycloakSession session, Auth auth, HttpRequest request) {
    this.session = session;
    this.auth = auth;
    this.realm = auth.getRealm();
    this.user = auth.getUser();
    this.request = request;
}
 
Example #19
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(final AuthenticationFlowContext context) {
    final HttpRequest httpRequest = context.getHttpRequest();
    final HttpHeaders httpHeaders = httpRequest.getHttpHeaders();
    final String[] usernameAndPassword = getUsernameAndPassword(httpHeaders);

    context.attempted();

    if (usernameAndPassword != null) {
        final RealmModel realm = context.getRealm();
        final String username = usernameAndPassword[0];
        final UserModel user = context.getSession().users().getUserByUsername(username, realm);

        // to allow success/failure logging for brute force
        context.getEvent().detail(Details.USERNAME, username);
        context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        if (user != null) {
            final String password = usernameAndPassword[1];
            final boolean valid = context.getSession().userCredentialManager().isValid(realm, user, UserCredentialModel.password(password));

            if (valid) {
                if (isTemporarilyDisabledByBruteForce(context, user)) {
                    userDisabledAction(context, realm, user, Errors.USER_TEMPORARILY_DISABLED);
                } else if (user.isEnabled()) {
                    userSuccessAction(context, user);
                } else {
                    userDisabledAction(context, realm, user, Errors.USER_DISABLED);
                }
            } else {
                notValidCredentialsAction(context, realm, user);
            }
        } else {
            nullUserAction(context, realm, username);
        }
    }
}
 
Example #20
Source File: ActionTokenContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ActionTokenContext(KeycloakSession session, RealmModel realm, UriInfo uriInfo,
  ClientConnection clientConnection, HttpRequest request,
  EventBuilder event, ActionTokenHandler<T> handler, String executionId,
  ProcessAuthenticateFlow processFlow, ProcessBrokerFlow processBrokerFlow) {
    this.session = session;
    this.realm = realm;
    this.uriInfo = uriInfo;
    this.clientConnection = clientConnection;
    this.request = request;
    this.event = event;
    this.handler = handler;
    this.executionId = executionId;
    this.processAuthenticateFlow = processFlow;
    this.processBrokerFlow = processBrokerFlow;
}
 
Example #21
Source File: RequiredActionContextResult.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public RequiredActionContextResult(AuthenticationSessionModel authSession,
                                   RealmModel realm, EventBuilder eventBuilder, KeycloakSession session,
                                   HttpRequest httpRequest,
                                   UserModel user, RequiredActionFactory factory) {
    this.authenticationSession = authSession;
    this.realm = realm;
    this.eventBuilder = eventBuilder;
    this.session = session;
    this.httpRequest = httpRequest;
    this.user = user;
    this.factory = factory;
}
 
Example #22
Source File: VertxClientCertificateLookup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(HttpRequest httpRequest) {
    Instance<RoutingContext> instances = CDI.current().select(RoutingContext.class);

    if (instances.isResolvable()) {
        RoutingContext context = instances.get();

        try {
            SSLSession sslSession = context.request().sslSession();
            
            if (sslSession == null) {
                return null;
            }
            
            X509Certificate[] certificates = (X509Certificate[]) sslSession.getPeerCertificates();

            if (logger.isTraceEnabled() && certificates != null) {
                for (X509Certificate cert : certificates) {
                    logger.tracef("Certificate's SubjectDN => \"%s\"", cert.getSubjectDN().getName());
                }
            }

            return certificates;
        } catch (SSLPeerUnverifiedException ignore) {
            // client not authenticated
        }
    }

    return null;
}
 
Example #23
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void evaluateRequiredActionTriggers(final KeycloakSession session, final AuthenticationSessionModel authSession, final ClientConnection clientConnection, final HttpRequest request, final UriInfo uriInfo, final EventBuilder event, final RealmModel realm, final UserModel user) {

        // see if any required actions need triggering, i.e. an expired password
        for (RequiredActionProviderModel model : realm.getRequiredActionProviders()) {
            if (!model.isEnabled()) continue;
            RequiredActionFactory factory = (RequiredActionFactory)session.getKeycloakSessionFactory().getProviderFactory(RequiredActionProvider.class, model.getProviderId());
            if (factory == null) {
                throw new RuntimeException("Unable to find factory for Required Action: " + model.getProviderId() + " did you forget to declare it in a META-INF/services file?");
            }
            RequiredActionProvider provider = factory.create(session);
            RequiredActionContextResult result = new RequiredActionContextResult(authSession, realm, event, session, request, user, factory) {
                @Override
                public void challenge(Response response) {
                    throw new RuntimeException("Not allowed to call challenge() within evaluateTriggers()");
                }

                @Override
                public void failure() {
                    throw new RuntimeException("Not allowed to call failure() within evaluateTriggers()");
                }

                @Override
                public void success() {
                    throw new RuntimeException("Not allowed to call success() within evaluateTriggers()");
                }

                @Override
                public void ignore() {
                    throw new RuntimeException("Not allowed to call ignore() within evaluateTriggers()");
                }
            };

            provider.evaluateTriggers(result);
        }
    }
 
Example #24
Source File: MtlsHoKTokenUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate[] getCertificateChain(HttpRequest request, KeycloakSession session) {
    try {
           // Get a x509 client certificate
        X509ClientCertificateLookup provider = session.getProvider(X509ClientCertificateLookup.class);
        if (provider == null) {
            logger.errorv("\"{0}\" Spi is not available, did you forget to update the configuration?", X509ClientCertificateLookup.class);
        return null;
        }
        X509Certificate[] certs = provider.getCertificateChain(request);
        return certs;
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example #25
Source File: AuthorizationTokenService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public KeycloakAuthorizationRequest(AuthorizationProvider authorization, TokenManager tokenManager, EventBuilder event, HttpRequest request, Cors cors) {
    this.authorization = authorization;
    this.tokenManager = tokenManager;
    this.event = event;
    httpRequest = request;
    this.cors = cors;
}
 
Example #26
Source File: SiestaResourceMethodFinder.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public ResourceMethodInvoker getResourceMethod(final HttpServletRequest request,
                                               final HttpServletResponse response)
{
  HttpRequest httpRequest = new HttpServletInputMessage(
      request,
      response,
      request.getServletContext(),
      null,
      extractHttpHeaders(request),
      extractUriInfo(request, MOUNT_POINT),
      request.getMethod(),
      (SynchronousDispatcher) this.componentContainer.getDispatcher());

  return (ResourceMethodInvoker) deployment.getRegistry().getResourceInvoker(httpRequest);
}
 
Example #27
Source File: SisuResourceFactory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object createResource(final HttpRequest request,
                             final HttpResponse response,
                             final ResteasyProviderFactory factory)
{
  final Object resource = entry.getValue();
  propertyInjector.inject(request, response, resource);
  return resource;
}
 
Example #28
Source File: GuiceRsApplicationServlet.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Override
public Object createResource(HttpRequest request, HttpResponse response, ResteasyProviderFactory factory)
{
    Object resource = provider.get();
    contextPropertyInjector.inject(request, response, resource);
    return resource;
}
 
Example #29
Source File: LoggingInterceptor.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method)
        throws Failure, WebApplicationException {
    if (logger.isDebugEnabled()) {

        String httpMethod = request.getHttpMethod();

        URI uri = ui.getRequestUri();

        String uriPath = uri.getPath();
        if (uri.getQuery() != null) {
            uriPath += "?" + uri.getQuery();
        }
        if (uri.getFragment() != null) {
            uriPath += "#" + uri.getFragment();
        }

        String sessionid = null;
        List<String> headerSessionId = request.getHttpHeaders().getRequestHeader("sessionid");
        if (headerSessionId != null) {
            sessionid = headerSessionId.get(0);
        }
        if (logger.isDebugEnabled()) {
            // log only in debug mode
            logger.debug(sessionid + "|" + httpMethod + "|" + uriPath);
        }
    }
    return null;
}
 
Example #30
Source File: TestSamlApplicationResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.TEXT_HTML_UTF_8)
@Path("/{action}")
public String post(@PathParam("action") String action) {
    String title = "APP_REQUEST";
    if (action.equals("auth")) {
        title = "AUTH_RESPONSE";
    } else if (action.equals("logout")) {
        title = "LOGOUT_REQUEST";
    }

    StringBuilder sb = new StringBuilder();
    sb.append("<html><head><title>" + title + "</title></head><body>");

    sb.append("<b>Form parameters: </b><br>");
    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    MultivaluedMap<String, String> formParams = request.getDecodedFormParameters();
    for (String paramName : formParams.keySet()) {
        sb.append(paramName).append(": ").append("<span id=\"").append(paramName).append("\">").append(formParams.getFirst(paramName)).append("</span><br>");
    }
    sb.append("<br>");

    UriBuilder base = UriBuilder.fromUri("/auth");
    sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>");

    sb.append("</body></html>");
    return sb.toString();
}