生成 JSON Web 令牌
Posted
技术标签:
【中文标题】生成 JSON Web 令牌【英文标题】:Generate JSON Web token 【发布时间】:2015-07-20 10:53:22 【问题描述】:我有这个类来生成我从this post 获得的 JSON Web 令牌。
我需要一个 id 和一个表达式日期来创建一个令牌。
我是否必须设置某种服务器来获取 id 和表达式日期?
/**
* 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 = "crazyquote";
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);
System.out.println("request " + request);
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);
【问题讨论】:
【参考方案1】:我希望在这种情况下用户的 ID 是用户自己发送给应用程序的用户名,或者是您可以根据用户发送的主体查找的其他类型的 ID。您只需选择的到期日期。在用户必须重新登录之前,您希望令牌有效多长时间?现在,关于服务器的话题,OAuth2 协议中没有任何内容要求服务器或 Web 上下文。您正在构建什么样的应用程序?
【讨论】:
这是一个程序,用户通过身份验证可以添加不同的引号。这是我们编写尽可能安全的学校课程代码的地方。而且我已经尝试实现基于令牌的身份验证,但到目前为止进展并不顺利以上是关于生成 JSON Web 令牌的主要内容,如果未能解决你的问题,请参考以下文章
无法在浏览器的 cookie 中存储 json Web 令牌