JWT正在发出相同的令牌

时间:2017-03-23 11:15:50

标签: java rest jersey jwt

我正在使用Jersey创建一个rest API。我使用java-jwthttps://github.com/auth0/java-jwt)进行令牌生成工作。请检查以下代码。

UserJSONInfo - REST方法类

@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 - 服务层

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 - 只需包含secret

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>

我将我的令牌生成类维护为另一个java项目,并将其作为库导入(我使用的是Netbeans)。以下是代码

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个不同的用户进行了登录尝试。问题是我得到了相同的标记!这是对的还是错的?在那种情况下,我该如何解决?

1 个答案:

答案 0 :(得分:4)

基于令牌的认证方案是什么

在基于令牌的身份验证方案中,令牌成为用户的凭据。用户名和密码等硬凭证将交换为必须在每个请求中发送的令牌,然后服务器才能执行身份验证/授权。令牌可以在很短的时间内有效,可以撤销,可以携带范围详细信息(可以使用令牌请求的内容)等。

使用令牌,您必须能够识别定位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中基于令牌的身份验证的更多详细信息,请参阅此answer