本文整理汇总了Java中com.nimbusds.jose.JWSObject.parse方法的典型用法代码示例。如果您正苦于以下问题:Java JWSObject.parse方法的具体用法?Java JWSObject.parse怎么用?Java JWSObject.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.nimbusds.jose.JWSObject
的用法示例。
在下文中一共展示了JWSObject.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getJWTUser
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static JWTUser getJWTUser(String token) throws JWTException {
if (StringUtils.isEmpty(token)) {
throw new JWTException("没有找到token信息!");
}
try {
JWSObject jwsObject = JWSObject.parse(token);
if (JWT.verify(jwsObject)) {
// 判断有效期,不在有效期内则直接抛出错误
JWTUser user = new JWTUser(jwsObject.getPayload().toJSONObject());
if (user.getExp() >= Calendar.getInstance().getTimeInMillis()) {
return user;
} else {
throw new JWTException("token已经超过有效期!");
}
} else {
throw new JWTException("token校验失败!");
}
} catch (Exception e) {
throw new JWTException(e);
}
}
示例2: verifySignature
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static boolean verifySignature( String token, String sharedKey )
{
boolean verifiedSignature = false;
try
{
JWSObject jwsObject = JWSObject.parse( token );
JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );
verifiedSignature = jwsObject.verify( verifier );
}
catch ( Exception e )
{
LOG.warn( e.getMessage() );
}
return verifiedSignature;
}
示例3: extractChainData
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private static Any<Key, JsonObject> extractChainData(Map<String, List<String>> maindata) throws ParseException {
List<String> chain = maindata.get("chain");
try {
PublicKey key = parseKey(MOJANG_KEY);
boolean foundMojangKey = false;
boolean signatureValid = false;
for (String element : chain) {
JWSObject jwsobject = JWSObject.parse(element);
if (!foundMojangKey && jwsobject.getHeader().getX509CertURL().toString().equals(MOJANG_KEY)) {
foundMojangKey = true;
signatureValid = true;
}
if (foundMojangKey && !verify(jwsobject, key)) {
signatureValid = false;
}
JsonObject jsonobject = Utils.GSON.fromJson(jwsobject.getPayload().toString(), JsonObject.class);
key = parseKey(JsonUtils.getString(jsonobject, "identityPublicKey"));
if (jsonobject.has("extraData")) {
return new Any<Key, JsonObject>(signatureValid ? key : null, JsonUtils.getJsonObject(jsonobject, "extraData"));
}
}
} catch (InvalidKeySpecException | JOSEException e) {
throw new DecoderException("Unable to decode login chain", e);
}
throw new DecoderException("Unable to find extraData");
}
示例4: createToken
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public JWTAuthenticationToken createToken(String token) {
try {
JWSObject jwsObject = JWSObject.parse(token);
String decrypted = jwsObject.getPayload().toString();
try (JsonReader jr = Json.createReader(new StringReader(decrypted))) {
JsonObject object = jr.readObject();
String userId = object.getString("sub", null);
return new JWTAuthenticationToken(userId, token);
}
} catch (ParseException ex) {
throw new AuthenticationException(ex);
}
}
示例5: authenticate
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Authentication authenticationResult = authenticationManager
.authenticate(authentication);
if (authenticationResult.isAuthenticated()) {
// validates nonce because JWT is already valid
if (authentication instanceof PoPAuthenticationToken) {
PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;
// starts validating nonce here
String nonce = popAuthentication.getNonce();
if (nonce == null) {
throw new UnapprovedClientAuthenticationException(
"This request does not have a valid signed nonce");
}
String token = (String) popAuthentication.getPrincipal();
System.out.println("access token:" + token);
try {
JWT jwt = JWTParser.parse(token);
String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
JWK jwk = JWK.parse(publicKey);
JWSObject jwsNonce = JWSObject.parse(nonce);
JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
if (!jwsNonce.verify(verifier)) {
throw new InvalidTokenException("Client hasn't possession of given token");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return authenticationResult;
}
示例6: verifyCertificateIsValid
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private boolean verifyCertificateIsValid(String token) {
try {
JWSObject jwsToken = JWSObject.parse(token);
jwsToken.verify(VERIFIER_FACTORY.createJWSVerifier(jwsToken.getHeader(), mojangPublicKey));
} catch (ParseException | JOSEException ex) {
return false;
}
return true;
}
示例7: verifyContainsMojangRootPublicKey
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private boolean verifyContainsMojangRootPublicKey(String token) {
try {
JWSObject jwsToken = JWSObject.parse(token);
return jwsToken.verify(VERIFIER_FACTORY.createJWSVerifier(jwsToken.getHeader(), mojangPublicKey));
} catch (ParseException | JOSEException ex) {
throw new RuntimeException(ex);
}
}
示例8: readLoginIdentity
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private String readLoginIdentity(String token) {
try {
JWSObject jwsObject = JWSObject.parse(token);
JSONObject json = jwsObject.getPayload().toJSONObject();
if (!json.containsKey("extraData")) {
return null;
}
return json.getAsString("extraData");
} catch (ParseException ex) {
return null;
}
}
示例9: UserPrincipal
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public UserPrincipal(String idToken) throws MalformedURLException, ParseException,
BadJOSEException, JOSEException {
final ConfigurableJWTProcessor<SecurityContext> validator = getAadJwtTokenValidator();
jwtClaimsSet = validator.process(idToken, null);
final JWTClaimsSetVerifier<SecurityContext> verifier = validator
.getJWTClaimsSetVerifier();
verifier.verify(jwtClaimsSet, null);
jwsObject = JWSObject.parse(idToken);
userGroups = null;
}
示例10: retrieveCredential
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
@Override
public JWTCredential retrieveCredential(String token) {
JWTCredential result = null;
try {
JWSObject jws = JWSObject.parse(token);
String apiKey = jws.getHeader().getKeyID();
if (apiKey != null && keys.contains(apiKey)) {
RSAKey rsaKey = (RSAKey) jwkSet.getKeyByKeyId(apiKey).toPublicJWK();
JWSVerifier verifier = new RSASSAVerifier(rsaKey);
if (jws.verify(verifier)) {
JWTClaimsSet claimsSet = JWTClaimsSet.parse(jws.getPayload().toJSONObject());
// Verify time validity of token.
Date creationTime = claimsSet.getIssueTime();
Date expirationTime = claimsSet.getExpirationTime();
Date now = new Date();
long validityPeriod = expirationTime.getTime() - creationTime.getTime();
if (creationTime.before(now) && now.before(expirationTime) && validityPeriod < 120000 /*2 minutes*/) {
JSONObject realmAccess = (JSONObject) claimsSet.getClaim("realm_access");
JSONArray rolesArray = (JSONArray) realmAccess.get("roles");
Set<String> roles = new HashSet<>();
rolesArray.forEach(r -> roles.add(r.toString()));
result = new JWTCredential(claimsSet.getSubject(), roles);
}
}
}
} catch (ParseException | JOSEException e) {
; // Token is not valid
}
return result;
}
示例11: retrieveAuthenticationToken
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
/**
* returns the access token from Request Header "Authorization"
* if the token is invalid an MCRRestAPIException is thrown
*
* @param request - the HTTPServletRequest object
* @return the JSON Web Token or null, if not provided in request
* @throws MCRRestAPIException
*/
public static SignedJWT retrieveAuthenticationToken(HttpServletRequest request) throws MCRRestAPIException {
String auth = request.getHeader("Authorization");
if (auth != null && auth.startsWith("Bearer ")) {
String authToken = auth.substring(7).trim();
try {
JWSObject jwsObj = JWSObject.parse(authToken);
SignedJWT signedJWT = jwsObj.getPayload().toSignedJWT();
// JWK class does equals only by object id
if (signedJWT.verify(new RSASSAVerifier((RSAPublicKey) MCRJSONWebTokenUtil.RSA_KEYS.getPublic()))
&& jwsObj.getHeader().getJWK().toJSONString()
.equals(JWK.parse(signedJWT.getJWTClaimsSet().getJSONObjectClaim("sub_jwk")).toJSONString())) {
Date expires = signedJWT.getJWTClaimsSet().getExpirationTime();
if (Instant.now().isBefore(expires.toInstant())) {
return signedJWT;
} else {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.GERMANY).withZone(ZoneId.systemDefault());
throw new MCRRestAPIException(Status.UNAUTHORIZED,
new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION,
"The Authentication Token expired at " + formatter.format(expires.toInstant()),
"Please log-in again."));
}
} else {
throw new MCRRestAPIException(Status.UNAUTHORIZED,
new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION,
"The signature of the Authentication Token could not be verified.", null));
}
} catch (ParseException | JOSEException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(
MCRRestAPIError.CODE_INVALID_AUTHENCATION, "Authentication is invalid.", e.getMessage()));
}
} else {
return null;
}
}
示例12: retrieveCredential
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
@Override
public JWTCredential retrieveCredential(String token) {
JWTCredential result = null;
try {
JWSObject jws = JWSObject.parse(token);
String apiKey = jws.getHeader().getKeyID();
if (apiKey != null && keys.containsKey(apiKey)) {
byte[] sharedSecret = keys.get(apiKey);
JWSVerifier verifier = new MACVerifier(sharedSecret);
if (jws.verify(verifier)) {
JWTClaimsSet claimsSet = JWTClaimsSet.parse(jws.getPayload().toJSONObject());
// Verify time validity of token.
Date creationTime = claimsSet.getIssueTime();
Date expirationTime = claimsSet.getExpirationTime();
Date now = new Date();
long validityPeriod = expirationTime.getTime() - creationTime.getTime();
if (creationTime.before(now) && now.before(expirationTime) && validityPeriod < 120000 /*2 minutes*/) {
JSONObject realmAccess = (JSONObject) claimsSet.getClaim("realm_access");
JSONArray rolesArray = (JSONArray) realmAccess.get("roles");
Set<String> roles = new HashSet<>();
rolesArray.forEach(r -> roles.add(r.toString()));
result = new JWTCredential(claimsSet.getSubject(), roles);
result.addInfo(API_KEY, apiKey);
}
}
}
} catch (ParseException | JOSEException e) {
; // Token is not valid
}
return result;
}
示例13: validToken
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
/**
* 校验token是否合法,返回Map集合,集合中主要包含 state状态码 data鉴权成功后从token中提取的数据
* 该方法在过滤器中调用,每次请求API时都校验
* @param token
* @return Map<String, Object>
*/
public static Map<String, Object> validToken(String token) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
JWSObject jwsObject = JWSObject.parse(token);
Payload payload = jwsObject.getPayload();
JWSVerifier verifier = new MACVerifier(SECRET);
if (jwsObject.verify(verifier)) {
JSONObject jsonOBj = payload.toJSONObject();
// token校验成功(此时没有校验是否过期)
resultMap.put("state", TokenState.VALID.toString());
// 若payload包含ext字段,则校验是否过期
if (jsonOBj.containsKey("ext")) {
long extTime = Long.valueOf(jsonOBj.get("ext").toString());
long curTime = new Date().getTime();
// 过期了
if (curTime > extTime) {
resultMap.clear();
resultMap.put("state", TokenState.EXPIRED.toString());
}
}
resultMap.put("data", jsonOBj);
} else {
// 校验失败
resultMap.put("state", TokenState.INVALID.toString());
}
} catch (Exception e) {
//e.printStackTrace();
// token格式不合法导致的异常
resultMap.clear();
resultMap.put("state", TokenState.INVALID.toString());
}
return resultMap;
}
示例14: verifySignatureAndDate
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static boolean verifySignatureAndDate( String token, String sharedKey ) throws SystemSecurityException
{
try
{
JWSObject jwsObject = JWSObject.parse( token );
JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );
if ( jwsObject.verify( verifier ) )
{
long date = getDate( jwsObject );
if ( date == 0 || System.currentTimeMillis() <= date )
{
return true;
}
else
{
throw new IdentityExpiredException();
}
}
else
{
throw new InvalidLoginException();
}
}
catch ( JOSEException | ParseException ex )
{
LOG.warn( ex.getMessage() );
throw new InvalidLoginException();
}
}
示例15: parseToken
import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static Payload parseToken( String token )
{
Payload payload = null;
try
{
JWSObject jwsObject = JWSObject.parse( token );
payload = jwsObject.getPayload();
}
catch ( Exception e )
{
LOG.error( "Error parsing token", e.getMessage() );
}
return payload;
}