当前位置: 首页>>代码示例>>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;未经允许,请勿转载。