当前位置: 首页>>代码示例>>Java>>正文


Java JWSObject.verify方法代码示例

本文整理汇总了Java中com.nimbusds.jose.JWSObject.verify方法的典型用法代码示例。如果您正苦于以下问题:Java JWSObject.verify方法的具体用法?Java JWSObject.verify怎么用?Java JWSObject.verify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.nimbusds.jose.JWSObject的用法示例。


在下文中一共展示了JWSObject.verify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: 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;
}
 
开发者ID:subutai-io,项目名称:base,代码行数:18,代码来源:TokenUtil.java

示例2: verifyTokenRSA

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static boolean verifyTokenRSA( PublicKey pKey, String token )
{
    try
    {
        Payload pl = new Payload( token );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );
        JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey );

        return jwsObject.verify( verifier );
    }
    catch ( JOSEException e )
    {
        LOG.warn( "Error verifying RSA token", e.getMessage() );

        return false;
    }
}
 
开发者ID:subutai-io,项目名称:base,代码行数:18,代码来源:TokenUtil.java

示例3: 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;
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:42,代码来源:PoPAuthenticationManager.java

示例4: 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;
}
 
开发者ID:JungleTree,项目名称:JungleTree,代码行数:10,代码来源:LoginValidator.java

示例5: 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);
    }
}
 
开发者ID:JungleTree,项目名称:JungleTree,代码行数:9,代码来源:LoginValidator.java

示例6: validatePublicKey

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private boolean validatePublicKey(JWSObject jwsToken, Key key) {
    JWSVerifier verifier;
    try {
        verifier = VERIFIER_FACTORY.createJWSVerifier(jwsToken.getHeader(), key);
    } catch (JOSEException ex) {
        return false;
    }

    try {
        return jwsToken.verify(verifier);
    } catch (JOSEException e) {
        return false;
    }
}
 
开发者ID:JungleTree,项目名称:JungleTree,代码行数:15,代码来源:LoginValidator.java

示例7: 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;
}
 
开发者ID:atbashEE,项目名称:jsr375-extensions,代码行数:39,代码来源:DemoJWTHandler.java

示例8: 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;
}
 
开发者ID:rdebusscher,项目名称:soteria-jwt,代码行数:40,代码来源:DemoJWTHandler.java

示例9: 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;
}
 
开发者ID:bigmeow,项目名称:JWT,代码行数:43,代码来源:Jwt.java

示例10: 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();
    }
}
 
开发者ID:subutai-io,项目名称:base,代码行数:33,代码来源:TokenUtil.java

示例11: verify

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private boolean verify(PublicKey key, JWSObject object) throws JOSEException {
    JWSVerifier verifier = new DefaultJWSVerifierFactory().createJWSVerifier(object.getHeader(), key);
    return object.verify(verifier);
}
 
开发者ID:voxelwind,项目名称:voxelwind,代码行数:5,代码来源:InitialNetworkPacketHandler.java

示例12: assertSignatureValid

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private void assertSignatureValid(JWSObject jwsObject, X509Certificate signingCertificate) throws JwtVerifyException {
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) signingCertificate.getPublicKey());
    try {
        // Verify the JWT was signed by the signing certificate
        if (!jwsObject.verify(verifier)) {
            // The contract on the verify method above is odd. Some failure scenarios result in returning false
            // while others throw. To distinguish between the two we throw different exception for each case.
            LOGGER.warn(format(SIGNATURE_MATCH_EXCEPTION, signingCertificate.getSubjectDN().getName()));
            throw new JwtVerifyException(SIGNATURE_MATCH_EXCEPTION, signingCertificate.getSubjectDN().getName());
        }
    } catch (JOSEException e) {
        LOGGER.warn(JWS_VERIFICATION_EXCEPTION, e);
        throw new JwtVerifyException(JWS_VERIFICATION_EXCEPTION, e);
    }
}
 
开发者ID:wdawson,项目名称:dropwizard-auth-example,代码行数:16,代码来源:JwtVerifier.java

示例13: verify

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
public static boolean verify(JWSObject jwsObject) throws JOSEException {
	JWSVerifier verifier = new MACVerifier(JWT.SHARED_SECRET);
	return jwsObject.verify(verifier);
}
 
开发者ID:mazhaoyong,项目名称:api-server-seed,代码行数:5,代码来源:JWT.java

示例14: verify

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
private static boolean verify(JWSObject object, PublicKey key) throws JOSEException {
	return object.verify(jwsverifierfactory.createJWSVerifier(object.getHeader(), key));
}
 
开发者ID:ProtocolSupport,项目名称:ProtocolSupportBungee,代码行数:4,代码来源:LoginHandshakePacket.java

示例15: authenticate

import com.nimbusds.jose.JWSObject; //导入方法依赖的package包/类
@Override
public Authentication authenticate(final Authentication authentication)
		throws AuthenticationException {

	JWSAuthenticationToken authRequest = (JWSAuthenticationToken) authentication;
	String token = authRequest.getJwsToken();
	Object messagePayload = authRequest.getPayload();
	if (StringUtils.isEmpty(token))
		throw new BadCredentialsException("Auth Token invalid");



	try
	{
		JWSObject jwsObject = JWSObject.parse(token);

           //We should test this comparation with binary payloads
           //Ensure message integrity
           if (!jwsObject.getPayload().toString()
                   .equals(messagePayload.toString())) {
               throw new BadCredentialsException("Invalid payload");
           }

		if (jwsObject.verify(verifier))
		{
			Collection<GrantedAuthority> authoritiesDefault = new ArrayList<GrantedAuthority>();
               String[] roles = defaultRoles.split(",");
               for (String role : roles) {
                   if (!StringUtils.isEmpty(role)){
                       GrantedAuthority auth = new SimpleGrantedAuthority(defaultRoles);
                       authoritiesDefault.add(auth);
                   }
               }

			if (userDetailsService != null)
			{
				UserDetails userDetails = userDetailsService.loadUserByUsername(cn);
				authoritiesDefault.addAll(userDetails.getAuthorities());
			}

			JWSAuthenticationToken authResult =
					new JWSAuthenticationToken((Object) cn, authoritiesDefault);

			if (logger.isDebugEnabled()) {
				logger.debug("CN: " + cn);
				logger.debug("Authentication success: " + authResult);
			}

			return authResult;
		}
	} catch(ParseException pe){
           throw new BadCredentialsException("Invalid JWS Object", pe);
       } catch (UsernameNotFoundException unfe){
		throw new BadCredentialsException("Auth Token invalid", unfe);
	}catch(Exception e){
           throw new BadCredentialsException("Unknown error", e);
       }
	return null;

}
 
开发者ID:Appverse,项目名称:appverse-server,代码行数:61,代码来源:JWSAuthenticationProvider.java


注:本文中的com.nimbusds.jose.JWSObject.verify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。