本文整理匯總了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);
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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");
}
示例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;
}
示例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;
}
示例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;
}
示例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("驗證用戶失敗!");
}
示例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);
}
}