programing

Java용 JWT(JSON Web Token) 라이브러리

iphone6s 2023. 3. 23. 22:22
반응형

Java용 JWT(JSON Web Token) 라이브러리

Java와 Angular를 사용하여 개발한 웹 어플리케이션을 만들고 있습니다.토큰 인증 및 인가를 구현하도록 선택했습니다.연습을 위해 자격 증명을 서버에 보내고 랜덤 토큰을 생성하여 클라이언트에 다시 보내는 단계에 도달했습니다.서버에 대한 요청 시마다 헤더에 토큰을 첨부하여 완벽하게 작동합니다.인증의 관점에서는 완벽하고 더 이상 필요하지 않기 때문입니다.

다만, 유저 타입(admin, 통상의 유저)과 그 ID, 또는 그 외의 일의 필드를 추적하고 싶다고 생각하고 있습니다.이것에 대해서는, 로그인 조작중에 클라이언트에 반송하는 토큰으로 암호화해야 합니다.그것이 맞습니까?

JWT 라이브러리를 사용하여 이러한 토큰을 생성, 암호화 및 복호화할 수 있는 것이 있습니까?라이브러리의 API와 Maven 의존관계에 대한 링크를 주시면 감사하겠습니다.

감사해요.

JJWT는 JVM 및 Android용 JWT 라이브러리를 가장 쉽게 사용하고 이해하는 것을 목표로 합니다.

https://github.com/jwtk/jjwt

답을 필요로 하는 사람이 있다면

저는 이 라이브러리를 사용했습니다.http://connect2id.com/products/nimbus-jose-jwt Maven here : http://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt/2.10.1

https://jwt.io/ 를 참조해 주세요.jwt다음과 같은 다양한 언어로 구현합니다.java또, 이 사이트에서는, 이러한 실장(이들이 서포트하는 알고리즘과 …)을 비교하고 있습니다.

위해서java다음은 라이브러리입니다.

이 라이브러리는 정상적으로 동작하고 있는 것 같습니다.https://code.google.com/p/jsontoken/

구글 구아바에 따라 다릅니다.Maven의 아티팩트는 다음과 같습니다.

<dependency>
    <groupId>com.googlecode.jsontoken</groupId>
    <artifactId>jsontoken</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

그 라이브러리는 사실 구글 월렛에 의해 사용되고 있다.

jwt를 작성하고 이를 확인하고 역직렬화하는 방법은 다음과 같습니다.

import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.Calendar;
import java.util.List;

import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.crypto.Verifier;
import net.oauth.jsontoken.discovery.VerifierProvider;
import net.oauth.jsontoken.discovery.VerifierProviders;

import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;


/**
 * Provides static methods for creating and verifying access tokens and such. 
 * @author davidm
 *
 */
public class AuthHelper {

    private static final String AUDIENCE = "NotReallyImportant";

    private static final String ISSUER = "YourCompanyOrAppNameHere";

    private static final String SIGNING_KEY = "LongAndHardToGuessValueWithSpecialCharacters@^($%*$%";

    /**
     * Creates a json web token which is a digitally signed token that contains a payload (e.g. userId to identify 
     * the user). The signing key is secret. That ensures that the token is authentic and has not been modified.
     * Using a jwt eliminates the need to store authentication session information in a database.
     * @param userId
     * @param durationDays
     * @return
     */
    public static String createJsonWebToken(String userId, Long durationDays)    {
        //Current time and signing algorithm
        Calendar cal = Calendar.getInstance();
        HmacSHA256Signer signer;
        try {
            signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        //Configure JSON token
        JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
        token.setAudience(AUDIENCE);
        token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
        token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis() + 1000L * 60L * 60L * 24L * durationDays));

        //Configure request object, which provides information of the item
        JsonObject request = new JsonObject();
        request.addProperty("userId", userId);

        JsonObject payload = token.getPayloadAsJsonObject();
        payload.add("info", request);

        try {
            return token.serializeAndSign();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Verifies a json web token's validity and extracts the user id and other information from it. 
     * @param token
     * @return
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    public static TokenInfo verifyToken(String token)  
    {
        try {
            final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());

            VerifierProvider hmacLocator = new VerifierProvider() {

                @Override
                public List<Verifier> findVerifier(String id, String key){
                    return Lists.newArrayList(hmacVerifier);
                }
            };
            VerifierProviders locators = new VerifierProviders();
            locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
            net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker(){

                @Override
                public void check(JsonObject payload) throws SignatureException {
                    // don't throw - allow anything
                }

            };
            //Ignore Audience does not mean that the Signature is ignored
            JsonTokenParser parser = new JsonTokenParser(locators,
                    checker);
            JsonToken jt;
            try {
                jt = parser.verifyAndDeserialize(token);
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
            JsonObject payload = jt.getPayloadAsJsonObject();
            TokenInfo t = new TokenInfo();
            String issuer = payload.getAsJsonPrimitive("iss").getAsString();
            String userIdString =  payload.getAsJsonObject("info").getAsJsonPrimitive("userId").getAsString();
            if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString))
            {
                t.setUserId(new ObjectId(userIdString));
                t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat").getAsLong()));
                t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp").getAsLong()));
                return t;
            }
            else
            {
                return null;
            }
        } catch (InvalidKeyException e1) {
            throw new RuntimeException(e1);
        }
    }


}

public class TokenInfo {
    private ObjectId userId;
    private DateTime issued;
    private DateTime expires;
    public ObjectId getUserId() {
        return userId;
    }
    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }
    public DateTime getIssued() {
        return issued;
    }
    public void setIssued(DateTime issued) {
        this.issued = issued;
    }
    public DateTime getExpires() {
        return expires;
    }
    public void setExpires(DateTime expires) {
        this.expires = expires;
    }
}

이것은, 다음의 코드에 근거하고 있습니다.https://developers.google.com/wallet/instant-buy/about-jwts 및 https://code.google.com/p/wallet-online-sample-java/source/browse/src/com/google/wallet/online/jwt/util/WalletOnlineService.java?r=08b3333bd7260b20846d7d96d3cf15be8a128dfa

IETF는 Wiki에서 jose libs를 제안했습니다.http://trac.tools.ietf.org/wg/jose/trac/wiki

서명에 사용하는 것을 강력히 추천합니다.저는 Java는 아니지만 jose4j를 선택하는 것이 좋을 것 같습니다.좋은 예도 있습니다.https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples

업데이트: jwt.io에서는 몇 가지 jwt 관련 라이브러리와 그 기능을 쉽게 비교할 수 있습니다.꼭 확인하세요!

나는 다른 자바 개발자들이 선호하는 것에 대해 듣고 싶다.

저는 이것이 작고 완전한 https://github.com/auth0/java-jwt임을 알게 되었습니다.

이 페이지에서는 Java를 포함한 다양한 언어의 구현에 대한 참조를 유지하고 http://kjur.github.io/jsjws/index_mat.html 기능을 비교합니다.

서명되지 않은 암호화되지 않은 토큰만 해석해야 하는 경우 다음 코드를 사용할 수 있습니다.

boolean parseJWT_2() {
    String authToken = getToken();
    String[] segments = authToken.split("\\.");
    String base64String = segments[1];
    int requiredLength = (int)(4 * Math.ceil(base64String.length() / 4.0));
    int nbrPaddings = requiredLength - base64String.length();

    if (nbrPaddings > 0) {
        base64String = base64String + "====".substring(0, nbrPaddings);
    }

    base64String = base64String.replace("-", "+");
    base64String = base64String.replace("_", "/");

    try {
        byte[] data = Base64.decode(base64String, Base64.DEFAULT);

        String text;
        text = new String(data, "UTF-8");
        tokenInfo = new Gson().fromJson(text, TokenInfo.class);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

https://github.com/networknt/jsontoken

오리지널 구글 jontoken의 포크입니다.

2012년 9월 11일 이후 업데이트되지 않았으며 일부 오래된 패키지에 의존합니다.

내가 한 일:

Convert from Joda time to Java 8 time. So it requires Java 8.
Covert Json parser from Gson to Jackson as I don't want to include two Json parsers to my projects.
Remove google collections from dependency list as it is stopped long time ago.
Fix thread safe issue with Java Mac.doFinal call.

기존의 모든 유닛 테스트는 새롭게 추가된 테스트 케이스와 함께 합격했습니다.

다음으로 토큰을 생성하고 토큰을 확인하는 예를 나타냅니다.상세한 것에 대하여는, https://github.com/networknt/light 의 소스 코드를 참조해 주세요.

저는 jsontoken과 Omni-Channel Application Framework의 저자입니다.

언급URL : https://stackoverflow.com/questions/23808460/jwt-json-web-token-library-for-java

반응형