public function login() { $response = $this->app->response(); $response->header("Content-Type", "application/json"); $username = $this->app->request()->params('username'); $password = $this->app->request()->params('password'); if (!isset($username)) { return Auth::deny_access("Username is null"); } if (!isset($password)) { return Auth::deny_access("Password is null"); } $username = htmlentities(trim($username)); $password = htmlentities(trim($password)); $database_user = User::where('username', $username); $database_user = json_decode($database_user, true); if (empty($database_user)) { return ['status' => 400, 'message' => 'username doesn\'t']; } $database_user = $database_user[0]; if ($database_user['password'] == md5($password)) { $key = $this->config->jwt_key(); $token = ["iss" => $this->config->jwt_issuer(), "iat" => $this->config->jwt_issuer_at(), "nbf" => $this->config->jwt_not_before(), "exp" => $this->config->jwt_expiration_time(), "data" => ["username" => $database_user['username']]]; $encode_jwt = JWT::encode($token, $key, 'HS512'); $responseArray = ["token" => $encode_jwt, "status" => 200]; $response->status(200); $response->body(json_encode($responseArray)); return $response; } else { return Auth::deny_access("Incorrect Authentication Details"); } }
public function registerAction() { $email = $this->post_data['email']; $password = $this->post_data['password']; if ($email == NULL || $password == NULL) { return $this->fail('Email and password not empty', Response::HTTP_BAD_REQUEST); } $user = User::where('email', '=', $email)->first(); if ($user) { return $this->fail('Email already exists ', Response::HTTP_BAD_REQUEST); } else { $user = new User(); $user->username = $this->post_data['username']; $user->password = md5($this->post_data['password']); $user->email = $this->post_data['email']; $user->status = 1; $user->save(); if ($user->password == md5($password) && $user->status == 1) { $secret = $this->app['config.app.secret']; $token = array('user_id' => $user->id); $encoded_token = JWT::encode($token, $secret, 'HS256'); return $this->json(['mess' => 'Thành công', 'user_id' => $user->id, 'token' => $encoded_token]); } else { return $this->fail('Database error', Response::HTTP_BAD_REQUEST); } } }
protected function buildToken(array $values = array(), $secretKey = 'ilios.jwt.key.secret') { $now = new DateTime(); $default = array('iss' => 'ilios', 'aud' => 'ilios', 'iat' => $now->format('U'), 'exp' => $now->modify('+1 year')->format('U'), 'user_id' => 42); $merged = array_merge($default, $values); return JWT::encode($merged, $secretKey); }
protected function login($user) { $key = Config::get('custom.JWTkey'); $token = array("sub" => $user->id, "iss" => "http://leo.app", "iat" => 1356999524, "name" => $user->name); $jwt = JWT::encode($token, $key); return $jwt; }
/** * @param stdClass $payload * @param null $expires - can be +1 day, or +1 week, etc * * @return String */ public function encode(stdClass $payload, $expires = null) : string { if (!empty($expires)) { $payload->exp = is_numeric($expires) ? time() + $expires : strtotime($expires); } return JWT::encode($payload, $this->key, 'HS256'); }
public function authenticate(Application $app, Request $request) { $username = $request->get('user'); $password = $request->get('pass'); if ($username && $password) { $sql = "SELECT * FROM user WHERE username = ? AND password = ?"; $user = $app['db']->fetchAssoc($sql, array($username, md5($password))); if ($user) { $tokenId = base64_encode(mcrypt_create_iv(32)); $issuedAt = time(); $notBefore = $issuedAt; //Adding 10 seconds $expire = $notBefore + 604800; // Adding 1 week $serverName = $app['serverName']; // Retrieve the server name from config file $id = 1; //TODO: da cambiare $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => ['userId' => $user['id'], 'userName' => $user['username']]]; // Get the secret key for signing the JWT from an environment variable $secretKey = base64_decode($app['secret']); $algorithm = $app['algorithm']; // Sign the JWT with the secret key $jwt = JWT::encode($data, $secretKey, $algorithm); return new JsonResponse(array('token' => $jwt), 200); } else { return new JsonResponse(array('message' => 'Failed to Authenticate'), 403); } } else { return new JsonResponse(array('message' => 'Failed to Authenticate'), 403); } }
/** * Generate JWT authorization header * @return string */ public function generateAuthHeader() { $time = time(); $iss = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'cli'; $signatureData = ['sub' => $this->config['public_key'], 'iat' => $time, 'exp' => $time + $this->config['leeway'], 'iss' => $iss, 'nbf' => $time - $this->config['leeway'], 'jti' => md5($this->config['public_key'] . $time)]; return JWT::encode($signatureData, $this->config['private_key']); }
private function get_profile_hmac($account) { $key = $this->apiSecret; $payload = array("account" => $account, "apiUniqueId" => $this->apiKey, "created" => date("DATE_W3C")); $jwt = JWT::encode($payload, $key); return $jwt; }
/** * Logs in a user with the given username and password POSTed. Though true * REST doesn't believe in sessions, it is often desirable for an AJAX server. * * @url POST /auth */ public function auth() { $username = $_POST['username']; $password = $_POST['password']; //ToDo: handle login and generate authtoken return it return JWT::encode('abc', 'my_key'); }
/** * @Route("/login") * @Method({"PUT"}) */ public function login(Request $request) { $email = $request->request->get('email'); $password = $request->request->get('password'); $customer = $this->getCustomerManager()->getRepo()->findOneByEmail($email); if (!$customer) { return $this->fail(); } $em = $this->getDoctrine()->getManager(); if ($customer->verifyPassword($password)) { $expire = new \DateTime('now'); $expire->modify('+20 minute'); $token = new Token($expire); if ($customer->getToken()) { $em->remove($customer->getToken()); } $customer->setToken($token); $em->persist($token); $em->persist($customer); $em->flush(); $key = $this->container->getParameter('jwt_key'); $payload = array('type' => 'customer', 'user_id' => $customer->getId(), 'token_id' => $token->getId(), 'expires' => $token->getExpires()); return $this->respondJson(array('jwt' => JWT::encode($payload, $key))); } return $this->fail(); }
public function createAutologinJwt(TokenSet $tokenSet, array $data = []) { if (empty($tokenSet->id_token)) { throw new InvalidArgumentException('Missing id_token'); } $data = array_merge(['remember_me' => false, 'access_token' => $tokenSet->access_token, 'id_token' => $tokenSet->id_token], $data); return JWT::encode($data, $this->config->client_secret, 'HS256'); }
public function generateToken($data = null) { $issuedAt = time(); // $notBefore = $issuedAt + 10; $expire = $issuedAt + 3600; $data = array_merge(['iat' => $issuedAt, 'exp' => $expire], $data); return JWT::encode($data, $this->key); }
protected function generateJwt($data = [], $options = []) { $options = array_merge(['alg' => 'RS256', 'key' => '4cee9dc4d2aaf2eb997113d6b76dc6fe'], $options); $now = time(); $data = array_merge(['iss' => 'http://sso.7pass.dev', 'aud' => ['543d077b656332528d000000', $this->configDefault['client_id'], '564f035a0640fd25df00000c', '565454f10640fd1cb500043a', '56b4824f0640fd4d460000b2'], 'exp' => $now + 10, 'iat' => $now, 'auth_time' => $now, 'nonce' => 'z8jw9aVPJ9vmz01d', 'azp' => $this->configDefault['client_id'], 'sub' => '56d6c9a07eddd9781d507ea5', 'gender' => 'male', 'birthdate' => '1964-07-03', 'first_name' => 'Test', 'last_name' => 'User', 'birthdate_verified' => false, 'email' => '*****@*****.**', 'email_verified' => false, 'at_hash' => 'k4taUhrRarXC78p5qFyUfg'], $data); return JWT::encode($data, file_get_contents(__DIR__ . '/fixtures/certs/jwk.pem'), $options['alg'], $options['key']); }
public function encode($data, $key, $duration) { $data = array_merge($this->getMandatoryClaims($duration), $data); $this->data = (object) $data; $this->encoded = JWT::encode($data, $key); $this->status = self::VALID_TOKEN; }
public function encode($data = array()) { // References: // - http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html // - http://websec.io/2014/08/04/Securing-Requests-with-JWT.html // // Registered Claim Names (all optional): // - iss = Issuer // - sub = Subject // - aud = Audience // - exp = Expiration Time // - nbf = Not Before // - iat = Issued At // - jti = JWT ID $curr_time = time(); $token = array("iss" => $this->mIssuer, "iat" => $curr_time, "jti" => random_string('unique')); // add expiry when necessary if (!empty($this->mExpiry)) { $token['exp'] = $curr_time + $this->mExpiry; } // append data to store with token if (!empty($data)) { $token = array_merge($token, $data); } // encode and return string return JWT::encode($token, $this->mSecretKey); }
function login_post() { $email = ''; $password = ''; try { $entityBody = file_get_contents('php://input'); $arrayObject = (array) json_decode($entityBody); if (!isset($arrayObject['email']) || !isset($arrayObject['password'])) { throw new Exception(); } $email = $arrayObject['email']; $password = $arrayObject['password']; if ($email == '') { throw new Exception(); } if ($password == '') { throw new Exception(); } } catch (Exception $e) { $this->response(array('message' => 'Invalid request data'), self::HTTP_BAD_REQUEST); } $this->load->model('Model_users'); $user = $this->Model_users->get_by(array('email' => $email, 'password' => sha1($password))); if ($user == NULL) { $this->response(array('message' => 'User not found'), self::HTTP_BAD_REQUEST); } $unixTime = new DateTime(); $unixTime = $unixTime->getTimestamp(); $token = array("uid" => $user->id, "name" => $user->name, "email" => $user->email, "iat" => $unixTime); $jwt = JWT::encode($token, "JWT_KEY"); $this->response(array('id' => (int) $user->id, 'name' => $user->name, 'token' => $jwt), self::HTTP_OK); }
public static function generate_jwt($user) { $issuedAt = time(); $tokenId = base64_encode(Random::key(32)); $serverName = Config::get('serverName'); /* * Create the token as an array */ $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'exp' => $issuedAt + 1800, 'data' => ['userId' => $user->id, 'userName' => $user->username]]; /* * Extract the key, which is coming from the config file. * * Generated with base64_encode(openssl_random_pseudo_bytes(64)); */ $secretKey = base64_decode(Config::get('jwt')['key']); /* * Extract the algorithm from the config file too */ $algorithm = Config::get('jwt')['algorithm']; /* * Encode the array to a JWT string. * Second parameter is the key to encode the token. * * The output string can be validated at http://jwt.io/ */ $jwt = JWT::encode($data, $secretKey, $algorithm); return $jwt; }
public function Login($user, $pass) { $output = array(); $this->db->join('user', 'superuser.ID_SU = user.ID_USU', 'left'); $this->db->where('SUname', $user); $this->db->where('pswd', md5($pass)); $query = $this->db->get('superuser'); if ($query->num_rows() == 0) { return false; } $output = $query->result(); $tokenId = base64_encode(mcrypt_create_iv(32)); $issuedAt = time(); $notBefore = $issuedAt; // Is valid right away $expire = $notBefore + 60 * 60 * 24 * 1; // Token expires in 1 week $serverName = 'myserver'; // Retrieve the server name from config file /* * Create the token as an array */ $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => ['userId' => $output[0]->ID_SU, 'userName' => $output[0]->SUname]]; $secretKey = base64_decode('lamevaclausupersecreta'); $jwt = JWT::encode($data, $secretKey, 'HS512'); $unencodedArray = ['token' => $jwt]; return $unencodedArray; }
public function getJwt() { $return = []; $key = "352352345623463246trswrgsdfgsdfgsdfgsert"; $token = array("iss" => "http://example.org", "aud" => "http://example.com", "iat" => time(), "nbf" => time() - 4123123); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $jwt = JWT::encode($token, $key); $return[] = $jwt; $decoded = JWT::decode($jwt, $key, array('HS256')); $return[] = $decoded; /* NOTE: This will now be an object instead of an associative array. To get an associative array, you will need to cast it as such: */ $decoded_array = (array) $decoded; $return[] = $decoded_array; /** * You can add a leeway to account for when there is a clock skew times between * the signing and verifying servers. It is recommended that this leeway should * not be bigger than a few minutes. * * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef */ JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); $return[] = $decoded; return $return; }
private function getToken($userID, $userName, $userRole) { $tokenId = base64_encode(mcrypt_create_iv(32)); $issuedAt = time(); $notBefore = $issuedAt + 10; $expire = $notBefore + 90000; $serverName = $_SERVER['SERVER_NAME']; /* * Create the token as an array */ $payload = ['userID' => $userID, 'userName' => $userName, 'userRole' => $userRole]; $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'user' => $payload]; // Store key in local file, not in php $privateKey = $this->utils->readFile('private/apikey'); $secretKey = base64_decode($privateKey); /* * Encode the array to a JWT string. * Second parameter is the key to encode the token. * * The output string can be validated at http://jwt.io/ */ $jwt = JWT::encode($data, $secretKey, 'HS512'); $unencodedArray = ['data' => $payload, 'token' => $jwt]; echo json_encode($unencodedArray); }
/** * @inheritdoc */ public function encode(User $user) { $issuedAt = time(); $token = [self::CLAIM_ISSUED_AT => $issuedAt, self::CLAIM_EXPIRATION_TIME => $issuedAt + self::EXPIRATION_PERIOD_IN_SECONDS, self::CLAIM_USER_ID => $user->getAuthIdentifier()]; $jwt = JWT::encode($token, $this->getSigningKey(), self::SIGNING_ALGORITHM); return $jwt; }
/** * authorizationEncode Generate token using $userID * * @param $userID * * @return string */ public function authorizationEncode($userID) { if (!is_null($userID)) { $token = array("iss" => $this->getIssuedBy(), "aud" => $this->getAuthUrl(), "user" => $userID, "exp" => time() + 3600000); } return JWT::encode($token, $this->getKey()); }
public function createToken(Request $request, $exp, $user) { $rand_val = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6); $payload = ['iss' => $request->getClientIp(), 'sub' => '', 'aud' => 'http://sheaker.com', 'exp' => $exp, 'nbf' => time(), 'iat' => time(), 'jti' => hash('sha256', time() . $rand_val), 'user' => $user]; $token = JWT::encode($payload, $this->secretKey); return $token; }
protected function createToken($request) { $secret_key = getenv('SECRET_KEY'); $token = array('iss' => getenv('AUTH_ISS'), 'aud' => $request->getUri()->getHost(), 'iat' => time(), 'nbf' => time(), 'exp' => time() + 3600); $jwt = JWT::encode($token, $secret_key); return $jwt; }
function createToken($user) { $key = "example_key"; $token = array("iss" => "http://crossfitsiilinjarvi.fi", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000); $jwt = JWT::encode($token, $key); $decoded = JWT::decode($jwt, $key, array('HS256')); var_dump($decoded); }
/** * Generate a json web token * for the current user * * @return string */ public function getToken() { $current_user = $this->user_manager->getCurrentUser(); $data = array('user_id' => intval($current_user->getId()), 'user_rights' => $this->ugroup_literalizer->getUserGroupsForUserWithArobase($current_user)); $token = array('exp' => $this->getExpireDate(), 'data' => $data); $encoded = JWT::encode($token, $this->private_key, 'HS512'); return $encoded; }
/** * Generate token * * @param array $data * @param null|string $sub Subject * @return string */ public function generateToken($data = [], $sub = null) { if (!is_null($sub)) { $data['sub'] = $sub; } $data['exp'] = time() + $this->tokenLifetime; return JWT::encode($data, $this->jwtSecret, $this->jwtAlgo); }
public function token() { $user = $this->Auth->identify(); if (!$user) { throw new UnauthorizedException('Invalid username or password'); } $this->set(['success' => true, 'data' => ['token' => JWT::encode(['sub' => $user['id'], 'exp' => time() + 604800, 'role' => $user['role']], Security::salt())], '_serialize' => ['success', 'data']]); }
/** * Handle an authentication attempt. * * @return Response */ public function authenticate(Request $request) { if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { return response()->json(["token" => JWT::encode(["sub" => Auth::user()->id, "email" => $request->input('email'), "pass" => $request->input('password')], Config::get('services.jwt.secret'))]); } else { return response()->json(["message" => "Identifiants invalides"], 401); } }
/** * Creates the JWT token * * @return string */ public function createToken() { $domain = $this->config->get('app.domain'); $data = ['iss' => $domain, 'aud' => $domain, 'iat' => time(), 'exp' => time() + $this->expiration]; $token = JWT::encode($data, $this->config->get('app.app_key')); $this->createAuth(['token' => $token, 'expires_at' => date('Y-m-d h:i:s', $data['exp'])]); return $token; }