Create the token.

@param Request $request     The request being processed.

@param string  $providerKey The provider key.

@return JavascriptWebToken|null
163344
public function createToken(Request $request, $providerKey)
    {
        if (!$this->secret) {
            return null;
        }

        // look for an authorization header
        $authorizationHeader = $request->headers->get('Authorization');

        if ($authorizationHeader === null) {
            return null;
        }

        if (0 !== stripos($authorizationHeader, 'Bearer ')) {
            return null;
        }

        // extract the JWT
        $authToken = substr($authorizationHeader, 7);

        try {
            // decode and validate the JWT - will throw exceptions for various conditions.
            $token = $this->decodeToken($authToken);
        } catch (\Exception $exception) {
            return null;
        }

        return new JavascriptWebToken($token, $providerKey);
    }
1289190
private function makeSign(BaseRequest $request, $secretKey, $endPoint)
    {
        $attr = $request->all();
        ksort($attr, SORT_STRING);

        $queryString = self::_buildParamStr($attr);

        $parseUrl = parse_url($endPoint);
        $srcString = $request->getMethod() . $parseUrl['host'] . $parseUrl['path'] . $queryString;

        return base64_encode(hash_hmac('sha1', $srcString, $secretKey, true));
    }
590415
protected function createAccessTokenProvider(ProviderRepository $repository)
    {
        Event::listen(AccessTokenCreated::class, function ($event) use ($repository) {
            $provider = config('auth.guards.api.provider');

            $repository->create($event->tokenId, $provider);
        });
    }
841716
private static function readToken(ServerRequestInterface $request, string $tokenKey): ?string
    {
        $token = is_array($form = $request->getParsedBody()) === true ? ($form[$tokenKey] ?? null) : null;

        return $token;
    }
356443
protected function getToken(Request $request)
    {
        try {
            $this->validateAuthorizationHeader($request);

            $token = $this->parseAuthorizationHeader($request);
        } catch (Exception $exception) {
            if (! $token = $request->query('token', false)) {
                throw $exception;
            }
        }

        return $token;
    }
86100
private function isAdminToken($providerKey, TokenInterface $token = null)
    {
        return is_callable([$token, 'getProviderKey']) && $token->getProviderKey() === $providerKey;
    }
1057685
public function post(Request $request)
    {
        $id    = $request->attributes->get('id');
        $token = Arr::get($this->getContentAsArray($request), 'token');

        if (! $token) {
            return $this->createSimpleResponse(422, 'Token not specified.');
        }

        $conditions = [
            'user_id'       => $id,
            'token'         => $token,
            'token_type_id' => TokenEntity::TYPE_VERIFY_REGISTRATION,
        ];

        $token = $this->userService->findTokenBy($conditions);

        if (! $token) {
            return $this->createNotFoundResponse();
        }

        try {
            $user = $this->userService->verifyRegistration($token);
        } catch (OutOfBoundsException $e) {
            $httpCodes = [
                UserService::INCORRECT_TOKEN_TYPE => 422,
                UserService::TOKEN_EXPIRED        => 410,
                UserService::TOKEN_NOT_FOUND      => 404,
            ];

            return $this->createErrorResponse(
                ['token' => ['INVALID']],
                $httpCodes[$e->getCode()]
            );
        }

        $user = $user->getArrayCopy();

        unset($user['password']);

        return $user;
    }
937665
public function authenticateToken(TokenInterface $token,
                                      UserProviderInterface $userProvider,
                                      $providerKey)
    {
        if (($user = $userProvider->loadUserByUsername($token->getUsername())) && ($user->getPassword()
            == $token->getCredentials())) {
            return new UsernamePasswordToken(
                $user, $user->getPassword(), $providerKey, $user->getRoles()
            );
        }
        throw new BadCredentialsException('The presented password is invalid.');
    }
1054916
public function fetchRequestToken(&$request)
    {
        $this->getVersion($request);

        $consumer = $this->getConsumer($request);

        // no token required for the initial token request
        $token = null;

        $this->checkSignature($request, $consumer, $token);

        // Rev A change
        $callback = $request->get_parameter('oauth_callback');
        $new_token = $this->data_store->new_request_token($consumer, $callback);

        return $new_token;
    }
771338
public static function create($baseUrl, $signKey = null)
    {
        $httpSignature = null;

        if (!is_null($signKey)) {
            $httpSignature = SignatureFactory::create($signKey);
        }

        return new UrlBuilder($baseUrl, $httpSignature);
    }
577799
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        if (empty($this->secretKey) == false) {
            $captcha = $this->request->get('g-recaptcha-response');

            $reCaptcha = new ReCaptcha($this->secretKey);
            $response = $reCaptcha->verify($captcha, $this->request->getClientIp());

            if ($response->isSuccess() == false) {
                throw new AuthenticationException('Captcha not passed');
            }
        }

        try {
            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException('Invalid username or password');
        }

        $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());

        if ($passwordValid) {
            return new UsernamePasswordToken(
                $user,
                $user->getPassword(),
                $providerKey,
                $user->getRoles()
            );
        }

        throw new AuthenticationException('Invalid username or password');
    }
461208
public function callback(Request $request)
    {
        // Check to see if this provider exists and has a callback implemented
        $provider = strtolower($request->attributes->get('provider'));

        if (! $this->providerExists($provider)) {
            return $this->createNotFoundResponse();
        }

        if (! method_exists($this, $provider)) {
            throw new LogicException(sprintf(
                'Callback for provider \'%s\' not implemented',
                $provider
            ));
        }

        // Use provider service and access token from provider to create a LoginRequest for our app
        $code            = $request->query->get('code');
        $providerService = $this->getServiceByProvider($provider);
        $providerToken   = $providerService->requestAccessToken($code);

        $socialLoginRequest = $this->$provider($providerService, $providerToken);

        // Handle login or link-account request and redirect to the redirect-url
        $state = (int) $request->query->get('state');
        try {
            if ($state === self::ACTION_LOGIN_WITH_ACCOUNT) {
                $token = $this->service->handleLoginRequest($socialLoginRequest);
            } elseif ($state === self::ACTION_LINK_ACCOUNT) {
                $token = $this->service->handleLinkRequest(
                    $socialLoginRequest,
                    $this->session->get('user')
                );
            } else {
                return new Response(
                    'State parameter not set',
                    422
                );
            }

            $redirect = $this->config['redirect-url'];
            $redirect .= '?'.http_build_query($token);
        } catch (NoLinkedAccountException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1&error=no_linked_account';
        } catch (LinkedAccountExistsException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1&error=account_already_linked';
        } catch (OutOfBoundsException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1';

            if ($e->getCode() === SocialLoginService::EXCEPTION_ACCOUNT_NOT_FOUND) {
                $redirect .= '&error=account_not_found';
            }
        }

        $response = new Response();
        $response->setStatusCode(301);
        $response->headers->set('Location', $redirect);

        return $response;
    }
559881
public function createAction(Request $request)
    {
        $newTag = new Tag();
        $newTagForm = $this->createForm(new TagType(),$newTag);

        $newTagForm->handleRequest($request);

        if($newTagForm->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($newTag);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('tag'));
    }
1358710
public function registerAction(Request $request): Response
    {
        $content = $request->getContent();
        $content = \json_decode($content, true);

        /** @var TenantInterface $tenant */
        /** @noinspection PhpUndefinedMethodInspection */
        $tenant = $this->em->getRepository($this->tenantClass)->findOneByClientKey($content['clientKey']);
        if ($tenant !== null) {
            try {
                $authorizationHeaderArray = \explode(' ', $request->headers->get('authorization'));
                if (\count($authorizationHeaderArray) <= 1) {
                    throw new \InvalidArgumentException('Bad authorization header');
                }

                $jwt = $authorizationHeaderArray[1];
                JWT::decode($jwt, $tenant->getSharedSecret(), ['HS256']);
            } catch (\Throwable $e) {
                $this->logger->error($e->getMessage(), ['exception' => $e]);

                return new Response('Unauthorized', 401);
            }
        } else {
            $tenantClass = $this->tenantClass;
            $tenant = new $tenantClass();
        }

        $tenant
            ->setAddonKey($content['key'])
            ->setClientKey($content['clientKey'])
            ->setPublicKey($content['publicKey'])
            ->setSharedSecret($content['sharedSecret'])
            ->setServerVersion($content['serverVersion'])
            ->setPluginsVersion($content['pluginsVersion'])
            ->setBaseUrl($content['baseUrl'])
            ->setProductType($content['productType'])
            ->setDescription($content['description'])
            ->setEventType($content['eventType'])
        ;

        if (\array_key_exists('oauthClientId', $content)) {
            $tenant->setOauthClientId($content['oauthClientId']);
        }

        $this->em->persist($tenant);
        $this->em->flush();

        return new Response('OK', 200);
    }
134841
public function execute( Request $request )
    {
        $controllerClass = $request->attributes->get('_controller');
        if( !($this->isJwtRequired($controllerClass))) {
            return null;
        }

        if( !$this->authoriser->isAuthorised( $request ) ) {
            return new JsonResponse( ['error' => 'Invalid token'], 403 );
        }
        return null;
    }
101550
public function createAuthenticatedToken(UserInterface $user, $providerKey)
    {
        $preAuthToken = $this->preAuthenticationTokenStorage->getToken();

        if (null === $preAuthToken) {
            throw new \RuntimeException('Unable to return an authenticated token since there is no pre authentication token.');
        }

        $authToken = new JWTUserToken($user->getRoles(), $user, $preAuthToken->getCredentials(), $providerKey);

        if ($this->dispatcher instanceof ContractsEventDispatcherInterface) {
            $this->dispatcher->dispatch(new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken), Events::JWT_AUTHENTICATED);
        } else {
            $this->dispatcher->dispatch(Events::JWT_AUTHENTICATED, new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken));
        }

        $this->preAuthenticationTokenStorage->setToken(null);

        return $authToken;
    }
573742
public function postAction(Request $request)
    {
        try {
            return $this->createJsonResponse($this->get('oauth.server')->grant(
                $this->getRequestData($request, 'snakelize')
            ));
        } catch (InvalidGrantException $e) {
            return new JsonResponse('Unavailable to create access token : bad credentials.', 401);
        } catch (\InvalidArgumentException $e) {
            return new JsonResponse('Invalid or missing fields for grant type.', 400);
        }
    }