org.keycloak.jose.jws.JWSInputException Java Examples
The following examples show how to use
org.keycloak.jose.jws.JWSInputException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertxHttpFacade.java From quarkus with Apache License 2.0 | 7 votes |
@Override public KeycloakSecurityContext getSecurityContext() { SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(routingContext, null); if (identity == null) { return null; } TokenCredential credential = identity.getCredential(AccessTokenCredential.class); if (credential == null) { return null; } String token = credential.getToken(); try { return new KeycloakSecurityContext(token, new JWSInput(token).readJsonContent(AccessToken.class), null, null); } catch (JWSInputException e) { throw new RuntimeException("Failed to create access token", e); } }
Example #2
Source File: KeycloakSpringAdapterUtils.java From smartling-keycloak-extras with Apache License 2.0 | 6 votes |
/** * Creates a new {@link RefreshableKeycloakSecurityContext} from the given {@link KeycloakDeployment} and {@link AccessTokenResponse}. * * @param deployment the <code>KeycloakDeployment</code> for which to create a <code>RefreshableKeycloakSecurityContext</code> (required) * @param accessTokenResponse the <code>AccessTokenResponse</code> from which to create a RefreshableKeycloakSecurityContext (required) * * @return a <code>RefreshableKeycloakSecurityContext</code> created from the given <code>accessTokenResponse</code> * @throws VerificationException if the given <code>AccessTokenResponse</code> contains an invalid {@link IDToken} */ public static RefreshableKeycloakSecurityContext createKeycloakSecurityContext(KeycloakDeployment deployment, AccessTokenResponse accessTokenResponse) throws VerificationException { String tokenString = accessTokenResponse.getToken(); String idTokenString = accessTokenResponse.getIdToken(); AccessToken accessToken = RSATokenVerifier .verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl()); IDToken idToken; try { JWSInput input = new JWSInput(idTokenString); idToken = input.readJsonContent(IDToken.class); } catch (JWSInputException e) { throw new VerificationException("Unable to verify ID token", e); } // FIXME: does it make sense to pass null for the token store? return new RefreshableKeycloakSecurityContext(deployment, null, tokenString, accessToken, idTokenString, idToken, accessTokenResponse.getRefreshToken()); }
Example #3
Source File: AbstractShowTokensServlet.java From keycloak with Apache License 2.0 | 6 votes |
protected String renderTokens(HttpServletRequest req) throws ServletException, IOException { RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName()); String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(ctx.getToken()); RefreshToken refreshToken; try { refreshToken = new JWSInput(ctx.getRefreshToken()).readJsonContent(RefreshToken.class); } catch (JWSInputException e) { throw new IOException(e); } String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken); return new StringBuilder("<span id=\"accessToken\">" + accessTokenPretty + "</span>") .append("<span id=\"refreshToken\">" + refreshTokenPretty + "</span>") .append("<span id=\"accessTokenString\">" + ctx.getTokenString() + "</span>") .toString(); }
Example #4
Source File: FixedHostnameTest.java From keycloak with Apache License 2.0 | 6 votes |
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException { ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation(); rep.setCount(1); rep.setExpiration(10000); ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep); JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class); assertEquals(expectedBaseUrl + "/auth/realms/" + realm, token.getIssuer()); ClientRegistration clientReg = ClientRegistration.create().url(authServerUrl, realm).build(); clientReg.auth(Auth.token(initialAccess.getToken())); ClientRepresentation client = new ClientRepresentation(); client.setEnabled(true); ClientRepresentation response = clientReg.create(client); String registrationAccessToken = response.getRegistrationAccessToken(); JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class); assertEquals(expectedBaseUrl + "/auth/realms/" + realm, registrationToken.getIssuer()); }
Example #5
Source File: DefaultHostnameTest.java From keycloak with Apache License 2.0 | 6 votes |
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException { ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation(); rep.setCount(1); rep.setExpiration(10000); ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep); JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class); assertEquals(expectedBaseUrl + "/realms/" + realm, token.getIssuer()); ClientRegistration clientReg = ClientRegistration.create().url(AUTH_SERVER_ROOT, realm).build(); clientReg.auth(Auth.token(initialAccess.getToken())); ClientRepresentation client = new ClientRepresentation(); client.setEnabled(true); ClientRepresentation response = clientReg.create(client); String registrationAccessToken = response.getRegistrationAccessToken(); JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class); assertEquals(expectedBaseUrl + "/realms/" + realm, registrationToken.getIssuer()); }
Example #6
Source File: AssertAdminEvents.java From keycloak with Apache License 2.0 | 5 votes |
private AuthDetailsRepresentation defaultAuthDetails() { String accessTokenString = context.getAdminClient().tokenManager().getAccessTokenString(); try { JWSInput input = new JWSInput(accessTokenString); AccessToken token = input.readJsonContent(AccessToken.class); AuthDetailsRepresentation authDetails = new AuthDetailsRepresentation(); String realmId = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1); authDetails.setRealmId(realmId); authDetails.setUserId(token.getSubject()); return authDetails; } catch (JWSInputException jwe) { throw new RuntimeException(jwe); } }
Example #7
Source File: TokenUtil.java From keycloak with Apache License 2.0 | 5 votes |
/** * Return refresh token or offline token * * @param decodedToken * @return */ public static RefreshToken getRefreshToken(byte[] decodedToken) throws JWSInputException { try { return JsonSerialization.readValue(decodedToken, RefreshToken.class); } catch (IOException e) { throw new JWSInputException(e); } }
Example #8
Source File: OAuthRequestAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
private void logToken(String name, String token) { try { JWSInput jwsInput = new JWSInput(token); String wireString = jwsInput.getWireString(); log.tracef("\t%s: %s", name, wireString.substring(0, wireString.lastIndexOf(".")) + ".signature"); } catch (JWSInputException e) { log.errorf(e, "Failed to parse %s: %s", name, token); } }
Example #9
Source File: AdminRoot.java From keycloak with Apache License 2.0 | 5 votes |
protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) { String tokenString = authManager.extractAuthorizationHeaderToken(headers); if (tokenString == null) throw new NotAuthorizedException("Bearer"); AccessToken token; try { JWSInput input = new JWSInput(tokenString); token = input.readJsonContent(AccessToken.class); } catch (JWSInputException e) { throw new NotAuthorizedException("Bearer token format error"); } String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1); RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(realmName); if (realm == null) { throw new NotAuthorizedException("Unknown realm in token"); } session.getContext().setRealm(realm); AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers); if (authResult == null) { logger.debug("Token not valid"); throw new NotAuthorizedException("Bearer"); } ClientModel client = realm.getClientByClientId(token.getIssuedFor()); if (client == null) { throw new NotFoundException("Could not find client for authorization"); } return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client); }
Example #10
Source File: TokenManager.java From keycloak with Apache License 2.0 | 5 votes |
public RefreshToken toRefreshToken(KeycloakSession session, String encodedRefreshToken) throws JWSInputException, OAuthErrorException { RefreshToken refreshToken = session.tokens().decode(encodedRefreshToken, RefreshToken.class); if (refreshToken == null) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token"); } return refreshToken; }
Example #11
Source File: ExportResourceProvider.java From keycloak-export with GNU Affero General Public License v3.0 | 5 votes |
/** * This code has been copied from keycloak org.keycloak.services.resources.admin.AdminRoot; * it allows to check if a user as realm/master admin * at each upgrade check that it hasn't been modified */ private AdminAuth authenticateRealmAdminRequest(HttpHeaders headers, UriInfo uriInfo) { String tokenString = authManager.extractAuthorizationHeaderToken(headers); if (tokenString == null) throw new NotAuthorizedException("Bearer"); AccessToken token; try { JWSInput input = new JWSInput(tokenString); token = input.readJsonContent(AccessToken.class); } catch (JWSInputException e) { throw new NotAuthorizedException("Bearer token format error", e); } String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1); RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(realmName); if (realm == null) { throw new NotAuthorizedException("Unknown realm in token"); } session.getContext().setRealm(realm); AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers); if (authResult == null) { logger.debug("Token not valid"); throw new NotAuthorizedException("Bearer"); } ClientModel client = realm.getClientByClientId(token.getIssuedFor()); if (client == null) { throw new NotFoundException("Could not find client for authorization"); } return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client); }
Example #12
Source File: KcOidcBrokerNonceParameterTest.java From keycloak with Apache License 2.0 | 5 votes |
protected IDToken toIdToken(String encoded) { IDToken idToken; try { idToken = new JWSInput(encoded).readJsonContent(IDToken.class); } catch (JWSInputException cause) { throw new RuntimeException("Failed to deserialize RPT", cause); } return idToken; }
Example #13
Source File: OfflineAccessPortalServlet.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { if (req.getRequestURI().endsWith("/login")) { storeToken(req); req.getRequestDispatcher("/WEB-INF/pages/loginCallback.jsp").forward(req, resp); return; } String refreshToken = RefreshTokenDAO.loadToken(); String refreshTokenInfo; boolean savedTokenAvailable; if (refreshToken == null) { refreshTokenInfo = "No token saved in database. Please login first"; savedTokenAvailable = false; } else { RefreshToken refreshTokenDecoded = null; refreshTokenDecoded = TokenUtil.getRefreshToken(refreshToken); String exp = (refreshTokenDecoded.getExpiration() == 0) ? "NEVER" : Time.toDate(refreshTokenDecoded.getExpiration()).toString(); refreshTokenInfo = String.format("<p>Type: %s</p><p>ID: %s</p><p>Expires: %s</p>", refreshTokenDecoded.getType(), refreshTokenDecoded.getId(), exp); savedTokenAvailable = true; } req.setAttribute("tokenInfo", refreshTokenInfo); req.setAttribute("savedTokenAvailable", savedTokenAvailable); String customers; if (req.getRequestURI().endsWith("/loadCustomers")) { customers = loadCustomers(req, refreshToken); } else { customers = ""; } req.setAttribute("customers", customers); req.getRequestDispatcher("/WEB-INF/pages/view.jsp").forward(req, resp); } catch (JWSInputException e) { throw new ServletException(e); } }
Example #14
Source File: AbstractAuthzTest.java From keycloak with Apache License 2.0 | 5 votes |
protected AccessToken toAccessToken(String rpt) { AccessToken accessToken; try { accessToken = new JWSInput(rpt).readJsonContent(AccessToken.class); } catch (JWSInputException cause) { throw new RuntimeException("Failed to deserialize RPT", cause); } return accessToken; }
Example #15
Source File: LoginTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void loginSuccessRealmSigningAlgorithms() throws JWSInputException { ContainerAssume.assumeAuthServerSSL(); loginPage.open(); loginPage.login("login-test", "password"); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE)); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); driver.navigate().to(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test/"); String keycloakIdentity = driver.manage().getCookieNamed("KEYCLOAK_IDENTITY").getValue(); // Check identity cookie is signed with HS256 String algorithm = new JWSInput(keycloakIdentity).getHeader().getAlgorithm().name(); assertEquals("HS256", algorithm); try { TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.ES256); oauth.openLoginForm(); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); driver.navigate().to(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/test/"); keycloakIdentity = driver.manage().getCookieNamed("KEYCLOAK_IDENTITY").getValue(); // Check identity cookie is still signed with HS256 algorithm = new JWSInput(keycloakIdentity).getHeader().getAlgorithm().name(); assertEquals("HS256", algorithm); // Check identity cookie still works oauth.openLoginForm(); Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); } finally { TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.RS256); } }
Example #16
Source File: OfflineAccessPortalServlet.java From keycloak with Apache License 2.0 | 5 votes |
private void storeToken(HttpServletRequest req) throws IOException, JWSInputException { RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName()); String refreshToken = ctx.getRefreshToken(); RefreshTokenDAO.saveToken(refreshToken); RefreshToken refreshTokenDecoded = TokenUtil.getRefreshToken(refreshToken); Boolean isOfflineToken = refreshTokenDecoded.getType().equals(TokenUtil.TOKEN_TYPE_OFFLINE); req.setAttribute("isOfflineToken", isOfflineToken); }
Example #17
Source File: PolicyEnforcerClaimsTest.java From keycloak with Apache License 2.0 | 5 votes |
private OIDCHttpFacade createHttpFacade(String path, String method, String token, Map<String, List<String>> headers, Map<String, List<String>> parameters, InputStream requestBody) { return new OIDCHttpFacade() { Request request; Response response; @Override public KeycloakSecurityContext getSecurityContext() { AccessToken accessToken; try { accessToken = new JWSInput(token).readJsonContent(AccessToken.class); } catch (JWSInputException cause) { throw new RuntimeException(cause); } return new KeycloakSecurityContext(token, accessToken, null, null); } @Override public Request getRequest() { if (request == null) { request = createHttpRequest(path, method, headers, parameters, requestBody); } return request; } @Override public Response getResponse() { if (response == null) { response = createHttpResponse(headers); } return response; } @Override public X509Certificate[] getCertificateChain() { return new X509Certificate[0]; } }; }
Example #18
Source File: AccessTokenTest.java From keycloak with Apache License 2.0 | 4 votes |
private IDToken getIdToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException { JWSInput input = new JWSInput(tokenResponse.getIdToken()); return input.readJsonContent(IDToken.class); }
Example #19
Source File: TokenUtil.java From keycloak with Apache License 2.0 | 4 votes |
public static RefreshToken getRefreshToken(String refreshToken) throws JWSInputException { byte[] encodedContent = new JWSInput(refreshToken).getContent(); return getRefreshToken(encodedContent); }
Example #20
Source File: CookieTokenStore.java From keycloak with Apache License 2.0 | 4 votes |
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore) { OIDCHttpFacade.Cookie cookie = facade.getRequest().getCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE); if (cookie == null) { log.debug("Not found adapter state cookie in current request"); return null; } String cookieVal = cookie.getValue(); String[] tokens = cookieVal.split(DELIM); if (tokens.length != 3) { log.warnf("Invalid format of %s cookie. Count of tokens: %s, expected 3", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, tokens.length); return null; } String accessTokenString = tokens[0]; String idTokenString = tokens[1]; String refreshTokenString = tokens[2]; try { // Skip check if token is active now. It's supposed to be done later by the caller TokenVerifier<AccessToken> tokenVerifier = AdapterTokenVerifier.createVerifier(accessTokenString, deployment, true, AccessToken.class) .checkActive(false) .verify(); AccessToken accessToken = tokenVerifier.getToken(); IDToken idToken; if (idTokenString != null && idTokenString.length() > 0) { try { JWSInput input = new JWSInput(idTokenString); idToken = input.readJsonContent(IDToken.class); } catch (JWSInputException e) { throw new VerificationException(e); } } else { idToken = null; } log.debug("Token Verification succeeded!"); RefreshableKeycloakSecurityContext secContext = new RefreshableKeycloakSecurityContext(deployment, tokenStore, accessTokenString, accessToken, idTokenString, idToken, refreshTokenString); return new KeycloakPrincipal<>(AdapterUtils.getPrincipalName(deployment, accessToken), secContext); } catch (VerificationException ve) { log.warn("Failed verify token", ve); return null; } }
Example #21
Source File: OIDCIdentityProvider.java From keycloak with Apache License 2.0 | 4 votes |
protected JsonWebToken validateToken(String encodedToken, boolean ignoreAudience) { if (encodedToken == null) { throw new IdentityBrokerException("No token from server."); } JsonWebToken token; try { JWSInput jws = new JWSInput(encodedToken); if (!verify(jws)) { throw new IdentityBrokerException("token signature validation failed"); } token = jws.readJsonContent(JsonWebToken.class); } catch (JWSInputException e) { throw new IdentityBrokerException("Invalid token", e); } String iss = token.getIssuer(); if (!token.isActive(getConfig().getAllowedClockSkew())) { throw new IdentityBrokerException("Token is no longer valid"); } if (!ignoreAudience && !token.hasAudience(getConfig().getClientId())) { throw new IdentityBrokerException("Wrong audience from token."); } if (!ignoreAudience && (token.getIssuedFor() != null && !getConfig().getClientId().equals(token.getIssuedFor()))) { throw new IdentityBrokerException("Token issued for does not match client id"); } String trustedIssuers = getConfig().getIssuer(); if (trustedIssuers != null && trustedIssuers.length() > 0) { String[] issuers = trustedIssuers.split(","); for (String trustedIssuer : issuers) { if (iss != null && iss.equals(trustedIssuer.trim())) { return token; } } throw new IdentityBrokerException("Wrong issuer from token. Got: " + iss + " expected: " + getConfig().getIssuer()); } return token; }
Example #22
Source File: PolicyEnforcerTest.java From keycloak with Apache License 2.0 | 4 votes |
private OIDCHttpFacade createHttpFacade(String path, String method, String token, Map<String, List<String>> headers, Map<String, List<String>> parameters, InputStream requestBody, KeycloakDeployment deployment, Function<String, String> parameterFunction) { return new OIDCHttpFacade() { Request request; Response response; @Override public KeycloakSecurityContext getSecurityContext() { if (token != null) { AccessToken accessToken; try { accessToken = new JWSInput(token).readJsonContent(AccessToken.class); } catch (JWSInputException cause) { throw new RuntimeException(cause); } return new RefreshableKeycloakSecurityContext(deployment, null, token, accessToken, null, null, null); } return null; } @Override public Request getRequest() { if (request == null) { request = createHttpRequest(path, method, headers, parameters, requestBody, parameterFunction); } return request; } @Override public Response getResponse() { if (response == null) { response = createHttpResponse(headers); } return response; } @Override public X509Certificate[] getCertificateChain() { return new X509Certificate[0]; } }; }
Example #23
Source File: TestSamlApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/saml/k_test_available") public void testAvailable(String data) throws JWSInputException { adminTestAvailabilityAction.add(new JWSInput(data).readJsonContent(TestAvailabilityAction.class)); }
Example #24
Source File: TestSamlApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/saml/k_push_not_before") public void adminPushNotBefore(String data) throws JWSInputException { adminPushNotBeforeActions.add(new JWSInput(data).readJsonContent(PushNotBeforeAction.class)); }
Example #25
Source File: TestSamlApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/saml/k_logout") public void adminLogout(String data) throws JWSInputException { adminLogoutActions.add(new JWSInput(data).readJsonContent(LogoutAction.class)); }
Example #26
Source File: TestApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_test_available") public void testAvailable(String data) throws JWSInputException { adminTestAvailabilityAction.add(new JWSInput(data).readJsonContent(TestAvailabilityAction.class)); }
Example #27
Source File: TestApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_push_not_before") public void adminPushNotBefore(String data) throws JWSInputException { adminPushNotBeforeActions.add(new JWSInput(data).readJsonContent(PushNotBeforeAction.class)); }
Example #28
Source File: TestApplicationResourceProvider.java From keycloak with Apache License 2.0 | 4 votes |
@POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_logout") public void adminLogout(String data) throws JWSInputException { adminLogoutActions.add(new JWSInput(data).readJsonContent(LogoutAction.class)); }
Example #29
Source File: KeyRotationTest.java From keycloak with Apache License 2.0 | 4 votes |
private void assertTokenKid(String expectedKid, String token) throws JWSInputException { assertEquals(expectedKid, new JWSInput(token).getHeader().getKeyId()); }
Example #30
Source File: AccessTokenTest.java From keycloak with Apache License 2.0 | 4 votes |
private AccessToken getAccessToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException { JWSInput input = new JWSInput(tokenResponse.getToken()); return input.readJsonContent(AccessToken.class); }