當前位置: 首頁>>代碼示例>>Java>>正文


Java JOSEException類代碼示例

本文整理匯總了Java中com.nimbusds.jose.JOSEException的典型用法代碼示例。如果您正苦於以下問題:Java JOSEException類的具體用法?Java JOSEException怎麽用?Java JOSEException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JOSEException類屬於com.nimbusds.jose包,在下文中一共展示了JOSEException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: readSignedJWT

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
private <T> JWTData<T> readSignedJWT(String data, KeySelector keySelector, Class<T> classType, JWTVerifier verifier) throws ParseException, JOSEException {
    SignedJWT signedJWT = SignedJWT.parse(data);

    String keyID = signedJWT.getHeader().getKeyID();
    Key key = keySelector.selectSecretKey(keyID);
    if (key == null) {
        throw new InvalidJWTException(String.format("No key found for %s", keyID));
    }

    JWSVerifier jwsVerifier = jwsVerifierFactory.createJWSVerifier(signedJWT.getHeader(), key);

    if (!signedJWT.verify(jwsVerifier)) {
        throw new InvalidJWTException("JWT Signature verification failed");
    }

    if (verifier != null) {
        if (!verifier.verify(signedJWT.getHeader(), signedJWT.getJWTClaimsSet())) {
            throw new InvalidJWTException("JWT verification failed");
        }
    }
    MetaJWTData metaJWTData = new MetaJWTData(keyID, signedJWT.getHeader().getCustomParams());

    return readJSONString(signedJWT.getPayload().toString(), classType, metaJWTData);
}
 
開發者ID:atbashEE,項目名稱:atbash-octopus,代碼行數:25,代碼來源:JWTDecoder.java

示例2: retrieveUsernamePasswordFromLoginToken

import com.nimbusds.jose.JOSEException; //導入依賴的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

示例3: selectSecretKey

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
@Override
public <T extends Key> T selectSecretKey(String keyId) {
    try {
        if (keyId.equals(jwk.getKeyID())) {
            if (jwk instanceof SecretJWK) {
                return (T) ((SecretJWK) jwk).toSecretKey();
            }
            if (jwk instanceof AssymetricJWK) {
                return (T) ((AssymetricJWK) jwk).toPublicKey();
            }
            throw new UnsupportedOperationException("JWK not supported " + jwk.getClass().getName());
        }
    } catch (JOSEException e) {
        e.printStackTrace();
        // FIXME
    }
    return null;
}
 
開發者ID:atbashEE,項目名稱:atbash-octopus,代碼行數:19,代碼來源:SingleKeySelector.java

示例4: validateRequest

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
public void validateRequest(AbstractOptionallyIdentifiedRequest request)
		throws InvalidClientException, JOSEException {
	ClientAuthentication clientAuthentication = request.getClientAuthentication();

	OIDCClientInformation client = this.clientRepository
			.findById((clientAuthentication != null) ? clientAuthentication.getClientID() : request.getClientID());

	if (client == null) {
		throw InvalidClientException.BAD_ID;
	}

	if (client.inferClientType() == ClientType.CONFIDENTIAL) {
		if (clientAuthentication == null) {
			throw InvalidClientException.BAD_SECRET;
		}

		ClientAuthenticationVerifier<OIDCClientInformation> verifier = new ClientAuthenticationVerifier<>(
				new ClientInformationCredentialsSelector(), null, Collections.singleton(new Audience(this.issuer)));

		Context<OIDCClientInformation> context = new Context<>();
		context.set(client);
		verifier.verify(clientAuthentication, null, context);
	}
}
 
開發者ID:vpavic,項目名稱:simple-openid-provider,代碼行數:25,代碼來源:ClientRequestValidator.java

示例5: validate

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
@Override
public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException {
    try {
        if (originalIssuer.contains("%7Btenantid%7D")) {
            Object tid = idToken.getJWTClaimsSet().getClaim("tid");
            if (tid == null) {
                throw new BadJWTException("ID token does not contain the 'tid' claim");
            }
            base = new IDTokenValidator(new Issuer(originalIssuer.replace("%7Btenantid%7D", tid.toString())),
                    base.getClientID(), base.getJWSKeySelector(), base.getJWEKeySelector());
            base.setMaxClockSkew(getMaxClockSkew());
        }
    } catch (ParseException e) {
        throw new BadJWTException(e.getMessage(), e);
    }
    return base.validate(idToken, expectedNonce);
}
 
開發者ID:yaochi,項目名稱:pac4j-plus,代碼行數:18,代碼來源:AzureAdIdTokenValidator.java

示例6: getUsername

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
@Override
 public String getUsername(Context ctx) {
 	String[] authTokenHeaderValues = ctx.request().headers().get(AuthUtils.AUTH_HEADER_KEY);
 	if ((authTokenHeaderValues != null) && (authTokenHeaderValues.length == 1) && (authTokenHeaderValues[0] != null)) {
 		String authHeader = authTokenHeaderValues[0];

try {
	JWTClaimsSet claimSet = (JWTClaimsSet) authenticator.decodeToken(authHeader);
	if (new DateTime(claimSet.getExpirationTime()).isAfter(DateTime.now())) {
		return claimSet.getSubject();
	} 
} catch (ParseException | JOSEException e) {
	Logger.error("Erro na validação do token: " + e.getMessage());
}
 	}

     return null;
 }
 
開發者ID:nazareno,項目名稱:diferentonas-server,代碼行數:19,代碼來源:AcessoCidadao.java

示例7: autenticaAdmin

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
@Before
  public void autenticaAdmin() throws JOSEException{
  	
  	admin = app.injector().instanceOf(JPAApi.class).withTransaction(()->{
  		Configuration configuration = app.injector().instanceOf(Configuration.class);
  		String adminEmail = configuration.getString(Cidadao.ADMIN_EMAIL);
  		CidadaoDAO cidadaoDAO = app.injector().instanceOf(CidadaoDAO.class);
  		if(cidadaoDAO.findByLogin(adminEmail) == null){
  			Cidadao cidadao = new Cidadao("Governo Federal", adminEmail);
              cidadao.setFuncionario(true);
              cidadao.setMinisterioDeAfiliacao("Governo Federal");
		return cidadaoDAO.saveAndUpdate(cidadao);
  		}
  		return cidadaoDAO.findByLogin(adminEmail);
  	});
  	
  	AuthUtils authenticator = app.injector().instanceOf(AuthUtils.class);
token = authenticator.createToken("localhost", admin).getToken();
  	builder = new RequestBuilder().header("authorization", "token " + token);
  }
 
開發者ID:nazareno,項目名稱:diferentonas-server,代碼行數:21,代碼來源:WithAuthentication.java

示例8: validateSignature

import com.nimbusds.jose.JOSEException; //導入依賴的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

示例9: getIdToken

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
protected JWT getIdToken(@Nonnull ClientID clientId, @Nullable Nonce nonce, @Nullable AccessTokenHash atHash,
		@Nullable CodeHash cHash) throws GeneralSecurityException, JOSEException, ParseException {
	JWTClaimsSet claims = getIdTokenClaims(clientId, nonce, atHash, cHash);

	RSAKey key = getSigningJwk();

	JWSHeader.Builder headerBuilder = new JWSHeader.Builder(JWSAlgorithm.RS256)
			.type(JOSEObjectType.JWT);
	if (params.getBool(INCLUDE_SIGNING_CERT)) {
		headerBuilder = headerBuilder.jwk(key.toPublicJWK());
	}
	JWSHeader header = headerBuilder.build();

	SignedJWT signedJwt = new SignedJWT(header, claims);

	JWSSigner signer = new RSASSASigner(key);
	signedJwt.sign(signer);

	return signedJwt;
}
 
開發者ID:RUB-NDS,項目名稱:PrOfESSOS,代碼行數:21,代碼來源:AbstractOPImplementation.java

示例10: parseAndVerifyToken

import com.nimbusds.jose.JOSEException; //導入依賴的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

示例11: retrievePublicKeyFromLoginToken

import com.nimbusds.jose.JOSEException; //導入依賴的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

示例12: createEmptyJWTwithPublicKey

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
/**
 * creates an empty JSON Web Token
 * 
 * @param webAppBaseURL - the base url of the application
 * 
 * @return the JSON WebToken
 */
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {

    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
        .issueTime(Date.from(currentTime.toInstant())).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        LOGGER.error(e);
    }
    return signedJWT;

}
 
開發者ID:MyCoRe-Org,項目名稱:mycore,代碼行數:25,代碼來源:MCRJSONWebTokenUtil.java

示例13: createJWT

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
/**
 * creates a JSON Web Token with user id, roles and client public key
 * 
 * @param user - the user that should be returned
 * @param roles - the roles that should be returned
 * @param webAppBaseURL - the base url of the application
 * @param clientPublicKey -  the client public key as JSON Web Key
 * 
 * @return the JSON WebToken
 */
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
        .expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant()))
        .issueTime(Date.from(currentTime.toInstant()))
        .notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user)
        // additional claims/attributes about the subject can be added
        // claims.setClaim("email", "[email protected]");
        // multi-valued claims work too and will end up as a JSON array
        .claim("roles", roles).claim("sub_jwk", clientPublicKey).build();

    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        // TODO Auto-generated catch block
        LOGGER.error(e);
    }
    System.out.println("JWT: " + signedJWT.serialize());
    return signedJWT;
}
 
開發者ID:MyCoRe-Org,項目名稱:mycore,代碼行數:35,代碼來源:MCRJSONWebTokenUtil.java

示例14: login

import com.nimbusds.jose.JOSEException; //導入依賴的package包/類
@RequestMapping(value = "/api/v1/login", method = RequestMethod.POST)
@ResponseBody
public APIResult login(@RequestParam("username") String username,
		@RequestParam("secretkey") String secretkey){
	//測試用,直接判斷
	if("admin".equals(username) && "123".equals(secretkey)){
		JWTUser user = new JWTUser("1",username);
		try {
			APIResult result = new APIResult();
			result.put("token", JWT.newToken(user));
			return result;
		} catch (JOSEException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}
	throw new RuntimeException("驗證用戶失敗!");
}
 
開發者ID:mazhaoyong,項目名稱:api-server-seed,代碼行數:18,代碼來源:JWTController.java

示例15: decryptAndVerify

import com.nimbusds.jose.JOSEException; //導入依賴的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);
    }
}
 
開發者ID:AusDTO,項目名稱:spring-security-stateless,代碼行數:22,代碼來源:JwtEncryption.java


注:本文中的com.nimbusds.jose.JOSEException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。