@Test public void clientCredentialsAuthSuccess() throws Exception { oauth.clientId("service-account-cl"); OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1"); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); events .expectClientLogin() .client("service-account-cl") .user(userId) .session(accessToken.getSessionState()) .detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()) .detail( Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl") .assertEvent(); assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); System.out.println("Access token other claims: " + accessToken.getOtherClaims()); Assert.assertEquals( "service-account-cl", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); Assert.assertTrue( accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_ADDRESS)); Assert.assertTrue( accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_HOST)); OAuthClient.AccessTokenResponse refreshedResponse = oauth.doRefreshTokenRequest(response.getRefreshToken(), "secret1"); AccessToken refreshedAccessToken = oauth.verifyToken(refreshedResponse.getAccessToken()); RefreshToken refreshedRefreshToken = oauth.verifyRefreshToken(refreshedResponse.getRefreshToken()); assertEquals(accessToken.getSessionState(), refreshedAccessToken.getSessionState()); assertEquals(accessToken.getSessionState(), refreshedRefreshToken.getSessionState()); events .expectRefresh(refreshToken.getId(), refreshToken.getSessionState()) .user(userId) .client("service-account-cl") .assertEvent(); }
@Test public void clientCredentialsLogout() throws Exception { oauth.clientId("service-account-cl"); OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1"); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); events .expectClientLogin() .client("service-account-cl") .user(userId) .session(accessToken.getSessionState()) .detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()) .detail( Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl") .detail(Details.CLIENT_AUTH_METHOD, ClientIdAndSecretAuthenticator.PROVIDER_ID) .assertEvent(); HttpResponse logoutResponse = oauth.doLogout(response.getRefreshToken(), "secret1"); assertEquals(204, logoutResponse.getStatusLine().getStatusCode()); events .expectLogout(accessToken.getSessionState()) .client("service-account-cl") .user(userId) .removeDetail(Details.REDIRECT_URI) .assertEvent(); response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "secret1"); assertEquals(400, response.getStatusCode()); assertEquals("invalid_grant", response.getError()); events .expectRefresh(refreshToken.getId(), refreshToken.getSessionState()) .client("service-account-cl") .user(userId) .removeDetail(Details.TOKEN_ID) .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID) .error(Errors.INVALID_TOKEN) .assertEvent(); }
@Test public void grantAccessTokenLogout() throws Exception { oauth.clientId("resource-owner"); OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "test-user@localhost", "password"); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); events .expectLogin() .client("resource-owner") .session(accessToken.getSessionState()) .detail(Details.AUTH_METHOD, "oauth_credentials") .detail(Details.RESPONSE_TYPE, "token") .detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()) .removeDetail(Details.CODE_ID) .removeDetail(Details.REDIRECT_URI) .removeDetail(Details.CONSENT) .assertEvent(); HttpResponse logoutResponse = oauth.doLogout(response.getRefreshToken(), "secret"); assertEquals(204, logoutResponse.getStatusLine().getStatusCode()); events .expectLogout(accessToken.getSessionState()) .client("resource-owner") .removeDetail(Details.REDIRECT_URI) .assertEvent(); response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "secret"); assertEquals(400, response.getStatusCode()); assertEquals("invalid_grant", response.getError()); events .expectRefresh(refreshToken.getId(), refreshToken.getSessionState()) .client("resource-owner") .removeDetail(Details.TOKEN_ID) .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID) .error(Errors.INVALID_TOKEN) .assertEvent(); }
private void grantAccessToken(String login) throws Exception { oauth.clientId("resource-owner"); OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", login, "password"); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); events .expectLogin() .client("resource-owner") .user(userId) .session(accessToken.getSessionState()) .detail(Details.AUTH_METHOD, "oauth_credentials") .detail(Details.RESPONSE_TYPE, "token") .detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()) .detail(Details.USERNAME, login) .removeDetail(Details.CODE_ID) .removeDetail(Details.REDIRECT_URI) .removeDetail(Details.CONSENT) .assertEvent(); assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); OAuthClient.AccessTokenResponse refreshedResponse = oauth.doRefreshTokenRequest(response.getRefreshToken(), "secret"); AccessToken refreshedAccessToken = oauth.verifyToken(refreshedResponse.getAccessToken()); RefreshToken refreshedRefreshToken = oauth.verifyRefreshToken(refreshedResponse.getRefreshToken()); assertEquals(accessToken.getSessionState(), refreshedAccessToken.getSessionState()); assertEquals(accessToken.getSessionState(), refreshedRefreshToken.getSessionState()); events .expectRefresh(refreshToken.getId(), refreshToken.getSessionState()) .user(userId) .client("resource-owner") .assertEvent(); }
@Test public void changeClientIdTest() throws Exception { keycloakRule.update( new KeycloakRule.KeycloakSetup() { @Override public void config( RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { ClientModel app = appRealm.getClientByClientId("service-account-cl"); app.setClientId("updated-client"); } }); oauth.clientId("updated-client"); OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1"); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); Assert.assertEquals( "updated-client", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); // Username still same. Client ID changed events .expectClientLogin() .client("updated-client") .user(userId) .session(accessToken.getSessionState()) .detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()) .detail( Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl") .assertEvent(); // Revert change keycloakRule.update( new KeycloakRule.KeycloakSetup() { @Override public void config( RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { ClientModel app = appRealm.getClientByClientId("updated-client"); app.setClientId("service-account-cl"); } }); }
public AccessTokenResponseBuilder generateIDToken() { if (accessToken == null) { throw new IllegalStateException("accessToken not set"); } idToken = new IDToken(); idToken.id(KeycloakModelUtils.generateId()); idToken.subject(accessToken.getSubject()); idToken.audience(client.getClientId()); idToken.issuedNow(); idToken.issuedFor(accessToken.getIssuedFor()); idToken.issuer(accessToken.getIssuer()); idToken.setSessionState(accessToken.getSessionState()); if (realm.getAccessTokenLifespan() > 0) { idToken.expiration(Time.currentTime() + realm.getAccessTokenLifespan()); } transformIDToken( session, idToken, realm, client, userSession.getUser(), userSession, clientSession); return this; }
public AccessTokenResponse build() { if (accessToken != null) { event.detail(Details.TOKEN_ID, accessToken.getId()); } if (refreshToken != null) { if (event.getEvent().getDetails().containsKey(Details.REFRESH_TOKEN_ID)) { event.detail(Details.UPDATED_REFRESH_TOKEN_ID, refreshToken.getId()); } else { event.detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()); } } AccessTokenResponse res = new AccessTokenResponse(); if (idToken != null) { String encodedToken = new JWSBuilder().jsonContent(idToken).rsa256(realm.getPrivateKey()); res.setIdToken(encodedToken); } if (accessToken != null) { String encodedToken = new JWSBuilder().jsonContent(accessToken).rsa256(realm.getPrivateKey()); res.setToken(encodedToken); res.setTokenType("bearer"); res.setSessionState(accessToken.getSessionState()); if (accessToken.getExpiration() != 0) { res.setExpiresIn(accessToken.getExpiration() - Time.currentTime()); } } if (refreshToken != null) { String encodedToken = new JWSBuilder().jsonContent(refreshToken).rsa256(realm.getPrivateKey()); res.setRefreshToken(encodedToken); if (refreshToken.getExpiration() != 0) { res.setRefreshExpiresIn(refreshToken.getExpiration() - Time.currentTime()); } } int notBefore = realm.getNotBefore(); if (client.getNotBefore() > notBefore) notBefore = client.getNotBefore(); res.setNotBeforePolicy(notBefore); return res; }
public TokenValidation validateToken( KeycloakSession session, UriInfo uriInfo, ClientConnection connection, RealmModel realm, AccessToken oldToken, HttpHeaders headers) throws OAuthErrorException { UserModel user = session.users().getUserById(oldToken.getSubject(), realm); if (user == null) { throw new OAuthErrorException( OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown user"); } if (!user.isEnabled()) { throw new OAuthErrorException( OAuthErrorException.INVALID_GRANT, "User disabled", "User disabled"); } UserSessionModel userSession = session.sessions().getUserSession(realm, oldToken.getSessionState()); if (!AuthenticationManager.isSessionValid(realm, userSession)) { AuthenticationManager.backchannelLogout( session, realm, userSession, uriInfo, connection, headers, true); throw new OAuthErrorException( OAuthErrorException.INVALID_GRANT, "Session not active", "Session not active"); } ClientSessionModel clientSession = null; for (ClientSessionModel clientSessionModel : userSession.getClientSessions()) { if (clientSessionModel.getId().equals(oldToken.getClientSession())) { clientSession = clientSessionModel; break; } } if (clientSession == null) { throw new OAuthErrorException( OAuthErrorException.INVALID_GRANT, "Client session not active", "Client session not active"); } ClientModel client = clientSession.getClient(); if (!client.getClientId().equals(oldToken.getIssuedFor())) { throw new OAuthErrorException( OAuthErrorException.INVALID_GRANT, "Unmatching clients", "Unmatching clients"); } if (oldToken.getIssuedAt() < client.getNotBefore()) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token"); } if (oldToken.getIssuedAt() < realm.getNotBefore()) { throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token"); } // recreate token. Set<RoleModel> requestedRoles = TokenManager.getAccess(null, clientSession.getClient(), user); AccessToken newToken = createClientAccessToken( session, requestedRoles, realm, client, user, userSession, clientSession); verifyAccess(oldToken, newToken); return new TokenValidation(user, userSession, clientSession, newToken); }