• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java RSASSAVerifier类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



RSASSAVerifier类属于com.nimbusds.jose.crypto包,在下文中一共展示了RSASSAVerifier类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: retrieveUsernamePasswordFromLoginToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/** 
 * retrieves username and password from JSON web tocken 
 * 
 * @param token - the serialized JSON web token from login
 * @return username and password (combined by ":")
 */
public static String retrieveUsernamePasswordFromLoginToken(String token) {
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(token);

        // Decrypt with shared key
        jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));

        // Extract payload
        SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
        RSAKey serverPublicKey = RSAKey.parse(signedJWT.getHeader().getJWK().toJSONObject());

        if (signedJWT.verify(new RSASSAVerifier(serverPublicKey))) {
            //Token is valid
            String username = signedJWT.getJWTClaimsSet().getSubject();
            String password = signedJWT.getJWTClaimsSet().getStringClaim("password");
            return username + ":" + password;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }

    return null;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:31,代码来源:MCRJSONWebTokenUtil.java


示例2: testRolesEndpointToJWTString

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 *
 * @throws Exception
 */
@Test
public void testRolesEndpointToJWTString() throws Exception {
    // Transform the JSON content into a signed JWT
    String jwt = TokenUtils.generateTokenString("/Token1.json");
    System.out.println(jwt);
    /* Note that if you try to validate this token string via jwt.io debugger, you need to take the
    /publicKey.pem contents, and use
    -----BEGIN PUBLIC KEY-----
    ...
    -----END PUBLIC KEY-----

    rather than the:
    -----BEGIN RSA PUBLIC KEY-----
    ...
    -----END RSA PUBLIC KEY-----

    in the file.
    */

    // Validate the string via Nimbus
    SignedJWT signedJWT = SignedJWT.parse(jwt);
    PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    Assert.assertTrue(publicKey instanceof RSAPublicKey, "publicKey isa RSAPublicKey");
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey)publicKey);
    Assert.assertTrue(signedJWT.verify(verifier));
}
 
开发者ID:eclipse,项目名称:microprofile-jwt-auth,代码行数:31,代码来源:TokenUtilsTest.java


示例3: validateSignature

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
  boolean valid = false;
  if (JWSObject.State.SIGNED == jwtToken.getState()) {
    LOG.debug("JWT token is in a SIGNED state");
    if (jwtToken.getSignature() != null) {
      LOG.debug("JWT token signature is not null");
      try {
        JWSVerifier verifier = new RSASSAVerifier(publicKey);
        if (jwtToken.verify(verifier)) {
          valid = true;
          LOG.debug("JWT token has been successfully verified");
        } else {
          LOG.warn("JWT signature verification failed.");
        }
      } catch (JOSEException je) {
        LOG.warn("Error while validating signature", je);
      }
    }
  }
  return valid;
}
 
开发者ID:aliyun-beta,项目名称:aliyun-oss-hadoop-fs,代码行数:31,代码来源:JWTRedirectAuthenticationHandler.java


示例4: parseAndVerifyToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
public SignedJWT parseAndVerifyToken(String jwtString) throws WebApiClientException {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwtString);

        JWSVerifier verifier = new RSASSAVerifier(jwtConfig.getRSAPublicKey());
        if (signedJWT.verify(verifier)) {
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
            if (claimsSet.getAudience().contains(jwtConfig.getServiceUUID()) &&
                    claimsSet.getIssuer().equalsIgnoreCase(JwtUtil.ISSUER)) {
                return signedJWT;
            }
        }
    } catch (ParseException | JOSEException e) {
        throw new WebApiClientException(e.getMessage());
    }
    throw new WebApiClientException("Authorization token cannot be verified");
}
 
开发者ID:vrk-kpa,项目名称:roles-auths-client,代码行数:18,代码来源:JwtUtil.java


示例5: retrievePublicKeyFromLoginToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 * retrieves the client public key from Login Token
 * 
 * @param token - the serialized JSON Web Token from login
 * @return the public key as JWK object
 */
public static JWK retrievePublicKeyFromLoginToken(String token) {
    JWK result = null;
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(token);

        // Decrypt with shared key
        jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));

        // Extract payload
        SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();

        result = signedJWT.getHeader().getJWK();

        RSAKey publicKey = RSAKey.parse(result.toJSONObject());
        if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
            return result;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return null;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:30,代码来源:MCRJSONWebTokenUtil.java


示例6: verifyTokenRSA

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的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


示例7: validateSignature

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
protected boolean validateSignature(SignedJWT jwtToken) {
  boolean valid = false;
  if (JWSObject.State.SIGNED == jwtToken.getState()) {

    if (jwtToken.getSignature() != null) {

      try {
        RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath);
        JWSVerifier verifier = new RSASSAVerifier(publicKey);
        if (verifier != null && jwtToken.verify(verifier)) {
          valid = true;
        }
      } catch (Exception e) {
        LOGGER.info("Exception in validateSignature", e);
      }
    }
  }
  return valid;
}
 
开发者ID:apache,项目名称:zeppelin,代码行数:20,代码来源:KnoxJwtRealm.java


示例8: verifySignature

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
private boolean verifySignature(String jwt) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwt);
        if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) {
            JWSVerifier verifier =
                    new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS));
            return signedJWT.verify(verifier);
        } else {
            log.info("Token has expired");
        }
    } catch (ParseException | IOException | KeyStoreException | CertificateException |
            NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) {
        log.error("Error occurred while JWT signature verification. JWT=" + jwt, e);
    }
    return false;
}
 
开发者ID:wso2,项目名称:msf4j,代码行数:17,代码来源:JWTSecurityInterceptor.java


示例9: extractAppIdFromIdToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
private String extractAppIdFromIdToken(String token) {
    String appId = null;
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        keyStoreManager.getDefaultPrimaryCertificate();
        JWSVerifier verifier =
                new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey());
        SignedJWT jwsObject = SignedJWT.parse(token);
        if (jwsObject.verify(verifier)) {
            appId = jwsObject.getJWTClaimsSet().getStringClaim("appId");
        }

    } catch (Exception e) {
        String message = "Could not extract application id from id token";
        log.error(message, e);
    }
    return appId;
}
 
开发者ID:apache,项目名称:stratos,代码行数:19,代码来源:OAuthHandler.java


示例10: setKeyPair

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
public void setKeyPair(KeyPair keyPair) {
	PrivateKey privateKey = keyPair.getPrivate();
	signer = new RSASSASigner(privateKey);
	RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	verifier = new RSASSAVerifier(publicKey);
	verifierKey = "-----BEGIN PUBLIC KEY-----\n"
			+ Base64Utils.encodeToString(publicKey.getEncoded())
			+ "\n-----END PUBLIC KEY-----";
}
 
开发者ID:making,项目名称:spring-boot-actuator-dashboard,代码行数:10,代码来源:JwtTokenConverter.java


示例11: authenticate

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的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


示例12: retrieveCredential

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的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


示例13: verify

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
@Override
public boolean verify(final SignedJWT jwt) throws JOSEException {
    init();
    CommonHelper.assertNotNull("publicKey", publicKey);

    final JWSVerifier verifier = new RSASSAVerifier(this.publicKey);
    return jwt.verify(verifier);
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:9,代码来源:RSASignatureConfiguration.java


示例14: retrievePublicKeyFromAuthenticationToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 * retrieves the client public key from Authentication Token
 * 
 * @param signedJWT - the authentication token
 * @return the public key as JWK object
 */
public static JWK retrievePublicKeyFromAuthenticationToken(SignedJWT signedJWT) {
    JWK result = null;
    try {
        result = JWK.parse(signedJWT.getJWTClaimsSet().getJSONObjectClaim("sub_jwk"));
        RSAKey publicKey = (RSAKey) signedJWT.getHeader().getJWK();
        if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
            return result;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }

    return null;
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:21,代码来源:MCRJSONWebTokenUtil.java


示例15: retrieveUsernameFromAuthenticationToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 * retrieves the username from Authentication Token
 * 
 * @param signedJWT - the authentication token
 * @return the user name
 */
public static String retrieveUsernameFromAuthenticationToken(SignedJWT signedJWT) {
    try {
        // Extract payload

        RSAKey serverPublicKey = RSAKey.parse(signedJWT.getHeader().getJWK().toJSONObject());
        if (signedJWT.verify(new RSASSAVerifier(serverPublicKey))) {
            //Token is valid
            return signedJWT.getJWTClaimsSet().getSubject();
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return MCRSystemUserInformation.getGuestInstance().getUserID();
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:21,代码来源:MCRJSONWebTokenUtil.java


示例16: retrieveAuthenticationToken

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的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;
    }
}
 
开发者ID:MyCoRe-Org,项目名称:mycore,代码行数:47,代码来源:MCRJSONWebTokenUtil.java


示例17: setJwtProperties

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
private void setJwtProperties() {
    if (jwtProperties != null) {
        authenticationProviderUrl = jwtProperties.getAuthenticationProviderUrl();
        publicKey = jwtProperties.getPublicKey();
        cookieName = jwtProperties.getCookieName();
        originalUrlQueryParam = jwtProperties.getOriginalUrlQueryParam();
        if (publicKey != null) {
            verifier = new RSASSAVerifier(publicKey);
        }
    }
}
 
开发者ID:apache,项目名称:incubator-atlas,代码行数:12,代码来源:AtlasKnoxSSOAuthenticationFilter.java


示例18: assertSignatureValid

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的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


示例19: afterPropertiesSet

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
/**
 * Tries to load the client certificate on initialization
 * @throws Exception
 */
@Override
public void afterPropertiesSet() throws Exception {
    if (this.certService == null ){
        logger.error("Invalid configuration: CertService");
        throw new BeanCreationException("Invalid configuration, CertService not found");
    }
    if (certificatePath==null) {
        logger.error("Invalid configuration: certificate Path not found");
        throw new BeanCreationException("Invalid configuration, certificatePath not found");
    }

    try {
        X509Certificate cert = certService.getCertificateFromInput(certificatePath.getInputStream());

        cn = certService.getName(cert);

        PublicKey publicKey = cert.getPublicKey();

        verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
        verifier.setProvider(new BouncyCastleProvider());


    } catch (Exception exc) {
        logger.error("Couldn't instantiate X.509 certificate", exc);
        throw   new BeanCreationException("Invalid configuration, certificatePath not found", exc);
    }

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


示例20: supports

import com.nimbusds.jose.crypto.RSASSAVerifier; //导入依赖的package包/类
@Override
public boolean supports(final JWSAlgorithm algorithm) {
    return algorithm != null && RSASSAVerifier.SUPPORTED_ALGORITHMS.contains(algorithm);
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:5,代码来源:RSASignatureConfiguration.java



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Duration类代码示例发布时间:2022-05-21
下一篇:
Java FlowLayout类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap