JWT issues the same token

I am creating a holiday API with Jersey. I use java-jwt( https://github.com/auth0/java-jwt ) to work with my tokens. Please check the code below.

UserJSONInfo - REST Method Class

@Path ("/user_info")
public class UserInfoJSONService 
{
    @POST
    @Path("/authenticateUser")
    @Produces(MediaType.APPLICATION_JSON)
    public Response authenticateUser(Credentials credentials)
    {
        UserInfoService service = new UserInfoService();

        try{
        UserInfo authenticateUser = service.authenticateUser(credentials.getUserName(), credentials.getPassword());
        String generateToken = service.generateToken(AuthKey.authorizationSecret);

        Authentication auth = new Authentication();
        auth.setIdUser(authenticateUser.getIduser());
        auth.setToken(generateToken);

        return Response.status(Response.Status.OK).entity(auth).build();
        //return authenticateUser;
        }
        catch(IndexOutOfBoundsException e)
        {
            throw new WebApplicationException(Response.Status.BAD_REQUEST);
        } catch (JWTCreationException ex) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        } catch (UnsupportedEncodingException ex) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}

UserInfoService - Service Level

public class UserInfoService {

    private static UserInfoDAOInterface userDAOInterface;

    public UserInfoService() {
        userDAOInterface = new UserInfoDAOImpl();
    }

    public Session getSession() {
        Session session = userDAOInterface.openCurrentSession();
        return session;
    }

    public Transaction getTransaction(Session session) {
        Transaction transaction = userDAOInterface.openTransaction(session);
        return transaction;
    }



    public UserInfo authenticateUser(String userName, String password)
    {
        return authenticate(userName, password);
    }

    private UserInfo authenticate(String userName, String password) throws IndexOutOfBoundsException
    {
        Session session = userDAOInterface.openCurrentSession();
        Transaction transaction = null;
        UserInfo user = new UserInfo();

        try {
            transaction = userDAOInterface.openTransaction(session);
            user = userDAOInterface.authenticate(userName, password, session);
            transaction.commit();
//        } catch (Exception ex) {
//            //ex.printStackTrace();
//            System.out.println("OK");
//        
        } finally {
            session.close();
        }

        return user;
    }

    public String generateToken(String secret) throws JWTCreationException, UnsupportedEncodingException
    {
        Token token = new Token();
        return token.issueTokenHMAC256(secret);
    }

}

AuthKey - just containssecret

public interface AuthKey {
    public static String authorizationSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>ExampleServlet</servlet-name>
        <servlet-class>test.ExampleServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Jersey RESTful Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>rest</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ExampleServlet</servlet-name>
        <url-pattern>/ExampleServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Jersey RESTful Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

I saved the token generation classes as another java project and imported it here as a library (I use Netbeans). Below is the code

package com.xyz.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;

/**
 *
 * @author Yohan
 */
public class Token {

    /**
     * Generate the HMAC256 Token
     * @param secret
     *          Secret to generate the token
     * @return 
     *      Token as a String
     * @throws UnsupportedEncodingException
     *      UTF-8 encoding not supported
     * @throws JWTVerificationException 
     *      Invalid Signing configuration / Couldn't convert Claims.
     */
    public String issueTokenHMAC256(String secret) throws UnsupportedEncodingException, JWTCreationException
    {

        String token="";
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            token = JWT.create()
                    .withIssuer("auth0")
                    .sign(algorithm);


        } catch (UnsupportedEncodingException exception) {
    //UTF-8 encoding not supported
            exception.printStackTrace();
        } catch (JWTCreationException exception) {
    //Invalid Signing configuration / Couldn't convert Claims.
            exception.printStackTrace();
        }

        return token;
    }


    /**
     * Validate a HMAC256 Token
     * @param token
     *          Token you need to validate
     * @param secret
     *          Secret used to generate the token
     * @return
     *          Returns `true` if token is valid.
     * @throws UnsupportedEncodingException
     *          UTF-8 encoding not supported
     * @throws JWTVerificationException 
     *          Invalid Signing configuration / Couldn't convert Claims.
     */
    public boolean validateTokenHMAC256(String token, String secret) throws UnsupportedEncodingException, JWTVerificationException
    {       
        Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("auth0")
                .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);

        return true;
    }
}

, , token , token. POSTMAN REST, 3 3 . , ! - ? , ?

+3
1

, ,

, , . , , , , /. , , ( ) ..

, API. , , .

JWT, . , (exp). , , ?

java-jwt :

try {

    Algorithm algorithm = Algorithm.HMAC256("secret");
    Date expirationDate = Date.from(ZonedDateTime.now().plusMinutes(60).toInstant());
    String token = JWT.create()
                      .withExpiresAt(expirationDate)
                      .withClaim("username", username)
                      .sign(algorithm);

} catch (UnsupportedEncodingException e){
    // UTF-8 encoding not supported
} catch (JWTCreationException e){
    // Invalid signing configuration / Couldn't convert claims
}

username , :

try {

    Algorithm algorithm = Algorithm.HMAC256("secret");
    JWTVerifier verifier = JWT.require(algorithm).build();
    DecodedJWT jwt = verifier.verify(token);

    Claim usernameClaim = jwt.getClaim("username");
    String username = usernameClaim.asString();

} catch (UnsupportedEncodingException e){
    // UTF-8 encoding not supported
} catch (JWTVerificationException e){
    // Invalid signature/claims
}

JWT

( ) . , exp.

, , ( ):

  • refreshLimit: , .
  • refreshCount: , .

, :

  • (exp >= now).
  • , (refreshCount < refreshLimit).

:

  • (exp = now + some-amount-of-time).
  • (refreshCount++).

, .

, . .

, JWT, .

.

JWT

, . , ( ) , . UUID.

jti . , , jti , .

, .


JAX-RS . .

+3

Source: https://habr.com/ru/post/1672428/


All Articles