Generating api key php

How can I generate strong unique API keys with PHP?

When you verify the API key, use only the first 32 characters to select the record from the database and then use hash_equals() to compare the API key as given by the user against what value you have stored. This helps protect against timing attacks. ParagonIE has an excellent write-up on this., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Can anyone suggest the best solution for this? I don’t want to use rand() function to generate random characters. Is there an alternative solution? ,To keep this answer from dragging on, I’ll just put some suggestions for handling Base64 without their supporting arguments. Pick a $length greater than 32 that is divisible by both 3 and 2. I like 42, so we’ll use that for $length. Base64 encodings are of length 4 * ceil($length / 3), so our $key will be 56 characters long. You can use the first 28 characters for selection from your storage, leaving another 28 characters on the end that are protected from leaking by timing attacks with hash_equals.

Читайте также:  Название документа

Putting this all together, you get this:

$key = bin2hex(random_bytes(32)); // 64 characters long 

For an example of the checking logic:

$token = $request->bearerToken(); // Retrieve however works best for your situation, // but it's critical that only the first 32 characters are used here. $users = app('db')->table('users')->where('api_key', 'LIKE', substr($token, 0, 32) . '%')->get(); // $users should only have one record in it, // but there is an extremely low chance that // another record will share a prefix with it. foreach ($users as $user) < // Performs a constant-time comparison of strings, // so you don't leak information about the token. if (hash_equals($user->api_token, $token)) < return $user; >> return null; 

Answer by Annabelle Stafford

function generateRandomString($length = 25) < $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) < $randomString .= $characters[rand(0, $charactersLength - 1)]; >return $randomString; > //usage $myRandomString = generateRandomString(5);

Answer by Roberto Bennett

i am using this currently to generate a unique license try to edit it to your needs,IDs are so unique that if everyone in the world generated 600,000,000 GUIDs there is a 50% chance that ONE key will be duplicated. ,I have created a restful API for a hosted service. To restrict indiscriminate access to the API, each client must submit an API key to be authenticated. I need a nice PHP class for this if any.,The GUID Generator class creates a globally unique identifier that is ideal for API keys. GUIDs, also known ad UUIDs (Universally Unique IDs) are used in enterprise applications to provide a virtually guaranteed unique identifier for your users, as database keys, component identifiers, or just about anywhere else a unique identifier is required.

Читайте также:  System identification toolbox python

$subs = array($Sub3,$sub4,$Block1,$Block3); $rand = array_rand($subs,2); $Block11 = $subs[$rand[0]]; $Block12 = $subs[$rand[1]];

Answer by Silas Thomas

Let’s get started, and I’ll show you how to build API Keys the right way.,If you provide an API for your clients to consume, it’s essential for you to build it in the right way.,API keys, when built right, are still a great way to communicate with another server. As we reviewed in this article, following certain practices offers benefits to both API consumers and API providers. Hope this helps you.,We all know how valuable APIs are. They’re the gateway to exploring other services, integrating with them, and building great solutions faster.

API Key Generation

Since the API key itself is an identity by which to identify the application or the user, it needs to be unique, random and non-guessable. API keys that are generated must also use Alphanumeric and special characters. An example of such an API key is zaCELgL.0imfnc8mVLWwsAawjYr4Rx-Af50DDqtlx .

zaCELgL.0imfnc8mVLWwsAawjYr4Rx-Af50DDqtlx

Answer by Palmer Boyer

Login to Admin CP and go to REST API > API Information.,Copy your REST API key and secret key information.,Edit the PHP code snippet template below by following these instructions:,Replace the values of the $apiKey and $secretKey variables with the REST API and secret key information you have obtained.

Replace the values of the $apiKey and $secretKey variables with the REST API and secret key information you have obtained.

Replace the values of the $apiKey and $secretKey variables with the REST API and secret key information you have obtained.

Answer by Keilani Barron

IPv4 network allowed to use the generated key. This is used for more protection against API key leaking and reuse.,This can be useful when you want impose a rate limit on specific users. By default, we set rate limits based on the IP address. This can become an issue when several users search from the same IP address. To avoid this, you can set a unique userToken for each user when generating their API key. This lets you restrict each user to a maximum number of API calls per hour, even if they share their IP with another user.,Generate a secured API key without any call to our servers.,You shouldn’t generate secured API keys from your front end. If you do, users can modify the code and remove restrictions, which can expose hidden, sensitive data.

SearchClient::generateSecuredApiKey(string apiKey, [ 'filters' => string, 'validUntil' => integer, 'restrictIndices' => array, 'restrictSources' => string, 'userToken' => string // + any searchParameter ]) 

Answer by Armani Magana

No Authentication Required, No Authentication Required , Basic Authentication using an API Key, Basic Authentication using an API Key

Authorization: 2524a832-c1c6-4894-9125-41a9ea84e013

Источник

Generating api keys for REST api

Question: Am using phil sturgeon codeigniter REST library for my REST API, i have set up the api to use api keys in the config file and also created a table for storing the keys on my database. I am not nearly familiar with it at all, so please excuse my pathetic stupid question if you find it to be, I’m using Phil Sturgeon’s REST API server, Curl Library, and REST API client here’s my code: in my controller application/controllers/make_key — no response at all where apifolder/key is the location of my key.php (from Phil Sturgeon’s default example): and note that I’ve also tried this via address bar: https://www.myapplication.com/apifolder/key/X-API-KEY/FOO — returns ()

Generating api keys for REST api

Am using phil sturgeon codeigniter REST library for my REST API, i have set up the api to use api keys in the config file and also created a table for storing the keys on my database. I want to be able to generate a new API key for a user when the log in, to give them access to the api, and delete the key when they sign out. Currently when i call the key controller using the PUT method to generate keys i get an error saying «the API Key is invalid». What am doing wrong?, Please help

It sounds like your PUT method requires the person to already have an API key, try moving that method to another controller that doesn’t extend the REST_Controller.

Best practices for building secure API Keys, API Key Generation. Since the API key itself is an identity by which to identify the application or the user, it needs to be unique, random and

Best And Secure Way To Create REST API In PHP

Learn how to create you can easily create secure rest api in php.Get project files and resource
Duration: 35:15

How to Generate Unique and Secure API keys with PHP

The string used for an API key or token should be unique and secure. PHP random_bytes Duration: 14:00

Automatic PHP REST API Generator from MySQL Database

How to generate an API key for Mysql PHP webservice?

I need to generate an API key for my webservice. Can anyone suggest idea for that? Users who use my webservice should have an API key.

You might consider implementing OAuth2’s client_credentials.

I am suggesting OAuth2 so that at least you are not home cooking yet another solution.

Try looking at the posts and urls below for reference.

If all you care about is the exact mechanics involved in generating the key, consult this post that is doing in C# but the concept is language agnostic.

How to Create RESTful API in PHP, Welcome to this course on Creating a simple REST API in PHP From Scratch. In this video Duration: 1:43:36

How can I generate an API Key in My own Controller in Codeigniter

Just want to mention that I am really a newbie in API development (concepts, structure, best practices) I am not nearly familiar with it at all, so please excuse my pathetic stupid question if you find it to be, I’m using Phil Sturgeon’s REST API server, Curl Library, and REST API client here’s my code:

in my controller application/controllers/make_key

function index()< $this->load->library('rest'); $this->load->library('curl'); $this->rest->put('https://www.myapplication.com/apifolder/key/X-API-KEY/FOO'); > 

where apifolder/key is the location of my key.php (from Phil Sturgeon’s default example):

and note that I’ve also tried this via address bar:

and tried quite a lot more queries but none seem to be working, my only question is.

How can make this key.php work? my apologies for such a simple minded question thank you in advance

see my self-accepted answer on my own qeuestion. Phils documentation does not provide this information. I had to dig into the library myself.

i ended up finding out the 403 forbidden was because i was not providing an api key to generate keys..
Kind of abiguous as Phil’s documentation doesn’t state that an existing api key is required before you can generate keys.. I simply created a bogus key in the table in the db and referenced that when calling /key/index?X-API-KEY=boguskey

codeigniter REST API Library Ajax PUT throwing 403 Forbidden

Implementing simple authentication for PHP REST API, 4 Answers 4 · When an API account is provisioned generate 2 random values: a Token and a Secret. · When a client makes a request they provide: The

How to generate an API key for a web-service call in PHP

I have a java program to generate an API key that will be later used to make a web-service call using curl_exec($curl). I’m running this java program manually everytime i need a new APIKEY. How do I convert this java program to PHP so I can first generate the API key using PHP code and then use the generated APIKEY in the actual request. I was trying to use curl_exec() to generate the API key but do not have any idea how to do the DataOutputStream or BufferedReader in PHP. Any tips or suggestions? Any other alternatives that I can use to generate the API key programmatically in PHP?

The java program is below:

import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MyRestApi < public void Apikey() < try < URL url = new URL( "http://c0016.test.cloud.hpe.com:7001/maximo/oslc/apitoken/create?_lid=testuser1&_lpwd=Test@123"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); String json = ""; connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); DataOutputStream d = new DataOutputStream(connection.getOutputStream()); d.writeBytes(json); d.flush(); d.close(); System.out.println(connection.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String output; while ((output = br.readLine()) != null) System.out.println(output); > catch (MalformedURLException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> public static void main(String[] args) < MyRestApi restapi = new MyRestApi(); restapi.Apikey(); >> 

Thanks for replying back. I was able to generate the API key by sending a CURL request as below (If someone needs to refer to the solution):

$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://c0016.test.cloud.hpe.com:7001/maximo/oslc/apitoken/create?_lid=testuser1&_lpwd=Test@123", CURLOPT_ENCODING => "gzip,deflate", CURLOPT_TIMEOUT => 20, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array('Accept: application/json' , 'Content-Type: application/json'), CURLOPT_POSTFIELDS => "", CURLOPT_RETURNTRANSFER => true, )); $response = curl_exec($curl); $results = json_decode($response, true); curl_close($curl); 

Generating api keys for REST api, I want to be able to generate a new api key for a user when the log in, to give them access to the api, and delete the key when they sign

Источник

How to Generate Unique and Secure API keys with PHP

The string used for an API key or token should be unique and secure. PHP random_bytes() function generates pseudo-random bytes that are cryptographically secure. Use random_bytes() and bin2hex() function to generate unique and strong API keys in PHP.

The following code snippet helps you to create a random and secure string with PHP which is useful for API key/token.

$key = bin2hex(random_bytes(32));

The above code will output 64 characters long string.

d7a03fee5546592a37e22ff8f45bbbe45da4632dfed9a774e085d0e8b5d3fa73

Use hash_equals() function to compare key strings.

if(hash_equals($api_token, $key)) < 
echo
'Valid';
>else <
echo
'Invalid';
>

Источник

Оцените статью