This endpoint is called when Keycloak redirects the logged in user to our application.

@return a response with a TokenCreateResponse as entity.
505824
@GET
    @Path("create")
    public Response createFromRedirect() {
        KeycloakPrincipal principal = (KeycloakPrincipal) sessionContext.getCallerPrincipal();
        RefreshableKeycloakSecurityContext kcSecurityContext = (RefreshableKeycloakSecurityContext)
                principal.getKeycloakSecurityContext();

        String refreshToken = kcSecurityContext.getRefreshToken();
        Token token = create(refreshToken);
        try {
            String redirectTo = System.getProperty("secretstore.redirectTo");

            if (null == redirectTo || redirectTo.isEmpty()) {
                return Response.ok("Redirect URL was not specified but token was created.").build();
            }

            URI location;
            if (redirectTo.toLowerCase().startsWith("http")) {
                location = new URI(redirectTo);
            } else {
                URI uri = uriInfo.getAbsolutePath();
                String newPath = redirectTo.replace("{tokenId}", token.getId().toString());
                location = new URI(
                        uri.getScheme(),
                        uri.getUserInfo(),
                        uri.getHost(),
                        uri.getPort(),
                        newPath,
                        uri.getQuery(),
                        uri.getFragment()
                );
            }

            return Response.seeOther(location).build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return Response.ok("Could not redirect back to the original URL, but token was created.").build();
        }
    }
589422
@Produces
    @LoggedIn
    public String extractUsername() {

        final KeycloakPrincipal principal = (KeycloakPrincipal) httpServletRequest.getUserPrincipal();
        if (principal != null) {
            logger.debug("Running with Keycloak context");
            KeycloakSecurityContext kcSecurityContext = principal.getKeycloakSecurityContext();
            return kcSecurityContext.getToken().getPreferredUsername();
        }

        logger.debug("Running outside of Keycloak context");
        final String basicUsername = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(httpServletRequest)[0];
        if (! basicUsername.isEmpty()) {
            logger.debug("running HttpBasic auth");
            return basicUsername;
        }

        logger.debug("Running without any Auth context");
        return "admin"; // by default, we are admin!
    }
602020
@Override
    public Response before(FilterChain chain, Context context) {
        SessionFacade session = context.getSession(false);//true?
        
        if (context.httpMethod() == HttpMethod.GET) {
            String path = context.path();
            if (path.equals(notLoggedInRedirect)) {
                // redirect to a known location if the user is actually logged in
                if (session != null && createSubject(context).hasRole(role))
                    return ResponseBuilder.redirect("/");
                
                // fall through as the user is not logged in
                return chain.before(context);
            } else if (path.equals(logout)) {
                if (session != null) {
                    Subject subject = session.get(SESSION_USER, Subject.class);
                    if (subject != null) {
                        subject.logout();
                        session.remove(SESSION_USER);
                    }
                }
                return chain.before(context);
            }
        }
        // is a session already active?
        // - if not -> surely an user cannot already have logged in (disregarding cookies at this time)
        // does the session have a subject associated?
        //  - if not -> an user is of course not authenticated
        // the subject exists
        // - (should we ask if authenticated, or is this auth enough?)
        // does the subject have the required role?
        // - if not -> return not authorized response
        
        String username = context.getParameter("username");
        String password = context.getParameter("password");
        String remember = context.getParameter("rememberMe"); //TODO handle cookie independently with framework
        
        System.out.println(MessageFormat.format("username {0} + pass {1} + remember {2} --  ip {3},{4},{5}", username, password, remember, context.ipAddress(), context.remoteAddress(), context.remoteHost()));

        // get the current user
        // if not already existing, create and save user
        if (session == null) {
            session = context.getSession(true);
            
//            context.finalizeResponse(ResponseBuilder.redirect(notLoggedInRedirect));
//            return null;//TODO Response with login html
        }
        
        
        
        //according to AbstractShiroFilter:
        //get request + response (meaning Context)
        //create a subject
        //updateSessionLastAccessTime
        Subject sub = createSubject(context);
        updateSessionLastAccessTime(sub);
        session.put(SESSION_USER, sub);
        
        //Only trust cookies for a period of time
        //Perhaps have the date as a part of the principal (or an extra DatePrincipal)
        //When date is exceeded re-login
        //The IP<->Cookie relationship also has to be taken into consideration
        //Perhaps this also ought to be a principal (IpPrincipal)
        System.out.println("is remembered? " + sub.isRemembered());
//        System.out.println(sub.getPrincipals().getPrimaryPrincipal());
        
        Subject subject = sub;
/*        Subject subject = session.get(SESSION_USER, Subject.class);
        if (subject == null) {
            ContextImpl c = (ContextImpl)context;
            subject = new WebSubject.Builder(c.getOriginalRequest(), c.getOriginalResponse())
//                            .sessionId(session.getId())
                            .host(context.ipAddress())
                            .sessionCreationEnabled(false)
                            .buildSubject();
//            ThreadContext.bind(subject);
            session.put(SESSION_USER, subject);
//            context.finalizeResponse(ResponseBuilder.redirect(notLoggedInRedirect));
//            return null;
        }*/
        
        if (!subject.isAuthenticated()) {
            
            System.out.println("not AUTH");
            
            if (context.httpMethod() == HttpMethod.POST) {
            
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setHost(context.host());
                token.setRememberMe(context.getParameter("rememberMe") != null); //TODO rememberme needs to be implemented manually
                try {
    //                SecurityUtils.getSecurityManager().login(subject, token);
                    subject.login(token);
                    
                } catch ( UnknownAccountException | IncorrectCredentialsException ice ) {
                    //UnknownAccountException:       username wasn't in the system, show them an error message?
                    //IncorrectCredentialsException: password didn't match, try again?
                    context.setFlash("credentials", "not match");
                    return  ResponseBuilder.redirect(notLoggedInRedirect + "?credentials");//add flash telling the credentials were not correct
                } catch ( LockedAccountException lae ) {
                    //account for that username is locked - can't login.  Show them a message?
                    lae.printStackTrace();
                } catch ( AuthenticationException ae ) {
                    //unexpected condition - error?
                    ae.printStackTrace();
                }
            //context.finalizeResponse(ResponseBuilder.noBody(401));// README could actually throw an exception instead
            } else {
                //save the path for later use
                session.put(SESSION_REQUESTED_PATH, context.path());
                return ResponseBuilder.redirect(notLoggedInRedirect);
            }
        }
        
        System.out.println(subject.getPrincipal() + " is AUTH ("+role+") " + subject.hasRole(role));
        
        
        //login was successful (whether the subject is authenticated or not)
        
        if (subject.hasRole(role)) {
            String location = session.get(SESSION_REQUESTED_PATH, String.class);
            session.remove(SESSION_REQUESTED_PATH);
            if (location != null)
                return ResponseBuilder.redirect(location);
            else
                return chain.before(context);
                //README Redirect to a 'defaultLoginWhenLocationNotFound'?
                //return ResponseBuilder.redirect("/");
        }
            //if not auth
        return ResponseBuilder.redirect(notAuthRedirect);
            
    }
738448
protected OAuthProviderToken createOAuthToken(ConsumerAuthentication authentication) {
    return getTokenServices().createUnauthorizedRequestToken(authentication.getConsumerDetails().getConsumerKey(),
                                                             authentication.getOAuthParameters().get(OAuthConsumerParameter.oauth_callback.toString()));
  }
245182
protected Response doRequest(HttpRequestBase request, String authorizationToken, Class<?> successResponseClass) {

		assertValid(authorizationToken, "An authorizationToken is required for web resource call");

		CloseableHttpClient httpclient = HttpClients.createDefault();
		request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		request.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		request.setHeader("Authorization", "Token " + authorizationToken);
		
		try {
			CloseableHttpResponse clientResponse = httpclient.execute(request);
		
		    HttpEntity entity = clientResponse.getEntity();

		    InputStream inputStream = entity.getContent();

		    StringWriter writer = new StringWriter();
		    IOUtils.copy(inputStream, writer, "UTF-8");
		    String json = writer.toString();
		    
		    LOG.debug("json: " + json);
		    
			Response response = (Response) OBJECT_MAPPER.readValue(json, successResponseClass);

			LOG.debug("response.statuscode: " + response.status_code);
			
			if (!StatusCode.SUCCESS.equals(response.status_code)) {

				throw new RuntimeException(response.toString());
			}

			Header totalCount = clientResponse.getFirstHeader("X-Total-Count");
			if (totalCount != null) {
				response.totalCount = Integer.valueOf(totalCount.getValue());
			}
		    EntityUtils.consume(entity);
			clientResponse.close();
		    
			LOG.debug("Response: " + response);
		    
			return response;

		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
730467
public function redirect()
    {
        $this->request->session()->put(
            'oauth.temp', $temp = $this->server->getTemporaryCredentials()
        );

        return new RedirectResponse($this->server->getAuthorizationUrl($temp));
    }
1338414
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // if the user hit a secure page and start() was called, this was
        // the URL they were on, and probably where you want to redirect to
        $targetPath = $request->getSession()->get('_security.'.$providerKey.'.target_path');

        if (!$targetPath) {
            $targetPath = $this->getDefaultSuccessRedirectUrl();
        }

        return new RedirectResponse($targetPath);
    }
763838
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        // get url to redirect (or return in the JSON-response)
        if ($this->session->get('_security.admin.target_path')
            && false !== strpos($this->session->get('_security.admin.target_path'), '#')
        ) {
            $url = $this->session->get('_security.admin.target_path');
        } else {
            $url = $this->router->generate('sulu_admin');
        }

        if ($request->isXmlHttpRequest()) {
            // if AJAX login
            $array = ['url' => $url];
            $response = new JsonResponse($array, 200);
        } else {
            // if form login
            $response = new RedirectResponse($url);
        }

        return $response;
    }
472746
private AuthenticationResult handleRedirect(HttpServletRequest req,
                                                HttpServletResponse res,
                                                WebRequest webRequest) {
        AuthenticationResult authResult;

        String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "form login URL: " + loginURL);
        }

        authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL);

        if (allowToAddCookieToResponse(webAppSecurityConfig, req)) {
            postParameterHelper.save(req, res, authResult);
            ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler();
//            referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req));
            Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req);
            authResult.setCookie(c);
        }

        return authResult;
    }
402169
public function authorize()
    {
        // Create the request and response objects
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();

        // Validate the authorize request
        if (!$this->tokenServer->validateAuthorizeRequest($request, $response)) {
            // Get the data as json and convert it to an array,
            // - so we can set our own response type.
            $data = $response->getResponseBody('json');
            $data = json_decode($data, true);

            // Set the response, status code and output content setting final output to true
            $this->response = $data;
            $this->statusCode = $response->getStatusCode();
            $this->output(true);
            return $this;
        }

        // Display an authorization form
        if ($this->method != 'post' || !isset($this->data['authorized'])) {
            // Get the authorization form
            ob_start();
            require $this->configuration->getAuthorizationForm();
            $form = ob_get_clean();
            $this->response = $form;
            $this->statusCode = 200;
            $this->responseType = 'text/html';
            $this->output(true);
            return $this;
        }

        // Print the authorization code if the user has authorized your client
        $isAuthorized = ($this->data['authorized'] === 'yes');
        $this->tokenServer->handleAuthorizeRequest($request, $response, $isAuthorized);

        // Check if the request was successful
        if ($response->getStatusCode() === 302) {
            // Check if we should redirect according to our configuration
            if ($this->configuration->getRedirectAuthorization() === true) {
                // The response will contain a Location header we should navigate to
                header('Location: ' . $response->getHttpHeader('Location'));
                exit;
            }

            // Create a response with the authorization code
            $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
            $this->response = ['status' => 1, 'authorization_code' => $code];
            $this->statusCode = 200;
            $this->output(true);
            return $this;
        }

        // Get the data as json and convert it to an array,
        // - so we can set our own response type.
        $data = $response->getResponseBody('json');
        $data = json_decode($data, true);

        // Set the response, status code and output content setting final output to true
        $this->response = $data;
        $this->statusCode = $response->getStatusCode();
        $this->output(true);
        return $this;
    }
1249070
public TokenRequestBuilder getTokenEndPoint() {
    for(Authentication auth : getAuthentications().values()) {
      if (auth instanceof OAuth) {
        OAuth oauth = (OAuth) auth;
        return oauth.getTokenRequestBuilder();
      }
    }
    return null;
  }
1047657
public function redirect()
    {
        $this->request->getSession()->set(
            'oauth.temp', $temp = $this->server->getTemporaryCredentials()
        );

        return new RedirectResponse($this->server->getAuthorizationUrl($temp));
    }
1140963
public AuthorizationCodeRefreshRequest.Builder authorizationCodeRefresh() {
    return new AuthorizationCodeRefreshRequest.Builder(clientId, clientSecret)
            .setDefaults(httpManager, scheme, host, port)
            .grant_type("refresh_token")
            .refresh_token(refreshToken);
  }
593378
public Observable<UserInner> getPublishingUserAsync() {
        return getPublishingUserWithServiceResponseAsync().map(new Func1<ServiceResponse<UserInner>, UserInner>() {
            @Override
            public UserInner call(ServiceResponse<UserInner> response) {
                return response.body();
            }
        });
    }
617115
public ApiResponse<TokenInfoSuccessResponse> tokenInfoWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = tokenInfoValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<TokenInfoSuccessResponse>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }
876962
public function tokenAction()
    {
        $request = $this->getRequest();
        if (! $request instanceof HttpRequest) {
            // not an HTTP request; nothing left to do
            return;
        }

        if ($request->isOptions()) {
            // OPTIONS request.
            // This is most likely a CORS attempt; as such, pass the response on.
            return $this->getResponse();
        }

        $oauth2request = $this->getOAuth2Request();
        
        $response = $this->server->handleTokenRequest($oauth2request);
        if ($response->isClientError()) {
            $parameters = $response->getParameters();
            $errorUri   = isset($parameters['error_uri']) ? $parameters['error_uri'] : null;
            return new ApiProblemResponse(
                new ApiProblem(
                    $response->getStatusCode(),
                    $parameters['error_description'],
                    $errorUri,
                    $parameters['error']
                )
            );
        }
        return $this->setHttpResponse($response);
    }
793707
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(FACEBOOK_ACTION)) {
			String authCode = request.getParameter("code");
			if (!StringUtils.isBlank(authCode)) {
				String appid = SecurityUtils.getAppidFromAuthRequest(request);
				String redirectURI = SecurityUtils.getRedirectUrl(request);
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.FB_PREFIX);
				String url = Utils.formatMessage(TOKEN_URL, authCode, redirectURI, keys[0], keys[1]);
				try {
					HttpGet tokenPost = new HttpGet(url);
					String accessToken = parseAccessToken(httpclient.execute(tokenPost));
					if (accessToken != null) {
						userAuth = getOrCreateUser(app, accessToken);
					}
				} catch (Exception e) {
					logger.warn("Facebook auth request failed: GET " + url, e);
				}
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}