Top-office11.ru

IT и мир ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java generate token

How to create a authentication token using Java

On my Java EE6, REST service, I want to use authentication tokens for login from mobile devices, User will send their username, password and server will send back a token, which will be used to authorize the user on their further requests for a given time.

Can I simply create a token myself like this?(I guess I do not need to encrypt this since I will use HTTPS.)

Or there is a more standart way to create my tokens? maybe it exists in one of API’s

6 Answers 6

The scheme you are proposing effectively allows a client unlimited access to your service. After an initial login, the UID and ‘userid’ will be made available to the client, which can be simply combined with an always valid timestamp.

If you need a service with ‘login’ and a session token, then why not just use an HttpSession?

For Java 8 and above the fastest and simplest solution would be:

Above code will generate random string in base64 encoding with 32 chars. In Base64 encoding every char encodes 6 bits of the data. So for 24 bytes from the above example you get the 32 chars. You can change the length of the output string by changing the number of random bytes. This solution is more secure than UUID (that uses only 16 random bytes) and generates string that safely could be used in HTTP urls.

To create a hard to guess token in Java use java.security.SecureRandom

Rather than including the user name in the token it would be better to cache a user:token map in memory or in a database.

There is a way to create tokens which is cannot compromised but can be used for authentication too.

Create a token which is combined:

base64(username + expiration + other values for client + 3des encoded(usename, expiration, source ip, browser identitifier, other values for client))

The client can use the token to authenticate the request, for example the usage of JSON Web Token (RFC 7515).

On server side the keys which is used for 3des encoding can be rotated with time, as the token. Every request contains token for authentication and every response contains the same token or a new one before the expiration.

In that case token contains user name so on request authentication only have to check the 3des encoded part is valid or not (same as the , the source of request ip is same. In this case if somebody stole the token the usability of token is more limited as a session id. You can compose other identifiers to token, like browser etc. Harder to fake request, because the attacker have to fake more things — which is unknown for him, because he doesn’t know what is on encoded part of token. (As a matter of fact there is no perfect security, only can make harder to crack)

The pros of this solution are:

  • Every piece is standard, but not the whole together and the attacker have to know the implementation details to be able to attack.
  • The client side can use parts of the token for displaying information from token while the token itself is secured because every unencrypted part is contained in encrypted part — so cannot be modified without the invalidation of token on the server side — so its easy to detect an attack.
  • There is no need of session replication / sticky sessions for clustering. The 3des keys enough to replicate between nodes — so it is suitable for stateless backend strategy.

Harder to implement on server side, because for this solution have to implement the token generation / validation algorithm on server side For that server filter is recommended,.

The clients have to implement the store of tokens — instead of cookie browser session store is recommended — easier to stole cookies.

  • Have to make sure that the 3des keys are secured enough — Java security is recommended to use to avoid the comprimise.
  • Аутентификация с использованием Spring Security и JWT-токенов

    Всем привет! Хабр жив! Данный пост вряд ли соберёт кучу просмотров и комментов, но, надеюсь, немного поможет здоровью хабра.

    Читать еще:  Как открыть проект java в eclipse

    В данной статье рассмотрим принцип аутентификации в веб-приложениях на платформе Spring с использованием относительно нового механизма аутентификации — JSON Web Token (JWT). Этот механизм уже обкатан и реализован для многих языков программирования.

    Использование токена позволяет серверу не заботиться о сохранении состояния между запросами (HTTP-сессии), уменьшить количество запросов к БД — необходимые для восстановления данные могут сохраняться в токене. Непосредственно о токене JWT: сервер смешивает полезную нагрузку в формате JSON (заголовок и тело) с секретным ключом и генерирует хэш, прикрепляя его в качестве сигнатуры к полезной нагрузке. Полезная нагрузка кодируется алгоритмом base64Url, поэтому, естественно, не следует передавать в токене секретные данные. Стандартом JWT шифрование полезной нагрузки не предусмотрено. Шифруйте отдельно сами, если хотите, а задача токена — только обеспечить аутентификацию.

    Предполагается, что читатель знаком с основами Spring Secutity. Про него можно прочитать здесь

    1). Генерация токена

    Для своего примера я взял одну из реализаций спецификации JWT. Токен генерируется следующим образом:

    В итоге мы получаем строку вида . . , которую и отправляем клиенту

    Теперь к Spring Security. Для реализации собственного механизма аутентификации нам необходимо реализовать свой фильтр и менеджер аутентификации.

    2). Реализация фильтра

    Фильтр — это объект класса, реализующего интерфейс javax.servlet.Filter, который перехватывает запросы на определённые URL и выполняет некоторые действия. Если имеется несколько фильтров, то они образуют цепочку фильтров — HTTP-запрос после приёма приложением проходит через эту цепочку. Каждый фильтр в цепочке может обработать запрос, пропустить его к следующим фильтрам в цепочке или не пропустить, сразу отправив ответ клиенту.

    Задача нашего фильтра — передать токен из запроса менеджеру аутентификации и, в случае успешной аутентификации, установить контекст безопасности приложения.

    Мы унаследовались от абстрактного класса org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter, который специально предназначен для аутентификации. При совпадении URL запроса с паттерном «/rest/**» автоматом произойдёт вызов функции attemptAuthentication().
    Также в конструкторе мы установили два хэндлэра — AuthenticationSuccessHandler и AuthenticationFailureHandler. Если attemptAuthentication вернет объект Authentication, то сработает первый хэндлер, второй хэндлэр сработает при выбросе методом attemptAuthentication исключения AuthenticationException.
    Как мы видим, при успешной аутентификации мы устанавливаем контекст безопасности приложения посредством SecurityContextHolder.getContext().setAuthentication(authentication). Установленный таким образом контекст является переменной ThreadLocal, т.е. доступен, пока жив поток работы с клиентом. После установки контекста мы направляем запрос пользователя к сервлету с первоначально запрашиваемым URL.

    3). Менеджер аутентификации.

    Менеджер аутентификации — это объект класса, реализующего интерфейс org.springframework.security.authentication.AuthenticationManager с единственным методом authenticate(). Данному методу нужно передать частично заполненный объект, реализующий интерфейс org.springframework.security.core.Authentication (контекстом безопасности приложения).
    Задача менеджера аутентификации — в случае успешной аутентификации заполнить полностью объект Authentication и вернуть его. При заполнении нужно установить пользователя (principal), его права (authorities), выполнить setAuthenticated(true). В случае неудачи менеджер аутентификации должен выбросить исключение AuthenticationException.

    Приведём пример реализации интерфейса org.springframework.security.core.Authentication:

    Приведём реализацию менеджера аутентификации:

    4). Как всё это собрать вместе

    Во-первых, нужно установить фильтр. Сделать это можно 2-мя способами

    Первый способ — определить фильтр в файле web.xml нашего приложения

    При таком способе в конструкторе фильтра нужно сразу задать менеджер аутентификации, так как экземпляр фильтра не будет доступен в контексте приложения Spring. Если необходимо иметь фильтр или менеджер аутентификации в качестве бинов Spring, нужно воспользоваться вторым способом.

    Второй способ — установка фильтра в конфигурации Spring Security.

    Для примера покажем конфигурацию с использованием Java Config

    В строке
    .addFilterAfter(restTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
    мы добавили наш фильтр в цепочку фильтров после стандартного фильтра UsernamePasswordAuthenticationFilter.

    На этом основная настройка механизма аутентификации в Spring Security с использованием JSON Web Token завершена.

    Java generate token

    This repository has been archived and is no longer maintained.

    Firebase Token Generator — Java

    WARNING: This token generator is compatible with versions 1.x.x and 2.x.x of the Firebase SDK. If you are using the 3.x.x SDK, please refer to the documentation here.

    Firebase Custom Login gives you complete control over user authentication by allowing you to authenticate users with secure JSON Web Tokens (JWTs). The auth payload stored in those tokens is available for use in your Firebase security rules. This is a token generator library for Java which allows you to easily create those JWTs.

    The easiest way to install the Firebase Java token generator is via Maven. Add this dependency to your project:

    Otherwise, you can download the source and directly use it in your project. The token generator has two run time dependencies:

    Читать еще:  Java math подключить

    Unit tests depend on jUnit 4.11.

    A Note About Security

    IMPORTANT: Because token generation requires your Firebase Secret, you should only generate tokens on trusted servers. Never embed your Firebase Secret directly into your application and never share your Firebase Secret with a connected client.

    To generate tokens, you’ll need your Firebase Secret which you can find by entering your Firebase URL into a browser and clicking the «Secrets» tab on the left-hand navigation menu.

    Once you’ve downloaded the library and grabbed your Firebase Secret, you can generate a token with this snippet of Java code:

    The payload object passed into createToken() is then available for use within your security rules via the auth variable. This is how you pass trusted authentication details (e.g. the client’s user ID) to your Firebase security rules. The payload can contain any data of your choosing, however it must contain a «uid» key, which must be a string of less than 256 characters. The generated token must be less than 1024 characters in total.

    A second options argument can be passed to createToken() to modify how Firebase treats the token. The TokenOptions object has the following methods:

    setExpires(Date) — A timestamp denoting the time after which this token should no longer be valid.

    setNotBefore(Date) — A timestamp denoting the time before which this token should be rejected by the server.

    setAdmin(boolean) — Set to true if you want to disable all security rules for this client. This will provide the client with read and write access to your entire Firebase.

    setDebug(boolean) — Set to true to enable debug output from your security rules. You should generally not leave this set to True in production (as it slows down the rules implementation and gives your users visibility into your rules), but it can be helpful for debugging.

    Here is an example of how to use the second options argument:

    Token Authentication for Java Applications

    by Micah Silverman | August 13, 2015 |

    Heads up… this article is old!

    For an updated version of this article, see Simple Token Authentication for Java Apps on the Okta developer blog.

    Update 5/12/2016: Building a Java application? JJWT is a Java library providing end-to-end JWT creation and verification, developed by our very own Les Hazlewood. Forever free and open-source (Apache License, Version 2.0), JJWT is simple to use and understand. It was designed with a builder-focused fluent interface hiding most of its complexity. We’d love to have you try it out, and let us know what you think! (And, if you’re a Node developer, check out NJWT!)

    In my last post, we covered a lot of ground, including how we traditionally go about securing websites, some of the pitfalls of using cookies and sessions, and how to address those pitfalls by traditional means.

    In this post we’ll go beyond the traditional and take a deep dive into how token authentication with JWTs (JSON Web Tokens) not only addresses these concerns, but also gives us the benefit of inspectable metadata and strong cryptographic signatures.

    Token Authentication to the Rescue!

    Let’s first examine what we mean by authentication and token in this context.

    Authentication is proving that a user is who they say they are.

    A token is a self-contained singular chunk of information. It could have intrinsic value or not. We are going to look at a particular type of token that does have intrinsic value and addresses a number of the concerns with session IDs.

    JSON Web Tokens (JWTs)

    JWTs are a URL-safe, compact, self-contained string with meaningful information that is usually digitally signed or encrypted. They’re quickly becoming a de-facto standard for token implementations across the web.

    URL-safe is a fancy way of saying that the entire string is encoded so there are no special characters and the token can fit in a URL.

    The string is opaque and can be used standalone in much the same way that session IDs are used. By opaque, I mean that looking at the string itself provides no additional information.

    However, the string can also be decoded to pull out metadata and its signature can be cryptographically verified so that your application knows that the token has not been tampered with.

    Читать еще:  Javascript get set

    JWTs and OAuth2 Access Tokens

    Many OAuth2 implementations are using JWTs for their access tokens. It should be stated that the OAuth2 and JWT specifications are completely separate from each other and don’t have any dependencies on each other. Using JWTs as the token mechanism for OAuth2 affords a lot of benefit as we’ll see below.

    JWTs can be stored in cookies, but all the rules for cookies we discussed before still apply. You can entirely replace your session id with a JWT. You can then gain the additional benefit of accessing the meta-information directly from that session id.

    In the wild, they look like just another ugly string:

    If you look carefully, you can see that there are two periods in the string. These are significant as they delimit different sections of the JWT.

    JWT Structure

    JWTs have a three part structure, each of which is base64-encoded:

    Here are the parts decoded:

    Header

    Claims

    Cryptographic Signature

    JWT Claims

    Let’s examine the claims sections. Each type of claim that is part of the JWT Specification can be found here.

    iss is who issued the token.
    exp is when the token expires.
    sub is the subject of the token. This is usually a user identifier of some sort.

    The above parts of the claim are all included in the JWT specification. scope is not included in the specification, but it is commonly used to provide authorization information. That is, what parts of the application the user has access to.

    One advantage of JWTs is that arbitrary data can be encoded into the claims as with scope above. Another advantage is that the client can now react to this information without any further interaction with the server. For instance, a portion of the page may be hidden based on the data found in the scope claim.

    NOTE: It is still critical and a best practice for the server to always verify actions taken by the client. If, for instance, some administrative action was being taken on the client, you would still want to verify on the application server that the current user had permission to perform that action. You would never rely on client side authorization information alone.

    You may have picked up on another advantage: the cryptographic signature. The signature can be verified which proves that the JWT has not been tampered with. Note that the presence of a crytpographic signature does not guarantee confidentiality. Confidentiality is ensured only when the JWT is encrypted as well as signed.

    Now, for the big kicker: statelessness. While the server will need to generate the JWT, it does not need to store it anywhere as all of the user metadata is encoded right in to the JWT. The server and client could pass the JWT back and forth and never store it. This scales very well.

    Managing Bearer Token Security

    Implicit trust is a tradeoff. These types of tokens are often referred to as Bearer Tokens because all that is required to gain access to the protected sections of an application is the presentation of a valid, unexpired token.

    You have to address issues like: How long should the token be good for? How will you revoke it? (There’s a whole other post we could do on refresh tokens.)

    You have to be mindful of what you store in the JWT if they are not encrypted. Do not store any sensitive information. It is generally accepted practice to store a user identifier in the form of the sub claim. When a JWT is signed, it’s referred to as a JWS. When it’s encrypted, it’s referred to as a JWE.

    Java, JWT and You!

    We are very proud of the JJWT project on Github. Primarily authored by Stormpath’s own CTO, Les Hazlewood, it’s a fully open-source JWT solution for Java. It’s the easiest to use and understand library for creating and verifying JSON Web Tokens on the JVM.

    Ссылка на основную публикацию
    Adblock
    detector