Api key using java

API Key Authentication in a REST API with JAX-RS

The designer of a new REST APIs soon comes across the problem of authentication. He has a number of standardized or custom methods to choose from. In this blog entry I want to outline design and implementation criteria for API Key authentication.

Why API Keys?

Authentication methods for HTTP requests include but are not limited to standardized methods

The first 4 methods are designed for human authentication, typically in a browser. On the other hand, REST APIs are often designed for machine to machine communication. The differences between human and machine authentication will become clearer with a more detailed explanation of API Key requirements.

API Key Requirements

An API Key has these properties:

  • A token, in the form of a relatively long random string (e.g. 32 characters)
  • An identifier, for storage and unique identification
  • Transmitted with the request (Warning: this requires SSL for productive usage)
  • Known to the client
  • Can be validated by the server
  • Unique to a device or software
  • Bound to a user if necessary

A client device will store the token. In a way this is like a password, but there is no need for restricting this to human memory capabilities. The token is transmitted with every request so the request can always be authenticated.

Читайте также:  Write int to outputstream java

Because the API key has the same sensitivity as a password, it also should never be stored in the clear in a database or password file. Instead, a hash should be stored with similar (but not quite the same) properties as a password hash. This also serves as identifier. I’ll explain more on that later.

Users and API Keys

In the end every action is executed under some user with some rights. The database entry for the API Key can link to the user under whose name the machine will act.

Requests should be logged, but as with passwords, the token must not end up in a log file. Use the identifier instead. When a client device goes rogue and floods a server with requests or misbehaves otherwise, a single API Key can be revoked without affecting other devices, even other devices of the same user.

Submitting the token with JAX-RS

In this JAX-RS based example the API Key is sent as a custom HTTP Header. By convention custom HTTP headers start with ‘X’.

HTTP sends headers in the cleartext, so this approach requires encryption in the transport layer. For any productive use of this approach HTTPS is required.

The server receives the API Key with the annotation @HeaderParam at the desired parameter.

@Path("/my/resource") public class AssignLeafletRestService    @POST @Produces( MediaType.APPLICATION_JSON >)  public String create(@HeaderParam("X-My-API-Key-Token") String token, . )   // look up API Key for token  // log API Key usage  // proceed with request  > 

The client adds the header when it sends the request.

Entity entity = createEntity(); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(getBaseURI()); Response response = target.path("my").path("resource").request().accept(MediaType.APPLICATION_JSON) .header("X-My-API-Key-Token", "012345678901234567890123456789ab").post(entity); 

From the request/response side this is all there is in regards to the API key. Care must be taken on the server side to securely manage the token.

Creation, Storage and Hashing

The token can be any string, but it obviously must meet some requirements. The main power of an API key over an human chosen password is that it can be truly random, and of a considerable length, e.g. 32 characters. Have a look into UUID generation to receive such strings at low cost.

The token should not be stored in cleartext anywhere on the server. Instead its storage should meet password storage standards. Passwords are hashed with a hashing algorithm that was designed for this purpose such as BCrypt. BCrypt is designed as an expensive task and will stand up some time to brute force attacks.

BCrypt has two inputs, the password and the salt. Depending on the implementation of BCrypt the password is truncated at 56 or 72 bit. A good random salt must be used. The API key should carry both values. A token with 32 random characters can be considered as

This provides a deterministic hash value that is considered state of the art for password hashing.

For identification purposes this hash must also be unique, so a collision detection should be done when generating a token.

tldr; With HTTPS, long random strings and bcrypted hashing, secure machine to machine authentication can be implemented at relatively low cost.

Источник

Аутентификация с помощью ключа API в Java

bestprogrammer.ru

Зачем нам нужен API в Java

Программирование и разработка

Обычно в веб-приложении мы входим в систему, используя имя пользователя (идентификатор электронной почты/имя для входа) с паролем. Безопасно мы можем сделать то же самое, используя APIKey. Давайте посмотрим, что такое APIKey. Ключ API — это уникальный идентификатор, который аутентифицирует запросы, и если есть несколько пользователей, их имя пользователя или идентификатор электронной почты могут быть объединены с текущей датой и безопасным кодом, предназначенным только для этого проекта, с помощью механизма md5, мы можем создать APIKey и можем поддерживать в базе данных. Давайте посмотрим, как создать APIKey и вставить его в базу данных.

Пример проекта

Структура таблицы MySQL:

-- Sample table named users is available CREATE TABLE `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `loginId` varchar(20) DEFAULT NULL, apiKey varchar(255) DEFAULT NULL, PRIMARY KEY (`userId`) ); -- insert 2 records insert into users (loginId) values ('geeka@gmail.com'); insert into users (loginId) values ('geekb@gmail.com');

Теперь давайте посмотрим пример программы Java для создания ключа API

Теперь давайте посмотрим пример программы Java для создания ключа API и обновления в таблице «пользователи» (MySQL).

Источник

Java api key for programming tips code example

Solution: If you look at Youtube Java sample code on Github, you can see that the example is using api key : This post and this post are relevant to your question about Oauth vs API key The API key is a unique identifier that authenticates requests and if several users are there, their username or email id can be joined with the current date and a secure code meant only for that project by using the md5 mechanism, we can create APIKey and can maintain in a database.

How to pass an Api Key in a http request with java?

What you have looks good. To simulate the -k flag, which turns off hostname verification, you’ll need to make another call:

connection.setHostnameVerifier(new HostnameVerifier() < boolean verify(String hostname, SSLSession session) < return true; >>); 

Without that, you’ll might see certificate errors.

How to pass an Api Key in a http request with java?, i been trying to access an api with the request header example below using java curl -X GET -k —header "x-apikey: accesskey=4def6bc216f14c1ab86dfba8738ff4a5 Code sampleconnection.setHostnameVerifier(new HostnameVerifier() >);Feedback

Authentication with API Key in Java

Usually, in a web application, we will log in by using a username(email id/login name) with a password. Securely we can do the same by using an APIKey as well. Let us see what is an APIKey. The API key is a unique identifier that authenticates requests and if several users are there, their username or email id can be joined with the current date and a secure code meant only for that project by using the md5 mechanism, we can create APIKey and can maintain in a database. Let us see the ways of creating APIKey and inserting it into the database.

Example Project

MySQL table structure:

-- Sample table named users is available CREATE TABLE `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `loginId` varchar(20) DEFAULT NULL, apiKey varchar(255) DEFAULT NULL, PRIMARY KEY (`userId`) ); -- insert 2 records insert into users (loginId) values ('geeka@gmail.com'); insert into users (loginId) values ('geekb@gmail.com');

Now let us see the sample java program for the creation of an API key and updating into the ‘users’ (MySQL) table

Источник

VDenis / store_api_keys.md

Put xml file «api_keys.xml» in the directory «res/value/».

xml version="1.0" encoding="utf-8"?> resources> string name="THE_MOVIE_DB_API_TOKEN">XXXXXstring> resources>

use api keys in java code

getString(R.string.THE_MOVIE_DB_API_TOKEN);

2.1 Store api keys with help of gradle and the gradle.properties file (Java)

Add the following line to [USER_HOME]/.gradle/gradle.properties

For Windows OS, example for Denis user:

MyTheMovieDBApiToken="XXXXX"

Add the following code to the build.gradle file

apply plugin: 'com.android.application' android < ... defaultConfig < ... > buildTypes < release < ... > buildTypes.each < it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', MyTheMovieDBApiToken > > >

use api keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN)

2.2 Store api keys with help of gradle and the gradle.properties file (Java + XML)

buildTypes < //. buildTypes.each < it.buildConfigField 'String', 'APP_KEY_1', AppKey it.resValue 'string', 'APP_KEY_2', AppKey > >
Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2)); BuildConfig.APP_KEY_1
data android:scheme="@string/APP_KEY_2" />

3. Store api keys with help of gradle and the system path variable

Add new system PATH variable THE_MOVIE_DB_API_TOKEN=»XXXXX»:

  • open system
  • advanced system settings
  • environment variables
  • add new variables to the user variables

Add the following code to the build.gradle file

apply plugin: 'com.android.application' android < ... defaultConfig < ... > buildTypes < release < ... > buildTypes.each < it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', "$System.env.THE_MOVIE_DB_API_TOKEN" > > >

use api keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN)

Источник

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