本文整理汇总了Java中com.nimbusds.jose.crypto.MACVerifier类的典型用法代码示例。如果您正苦于以下问题:Java MACVerifier类的具体用法?Java MACVerifier怎么用?Java MACVerifier使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MACVerifier类属于com.nimbusds.jose.crypto包,在下文中一共展示了MACVerifier类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: method_verifySignature_should_validate_signedJWT
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Test
public void method_verifySignature_should_validate_signedJWT() throws Exception {
sharedSecret = TOKEN.getBytes();
signedJWT = spy(SignedJWT.parse(TOKEN));
mockStatic(SignedJWT.class);
when(SignedJWT.class, "parse", TOKEN).thenReturn(signedJWT);
when(sessionIndentifierStream.filter(any())).thenReturn(sessionIndentifierStream);
when(sessionIndentifierStream.findFirst()).thenReturn(sessionIdentifierOptional);
when(sessionIdentifierOptional.get()).thenReturn(sessionIdentifier);
when(sessionIdentifier.getSecretKey()).thenReturn(sharedSecret);
whenNew(MACVerifier.class).withArguments(sharedSecret).thenReturn(verifier);
when(signedJWT.verify(verifier)).thenReturn(POSITIVE_ANSWER);
assertTrue(securityContext.verifySignature(TOKEN));
}
示例2: decryptAndVerify
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Override
public String decryptAndVerify(String encryptedAndSignedJwt) {
try {
JWEObject jweObject = JWEObject.parse(encryptedAndSignedJwt);
jweObject.decrypt(new DirectDecrypter(sessionJwtEncryptionKey));
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
if (!signedJWT.verify(new MACVerifier(sessionJwtEncryptionKey))) {
logger.warn("JWT signature verification failed.");
return null;
}
for (JwtClaimsSetVerifier verifier : jwtClaimsSetVerifiers) {
if (!verifier.verify(signedJWT.getJWTClaimsSet())) {
logger.warn("JWT claims verification failed.");
return null;
}
}
return signedJWT.getJWTClaimsSet().getSubject();
} catch (ParseException | JOSEException e) {
throw new RuntimeException("Could not parse JWT", e);
}
}
示例3: verifySignature
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的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;
}
示例4: deserialize
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
public Client deserialize(String jweString) {
try {
JWEObject jweObject = JWEObject.parse(jweString);
jweObject.decrypt(new DirectDecrypter(sessionJwtEncryptionKey));
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
if(!signedJWT.verify(new MACVerifier(sessionJwtEncryptionKey))) {
return null;
}
if(!expirationJwtClaimsVerifier.verify(signedJWT.getJWTClaimsSet())) {
return null;
}
return objectMapper.readValue(signedJWT.getJWTClaimsSet().getSubject(), Client.class);
} catch (ParseException | JOSEException | IOException e) {
throw new RuntimeException("Could not deserialize JWT to Client", e);
}
}
示例5: isValidJWToken
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
/**
* Validates a JWT token.
* @param secret secret used for generating the token
* @param jwt token to validate
* @return true if token is valid
*/
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
try {
if (secret != null && jwt != null) {
JWSVerifier verifier = new MACVerifier(secret);
if (jwt.verify(verifier)) {
Date referenceTime = new Date();
JWTClaimsSet claims = jwt.getJWTClaimsSet();
Date expirationTime = claims.getExpirationTime();
Date notBeforeTime = claims.getNotBeforeTime();
boolean expired = expirationTime == null || expirationTime.before(referenceTime);
boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);
return !(expired || notYetValid);
}
}
} catch (JOSEException e) {
logger.warn(null, e);
} catch (ParseException ex) {
logger.warn(null, ex);
}
return false;
}
示例6: verifyJWT
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
private JWTClaimsSet verifyJWT(JWSObject parsed) throws Exception {
MACVerifier verifier = new MACVerifier(Signer.parseKey(sharedKey));
try {
boolean valid = parsed.verify(verifier);
assertTrue(parsed.verify(verifier));
} catch (JOSEException e) {
assertTrue(false);
}
ReadOnlyJWSHeader header = parsed.getHeader();
assertEquals(2, header.getIncludedParameters().size());
assertTrue(header.getAlgorithm() == JWSAlgorithm.HS256);
assertEquals("JWT", header.getType().toString());
Payload payload = parsed.getPayload();
JWTClaimsSet claims = JWTClaimsSet.parse(payload.toString());
return claims;
}
示例7: verify
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Override
public boolean verify(final SignedJWT jwt) throws JOSEException {
init();
final JWSVerifier verifier = new MACVerifier(this.secret);
return jwt.verify(verifier);
}
示例8: decodeToken
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
public JWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {
SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));
if (signedJWT.verify(new MACVerifier(tokenSecret))) {
return signedJWT.getJWTClaimsSet();
} else {
throw new JOSEException("Signature verification failed");
}
}
示例9: verifySignature
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
public Boolean verifySignature(String token) throws ParseException, JOSEException {
SignedJWT signedJWT = SignedJWT.parse(token);
SessionIdentifier session = getSession(token);
byte[] sharedSecret = session.getSecretKey();
JWSVerifier verifier = new MACVerifier(sharedSecret);
return signedJWT.verify(verifier);
}
示例10: retrieveCredential
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的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;
}
示例11: validToken
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的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;
}
示例12: verifySignatureAndDate
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的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();
}
}
示例13: handle
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Override
public void handle(Request request, Response response) throws Exception {
if (request.headers("Authorization") == null || !request.headers("Authorization").startsWith("Bearer "))
halt(401, createErrorResponse("token_missing", "Not authorized."));
SignedJWT token = SignedJWT.parse(request.headers("Authorization").substring(7));
if (!token.verify(new MACVerifier(sharedSecret)))
halt(401, createErrorResponse("token_invalid", "Not authorized."));
if (new Date().after(token.getJWTClaimsSet().getExpirationTime()))
halt(401, createErrorResponse("token_expired", "Not authorized."));
}
示例14: handle
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Override
public void handle(Request request, Response response) throws Exception {
if (request.headers("Authorization") == null || !request.headers("Authorization").startsWith("Bearer "))
halt(401, createErrorResponse("token_missing", "Not authorized."));
SignedJWT token = SignedJWT.parse(request.headers("Authorization").substring(7));
if (!token.verify(new MACVerifier(sharedSecret)))
halt(401, createErrorResponse("token_invalid", "Not authorized."));
if (new Date().after(token.getJWTClaimsSet().getExpirationTime()))
halt(401, createErrorResponse("token_expired", "Not authorized."));
if(!token.getJWTClaimsSet().getClaim("role").toString().equals("employee")){
halt(401, createErrorResponse("Invalid role", "Not authorized."));
}
}
示例15: setup
import com.nimbusds.jose.crypto.MACVerifier; //导入依赖的package包/类
@Before
public void setup() throws JOSEException {
verifier = new MACVerifier(SECRET);
transformer = new UsernamePasswordAuthenticationTokenJwtClaimsSetTransformer(Long.MAX_VALUE, Optional.empty());
jwtTokenService = new JwtTokenService(transformer, SECRET);
}