KEYCLOAK-531 Reduce info level logging

This commit is contained in:
Stian Thorgersen 2014-08-27 11:03:01 +02:00
parent 269a0dbec1
commit 55bd889a0f
20 changed files with 67 additions and 143 deletions

View file

@ -206,7 +206,6 @@ public class RSAVerifierTest {
v = verifySkeletonKeyToken(encoded); v = verifySkeletonKeyToken(encoded);
Assert.fail(); Assert.fail();
} catch (VerificationException ignored) { } catch (VerificationException ignored) {
System.out.println(ignored.getMessage());
} }
} }
@ -225,7 +224,6 @@ public class RSAVerifierTest {
try { try {
v = verifySkeletonKeyToken(encoded); v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) { } catch (VerificationException ignored) {
System.out.println(ignored.getMessage());
} }
} }

View file

@ -24,8 +24,6 @@ public class SkeletonKeyTokenTest {
token.addAccess("bar").addRole("user"); token.addAccess("bar").addRole("user");
String json = JsonSerialization.writeValueAsString(token); String json = JsonSerialization.writeValueAsString(token);
System.out.println(json);
token = JsonSerialization.readValue(json, AccessToken.class); token = JsonSerialization.readValue(json, AccessToken.class);
Assert.assertEquals("111", token.getId()); Assert.assertEquals("111", token.getId());
AccessToken.Access foo = token.getResourceAccess("foo"); AccessToken.Access foo = token.getResourceAccess("foo");
@ -47,8 +45,6 @@ public class SkeletonKeyTokenTest {
.jsonContent(token) .jsonContent(token)
.rsa256(keyPair.getPrivate()); .rsa256(keyPair.getPrivate());
System.out.println(encoded);
JWSInput input = new JWSInput(encoded); JWSInput input = new JWSInput(encoded);
token = input.readJsonContent(AccessToken.class); token = input.readJsonContent(AccessToken.class);

View file

@ -1,5 +1,12 @@
<chapter id="Migration_from_older_versions"> <chapter id="Migration_from_older_versions">
<title>Migration from older versions</title> <title>Migration from older versions</title>
<sect1>
<title>Migrating from 1.0 RC-1 to RC-2</title>
<itemizedlist>
<listitem>A lot of info level logging has been changed to debug. Also, a realm no longer has the jboss-logging audit listener by default.
If you want log output when users login, logout, change passwords, etc. enable the jboss-logging audit listener through the admin console.</listitem>
</itemizedlist>
</sect1>
<sect1> <sect1>
<title>Migrating from 1.0 Beta 4 to RC-1</title> <title>Migrating from 1.0 Beta 4 to RC-1</title>
<itemizedlist> <itemizedlist>

View file

@ -74,7 +74,7 @@ public class KeycloakServletExtension implements ServletExtension {
if (is == null) { if (is == null) {
String path = context.getInitParameter("keycloak.config.file"); String path = context.getInitParameter("keycloak.config.file");
if (path == null) { if (path == null) {
log.info("**** using /WEB-INF/keycloak.json"); log.debug("using /WEB-INF/keycloak.json");
is = context.getResourceAsStream("/WEB-INF/keycloak.json"); is = context.getResourceAsStream("/WEB-INF/keycloak.json");
} else { } else {
try { try {
@ -91,10 +91,10 @@ public class KeycloakServletExtension implements ServletExtension {
@Override @Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) { public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK")) { if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK")) {
log.info("auth-method is not keycloak!"); log.debug("auth-method is not keycloak!");
return; return;
} }
log.info("KeycloakServletException initialization"); log.debug("KeycloakServletException initialization");
InputStream is = getConfigInputStream(servletContext); InputStream is = getConfigInputStream(servletContext);
KeycloakDeployment deployment = null; KeycloakDeployment deployment = null;
if (is == null) { if (is == null) {
@ -139,14 +139,14 @@ public class KeycloakServletExtension implements ServletExtension {
} }
}); });
log.info("Setting jsession cookie path to: " + deploymentInfo.getContextPath()); log.debug("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
ServletSessionConfig cookieConfig = new ServletSessionConfig(); ServletSessionConfig cookieConfig = new ServletSessionConfig();
cookieConfig.setPath(deploymentInfo.getContextPath()); cookieConfig.setPath(deploymentInfo.getContextPath());
deploymentInfo.setServletSessionConfig(cookieConfig); deploymentInfo.setServletSessionConfig(cookieConfig);
} }
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) { protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) {
log.info("creating ServletKeycloakAuthMech"); log.debug("creating ServletKeycloakAuthMech");
return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, deploymentInfo.getConfidentialPortManager()); return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, deploymentInfo.getConfidentialPortManager());
} }
} }

View file

@ -397,7 +397,7 @@ public class RepresentationToModel {
if (resourceRep.getRedirectUris() != null) { if (resourceRep.getRedirectUris() != null) {
Set<String> origins = new HashSet<String>(); Set<String> origins = new HashSet<String>();
for (String redirectUri : resourceRep.getRedirectUris()) { for (String redirectUri : resourceRep.getRedirectUris()) {
logger.info("add redirectUri to origin: " + redirectUri); logger.debugv("add redirect-uri to origin: {0}", redirectUri);
if (redirectUri.startsWith("http:")) { if (redirectUri.startsWith("http:")) {
URI uri = URI.create(redirectUri); URI uri = URI.create(redirectUri);
String origin = uri.getScheme() + "://" + uri.getHost(); String origin = uri.getScheme() + "://" + uri.getHost();

View file

@ -38,7 +38,7 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory {
factories.put(factory.getId(), factory); factories.put(factory.getId(), factory);
log.info("Loaded SPI " + spi.getName() + " (provider = " + provider + ")"); log.debugv("Loaded SPI {0} (provider = {1})", spi.getName(), provider);
} else { } else {
for (ProviderFactory factory : ServiceLoader.load(spi.getProviderFactoryClass())) { for (ProviderFactory factory : ServiceLoader.load(spi.getProviderFactoryClass())) {
Config.Scope scope = Config.scope(spi.getName(), factory.getId()); Config.Scope scope = Config.scope(spi.getName(), factory.getId());
@ -51,9 +51,9 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory {
provider = factories.values().iterator().next().getId(); provider = factories.values().iterator().next().getId();
this.provider.put(spi.getProviderClass(), provider); this.provider.put(spi.getProviderClass(), provider);
log.info("Loaded SPI " + spi.getName() + " (provider = " + provider + ")"); log.debugv("Loaded SPI {0} (provider = {1})", spi.getName(), provider);
} else { } else {
log.info("Loaded SPI " + spi.getName() + " (providers = " + factories.keySet() + ")"); log.debugv("Loaded SPI {0} (providers = {1})", spi.getName(), factories.keySet());
} }
} }
} }

View file

@ -60,8 +60,6 @@ public class ApplianceBootstrap {
realm.setRegistrationAllowed(false); realm.setRegistrationAllowed(false);
KeycloakModelUtils.generateRealmKeys(realm); KeycloakModelUtils.generateRealmKeys(realm);
realm.setAuditListeners(Collections.singleton("jboss-logging"));
UserModel adminUser = session.users().addUser(realm, "admin"); UserModel adminUser = session.users().addUser(realm, "admin");
adminUser.setEnabled(true); adminUser.setEnabled(true);
UserCredentialModel password = new UserCredentialModel(); UserCredentialModel password = new UserCredentialModel();

View file

@ -55,26 +55,19 @@ public class AuthenticationManager {
public static boolean isSessionValid(RealmModel realm, UserSessionModel userSession) { public static boolean isSessionValid(RealmModel realm, UserSessionModel userSession) {
if (userSession == null) { if (userSession == null) {
logger.info("userSession was null"); logger.debug("No user session");
return false; return false;
} }
int currentTime = Time.currentTime(); int currentTime = Time.currentTime();
int max = userSession.getStarted() + realm.getSsoSessionMaxLifespan(); int max = userSession.getStarted() + realm.getSsoSessionMaxLifespan();
boolean valid = userSession != null && userSession.getLastSessionRefresh() + realm.getSsoSessionIdleTimeout() > currentTime && max > currentTime; return userSession != null && userSession.getLastSessionRefresh() + realm.getSsoSessionIdleTimeout() > currentTime && max > currentTime;
if (!valid) {
logger.info("userSession.getLastSessionRefresh(): " + userSession.getLastSessionRefresh());
logger.info("realm.getSsoSessionIdleTimeout(): " + realm.getSsoSessionIdleTimeout());
logger.info("currentTime: " + currentTime);
logger.info("max: " + max);
}
return valid;
} }
public static void logout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection) { public static void logout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection) {
if (userSession == null) return; if (userSession == null) return;
UserModel user = userSession.getUser(); UserModel user = userSession.getUser();
logger.infov("Logging out: {0} ({1})", user.getUsername(), userSession.getId()); logger.debugv("Logging out: {0} ({1})", user.getUsername(), userSession.getId());
session.sessions().removeUserSession(realm, userSession); session.sessions().removeUserSession(realm, userSession);
expireIdentityCookie(realm, uriInfo, connection); expireIdentityCookie(realm, uriInfo, connection);
@ -86,7 +79,6 @@ public class AuthenticationManager {
public AccessToken createIdentityToken(RealmModel realm, UserModel user, UserSessionModel session) { public AccessToken createIdentityToken(RealmModel realm, UserModel user, UserSessionModel session) {
logger.info("createIdentityToken");
AccessToken token = new AccessToken(); AccessToken token = new AccessToken();
token.id(KeycloakModelUtils.generateId()); token.id(KeycloakModelUtils.generateId());
token.issuedNow(); token.issuedNow();
@ -102,17 +94,15 @@ public class AuthenticationManager {
} }
public void createLoginCookie(RealmModel realm, UserModel user, UserSessionModel session, UriInfo uriInfo, ClientConnection connection) { public void createLoginCookie(RealmModel realm, UserModel user, UserSessionModel session, UriInfo uriInfo, ClientConnection connection) {
logger.info("createLoginCookie");
String cookiePath = getIdentityCookiePath(realm, uriInfo); String cookiePath = getIdentityCookiePath(realm, uriInfo);
AccessToken identityToken = createIdentityToken(realm, user, session); AccessToken identityToken = createIdentityToken(realm, user, session);
String encoded = encodeToken(realm, identityToken); String encoded = encodeToken(realm, identityToken);
boolean secureOnly = realm.getSslRequired().isRequired(connection); boolean secureOnly = realm.getSslRequired().isRequired(connection);
logger.debugv("creatingLoginCookie - name: {0} path: {1}", KEYCLOAK_IDENTITY_COOKIE, cookiePath);
int maxAge = NewCookie.DEFAULT_MAX_AGE; int maxAge = NewCookie.DEFAULT_MAX_AGE;
if (session.isRememberMe()) { if (session.isRememberMe()) {
maxAge = realm.getSsoSessionIdleTimeout(); maxAge = realm.getSsoSessionIdleTimeout();
logger.info("createLoginCookie maxAge: " + maxAge);
} }
logger.debugv("Create login cookie - name: {0}, path: {1}, max-age: {2}", KEYCLOAK_IDENTITY_COOKIE, cookiePath, maxAge);
CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true); CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true);
//builder.cookie(new NewCookie(cookieName, encoded, cookiePath, null, null, maxAge, secureOnly));// todo httponly , true); //builder.cookie(new NewCookie(cookieName, encoded, cookiePath, null, null, maxAge, secureOnly));// todo httponly , true);
@ -171,10 +161,9 @@ public class AuthenticationManager {
} }
public AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers, boolean checkActive) { public AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers, boolean checkActive) {
logger.info("authenticateIdentityCookie");
Cookie cookie = headers.getCookies().get(KEYCLOAK_IDENTITY_COOKIE); Cookie cookie = headers.getCookies().get(KEYCLOAK_IDENTITY_COOKIE);
if (cookie == null || "".equals(cookie.getValue())) { if (cookie == null || "".equals(cookie.getValue())) {
logger.infov("authenticateCookie could not find cookie: {0}", KEYCLOAK_IDENTITY_COOKIE); logger.debugv("Could not find cookie: {0}", KEYCLOAK_IDENTITY_COOKIE);
return null; return null;
} }
@ -191,35 +180,31 @@ public class AuthenticationManager {
protected AuthResult verifyIdentityToken(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, boolean checkActive, String tokenString) { protected AuthResult verifyIdentityToken(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, boolean checkActive, String tokenString) {
try { try {
AccessToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getName(), checkActive); AccessToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getName(), checkActive);
logger.info("identity token verified");
if (checkActive) { if (checkActive) {
logger.info("Checking if identity token is active");
if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) { if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) {
logger.info("identity cookie expired"); logger.debug("identity cookie expired");
return null; return null;
} else { } else {
logger.info("token.isActive() : " + token.isActive()); logger.debugv("token not active - active: {0}, issued-at: {1}, not-before: {2}", token.isActive(), token.getIssuedAt(), realm.getNotBefore());
logger.info("token.issuedAt: " + token.getIssuedAt());
logger.info("real.notbefore: " + realm.getNotBefore());
} }
} }
UserModel user = session.users().getUserById(token.getSubject(), realm); UserModel user = session.users().getUserById(token.getSubject(), realm);
if (user == null || !user.isEnabled() ) { if (user == null || !user.isEnabled() ) {
logger.info("Unknown user in identity token"); logger.debug("Unknown user in identity token");
return null; return null;
} }
UserSessionModel userSession = session.sessions().getUserSession(realm, token.getSessionState()); UserSessionModel userSession = session.sessions().getUserSession(realm, token.getSessionState());
if (!isSessionValid(realm, userSession)) { if (!isSessionValid(realm, userSession)) {
if (userSession != null) logout(session, realm, userSession, uriInfo, connection); if (userSession != null) logout(session, realm, userSession, uriInfo, connection);
logger.info("User session not active"); logger.debug("User session not active");
return null; return null;
} }
return new AuthResult(user, userSession, token); return new AuthResult(user, userSession, token);
} catch (VerificationException e) { } catch (VerificationException e) {
logger.info("Failed to verify identity token", e); logger.debug("Failed to verify identity token", e);
} }
return null; return null;
} }
@ -227,7 +212,7 @@ public class AuthenticationManager {
public AuthenticationStatus authenticateForm(KeycloakSession session, ClientConnection clientConnection, RealmModel realm, MultivaluedMap<String, String> formData) { public AuthenticationStatus authenticateForm(KeycloakSession session, ClientConnection clientConnection, RealmModel realm, MultivaluedMap<String, String> formData) {
String username = formData.getFirst(FORM_USERNAME); String username = formData.getFirst(FORM_USERNAME);
if (username == null) { if (username == null) {
logger.warn("Username not provided"); logger.debug("Username not provided");
return AuthenticationStatus.INVALID_USER; return AuthenticationStatus.INVALID_USER;
} }
@ -264,11 +249,11 @@ public class AuthenticationManager {
UserModel user = KeycloakModelUtils.findUserByNameOrEmail(session, realm, username); UserModel user = KeycloakModelUtils.findUserByNameOrEmail(session, realm, username);
if (user == null) { if (user == null) {
logger.warn("User " + username + " not found"); logger.debugv("User {0} not found", username);
return AuthenticationStatus.INVALID_USER; return AuthenticationStatus.INVALID_USER;
} }
if (!checkEnabled(user)) { if (!user.isEnabled()) {
return AuthenticationStatus.ACCOUNT_DISABLED; return AuthenticationStatus.ACCOUNT_DISABLED;
} }
@ -282,7 +267,7 @@ public class AuthenticationManager {
List<UserCredentialModel> credentials = new LinkedList<UserCredentialModel>(); List<UserCredentialModel> credentials = new LinkedList<UserCredentialModel>();
String password = formData.getFirst(CredentialRepresentation.PASSWORD); String password = formData.getFirst(CredentialRepresentation.PASSWORD);
if (password == null) { if (password == null) {
logger.warn("Password not provided"); logger.debug("Password not provided");
return AuthenticationStatus.MISSING_PASSWORD; return AuthenticationStatus.MISSING_PASSWORD;
} }
credentials.add(UserCredentialModel.password(password)); credentials.add(UserCredentialModel.password(password));
@ -290,7 +275,7 @@ public class AuthenticationManager {
if (user.isTotp()) { if (user.isTotp()) {
String token = formData.getFirst(CredentialRepresentation.TOTP); String token = formData.getFirst(CredentialRepresentation.TOTP);
if (token == null) { if (token == null) {
logger.warn("TOTP token not provided"); logger.debug("TOTP token not provided");
return AuthenticationStatus.MISSING_TOTP; return AuthenticationStatus.MISSING_TOTP;
} }
credentials.add(UserCredentialModel.totp(token)); credentials.add(UserCredentialModel.totp(token));
@ -311,7 +296,7 @@ public class AuthenticationManager {
} else if (types.contains(CredentialRepresentation.SECRET)) { } else if (types.contains(CredentialRepresentation.SECRET)) {
String secret = formData.getFirst(CredentialRepresentation.SECRET); String secret = formData.getFirst(CredentialRepresentation.SECRET);
if (secret == null) { if (secret == null) {
logger.warn("Secret not provided"); logger.debug("Secret not provided");
return AuthenticationStatus.MISSING_PASSWORD; return AuthenticationStatus.MISSING_PASSWORD;
} }
if (!session.users().validCredentials(realm, user, UserCredentialModel.secret(secret))) { if (!session.users().validCredentials(realm, user, UserCredentialModel.secret(secret))) {
@ -328,15 +313,6 @@ public class AuthenticationManager {
} }
} }
private boolean checkEnabled(UserModel user) {
if (!user.isEnabled()) {
logger.warn("AccountProvider is disabled, contact admin. " + user.getUsername());
return false;
} else {
return true;
}
}
public enum AuthenticationStatus { public enum AuthenticationStatus {
SUCCESS, ACCOUNT_TEMPORARILY_DISABLED, ACCOUNT_DISABLED, ACTIONS_REQUIRED, INVALID_USER, INVALID_CREDENTIALS, MISSING_PASSWORD, MISSING_TOTP, FAILED SUCCESS, ACCOUNT_TEMPORARILY_DISABLED, ACCOUNT_DISABLED, ACTIONS_REQUIRED, INVALID_USER, INVALID_CREDENTIALS, MISSING_PASSWORD, MISSING_TOTP, FAILED
} }

View file

@ -86,8 +86,6 @@ public class RealmManager {
setupAccountManagement(realm); setupAccountManagement(realm);
setupAdminConsole(realm); setupAdminConsole(realm);
realm.setAuditListeners(Collections.singleton("jboss-logging"));
return realm; return realm;
} }
@ -226,11 +224,6 @@ public class RealmManager {
RepresentationToModel.importRealm(session, rep, realm); RepresentationToModel.importRealm(session, rep, realm);
if (realm.getAuditListeners().size() == 0) {
realm.setAuditListeners(Collections.singleton("jboss-logging"));
}
// Refresh periodic sync tasks for configured federationProviders // Refresh periodic sync tasks for configured federationProviders
List<UserFederationProviderModel> federationProviders = realm.getUserFederationProviders(); List<UserFederationProviderModel> federationProviders = realm.getUserFederationProviders();
UsersSyncManager usersSyncManager = new UsersSyncManager(); UsersSyncManager usersSyncManager = new UsersSyncManager();

View file

@ -59,7 +59,7 @@ public class ResourceAdminManager {
SessionStatsAction adminAction = new SessionStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName()); SessionStatsAction adminAction = new SessionStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName());
adminAction.setListUsers(users); adminAction.setListUsers(users);
String token = new TokenManager().encodeToken(realm, adminAction); String token = new TokenManager().encodeToken(realm, adminAction);
logger.infov("session stats for application: {0} url: {1}", application.getName(), managementUrl); logger.debugv("session stats for application: {0} url: {1}", application.getName(), managementUrl);
ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_GET_SESSION_STATS).build().toString()); ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_GET_SESSION_STATS).build().toString());
ClientResponse<SessionStats> response = null; ClientResponse<SessionStats> response = null;
try { try {
@ -90,7 +90,7 @@ public class ResourceAdminManager {
response.releaseConnection(); response.releaseConnection();
} }
} else { } else {
logger.info("no management url."); logger.debug("no management url.");
return null; return null;
} }
@ -121,7 +121,7 @@ public class ResourceAdminManager {
if (managementUrl != null) { if (managementUrl != null) {
UserStatsAction adminAction = new UserStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName(), user.getId()); UserStatsAction adminAction = new UserStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName(), user.getId());
String token = new TokenManager().encodeToken(realm, adminAction); String token = new TokenManager().encodeToken(realm, adminAction);
logger.infov("session stats for application: {0} url: {1}", application.getName(), managementUrl); logger.debugv("session stats for application: {0} url: {1}", application.getName(), managementUrl);
ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_GET_USER_STATS).build().toString()); ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_GET_USER_STATS).build().toString());
ClientResponse<UserStats> response = null; ClientResponse<UserStats> response = null;
try { try {
@ -141,7 +141,7 @@ public class ResourceAdminManager {
response.releaseConnection(); response.releaseConnection();
} }
} else { } else {
logger.info("no management url."); logger.debug("no management url.");
return null; return null;
} }
@ -210,7 +210,7 @@ public class ResourceAdminManager {
if (managementUrl != null) { if (managementUrl != null) {
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), user, session, notBefore); LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), user, session, notBefore);
String token = new TokenManager().encodeToken(realm, adminAction); String token = new TokenManager().encodeToken(realm, adminAction);
logger.infov("logout user: {0} resource: {1} url: {2}", user, resource.getName(), managementUrl); logger.debugv("logout user: {0} resource: {1} url: {2}", user, resource.getName(), managementUrl);
ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_LOGOUT).build().toString()); ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_LOGOUT).build().toString());
ClientResponse response; ClientResponse response;
try { try {
@ -220,13 +220,13 @@ public class ResourceAdminManager {
} }
try { try {
boolean success = response.getStatus() == 204; boolean success = response.getStatus() == 204;
logger.info("logout success."); logger.debug("logout success.");
return success; return success;
} finally { } finally {
response.releaseConnection(); response.releaseConnection();
} }
} else { } else {
logger.info("Can't logout " + resource.getName() + " no mgmt url."); logger.debugv("Can't logout {0}: no management url", resource.getName());
return false; return false;
} }
} }
@ -260,7 +260,7 @@ public class ResourceAdminManager {
if (managementUrl != null) { if (managementUrl != null) {
PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), notBefore); PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), notBefore);
String token = new TokenManager().encodeToken(realm, adminAction); String token = new TokenManager().encodeToken(realm, adminAction);
logger.infov("pushRevocation resource: {0} url: {1}", resource.getName(), managementUrl); logger.debugv("pushRevocation resource: {0} url: {1}", resource.getName(), managementUrl);
ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_PUSH_NOT_BEFORE).build().toString()); ClientRequest request = client.createRequest(UriBuilder.fromUri(managementUrl).path(AdapterConstants.K_PUSH_NOT_BEFORE).build().toString());
ClientResponse response = null; ClientResponse response = null;
try { try {
@ -271,13 +271,13 @@ public class ResourceAdminManager {
try { try {
boolean success = response.getStatus() == 204; boolean success = response.getStatus() == 204;
logger.info("pushRevocation success."); logger.debug("pushRevocation success.");
return success; return success;
} finally { } finally {
response.releaseConnection(); response.releaseConnection();
} }
} else { } else {
logger.info("no management URL for application: " + resource.getName()); logger.debug("no management URL for application: " + resource.getName());
return false; return false;
} }

View file

@ -586,7 +586,7 @@ public class AccountService {
if (session.users().getSocialLinks(user, realm).size() > 1 || user.getFederationLink() != null) { if (session.users().getSocialLinks(user, realm).size() > 1 || user.getFederationLink() != null) {
session.users().removeSocialLink(realm, user, providerId); session.users().removeSocialLink(realm, user, providerId);
logger.debug("Social provider " + providerId + " removed successfully from user " + user.getUsername()); logger.debugv("Social provider {0} removed successfully from user {1}", providerId, user.getUsername());
audit.event(EventType.REMOVE_SOCIAL_LINK).client(auth.getClient()).user(auth.getUser()) audit.event(EventType.REMOVE_SOCIAL_LINK).client(auth.getClient()).user(auth.getUser())
.detail(Details.USERNAME, link.getSocialUserId() + "@" + link.getSocialProvider()) .detail(Details.USERNAME, link.getSocialUserId() + "@" + link.getSocialProvider())
@ -603,9 +603,7 @@ public class AccountService {
return account.setError(Messages.SOCIAL_LINK_NOT_ACTIVE).createResponse(AccountPages.SOCIAL); return account.setError(Messages.SOCIAL_LINK_NOT_ACTIVE).createResponse(AccountPages.SOCIAL);
} }
default: default:
// Shouldn't happen throw new IllegalArgumentException();
logger.warn("Action is null!");
return null;
} }
} }

View file

@ -129,18 +129,17 @@ public class Cors {
return builder.build(); return builder.build();
} }
public void build(HttpResponse response) { public void build(HttpResponse response) {
logger.info("build CORS");
String origin = request.getHttpHeaders().getRequestHeaders().getFirst(ORIGIN_HEADER); String origin = request.getHttpHeaders().getRequestHeaders().getFirst(ORIGIN_HEADER);
if (origin == null) { if (origin == null) {
logger.info("No origin returning"); logger.debug("No origin returning");
return; return;
} }
if (!preflight && (allowedOrigins == null || !allowedOrigins.contains(origin))) { if (!preflight && (allowedOrigins == null || !allowedOrigins.contains(origin))) {
logger.info("!preflight and no origin"); logger.debug("!preflight and no origin");
return; return;
} }
logger.info("build CORS headers and return"); logger.debug("build CORS headers and return");
response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_ORIGIN, origin); response.getOutputHeaders().add(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
if (allowedMethods != null) { if (allowedMethods != null) {

View file

@ -92,10 +92,8 @@ public class RealmsResource {
public String getLoginStatusIframe(final @PathParam("realm") String name, public String getLoginStatusIframe(final @PathParam("realm") String name,
@QueryParam("client_id") String client_id, @QueryParam("client_id") String client_id,
@QueryParam("origin") String origin) { @QueryParam("origin") String origin) {
logger.info("getLoginStatusIframe");
AuthenticationManager auth = new AuthenticationManager(); AuthenticationManager auth = new AuthenticationManager();
//logger.info("getting login-status-iframe.html for client_id: " + client_id);
RealmManager realmManager = new RealmManager(session); RealmManager realmManager = new RealmManager(session);
RealmModel realm = locateRealm(name, realmManager); RealmModel realm = locateRealm(name, realmManager);
ClientModel client = realm.findClient(client_id); ClientModel client = realm.findClient(client_id);

View file

@ -69,6 +69,7 @@ import java.util.concurrent.TimeUnit;
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/ */
public class RequiredActionsService { public class RequiredActionsService {
protected static final Logger logger = Logger.getLogger(RequiredActionsService.class); protected static final Logger logger = Logger.getLogger(RequiredActionsService.class);
private RealmModel realm; private RealmModel realm;
@ -180,13 +181,10 @@ public class RequiredActionsService {
@POST @POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updatePassword(final MultivaluedMap<String, String> formData) { public Response updatePassword(final MultivaluedMap<String, String> formData) {
logger.debug("updatePassword");
AccessCode accessCode = getAccessCodeEntry(RequiredAction.UPDATE_PASSWORD); AccessCode accessCode = getAccessCodeEntry(RequiredAction.UPDATE_PASSWORD);
if (accessCode == null) { if (accessCode == null) {
logger.debug("updatePassword access code is null");
return unauthorized(); return unauthorized();
} }
logger.debug("updatePassword has access code");
UserModel user = getUser(accessCode); UserModel user = getUser(accessCode);
@ -208,8 +206,6 @@ public class RequiredActionsService {
return loginForms.setError(ape.getMessage()).createResponse(RequiredAction.UPDATE_PASSWORD); return loginForms.setError(ape.getMessage()).createResponse(RequiredAction.UPDATE_PASSWORD);
} }
logger.debug("updatePassword updated credential");
user.removeRequiredAction(RequiredAction.UPDATE_PASSWORD); user.removeRequiredAction(RequiredAction.UPDATE_PASSWORD);
audit.clone().event(EventType.UPDATE_PASSWORD).success(); audit.clone().event(EventType.UPDATE_PASSWORD).success();
@ -306,7 +302,6 @@ public class RequiredActionsService {
} }
if (user == null) { if (user == null) {
logger.warn("Failed to send password reset email: user not found");
audit.error(Errors.USER_NOT_FOUND); audit.error(Errors.USER_NOT_FOUND);
} else { } else {
UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false); UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), "form", false);
@ -337,19 +332,18 @@ public class RequiredActionsService {
private AccessCode getAccessCodeEntry(RequiredAction requiredAction) { private AccessCode getAccessCodeEntry(RequiredAction requiredAction) {
String code = uriInfo.getQueryParameters().getFirst(OAuth2Constants.CODE); String code = uriInfo.getQueryParameters().getFirst(OAuth2Constants.CODE);
if (code == null) { if (code == null) {
logger.debug("getAccessCodeEntry code as not in query param"); logger.debug("Code query param not found");
return null; return null;
} }
AccessCode accessCode = AccessCode.parse(code, session, realm); AccessCode accessCode = AccessCode.parse(code, session, realm);
if (accessCode == null) { if (accessCode == null) {
logger.debug("getAccessCodeEntry access code entry null"); logger.debug("Access code not found");
return null; return null;
} }
if (!accessCode.isValid(requiredAction)) { if (!accessCode.isValid(requiredAction)) {
logger.debugv("getAccessCodeEntry: access code id: {0}", accessCode.getCodeId()); logger.debugv("Invalid access code");
logger.debugv("getAccessCodeEntry access code not valid");
return null; return null;
} }
@ -371,7 +365,7 @@ public class RequiredActionsService {
return Flows.forms(session, realm, null, uriInfo).setAccessCode(accessCode.getCode()).setUser(user) return Flows.forms(session, realm, null, uriInfo).setAccessCode(accessCode.getCode()).setUser(user)
.createResponse(requiredActions.iterator().next()); .createResponse(requiredActions.iterator().next());
} else { } else {
logger.debugv("redirectOauth: redirecting to: {0}", accessCode.getRedirectUri()); logger.debugv("Redirecting to: {0}", accessCode.getRedirectUri());
accessCode.setAction(ClientSessionModel.Action.CODE_TO_TOKEN); accessCode.setAction(ClientSessionModel.Action.CODE_TO_TOKEN);
AuthenticationManager authManager = new AuthenticationManager(); AuthenticationManager authManager = new AuthenticationManager();

View file

@ -70,7 +70,6 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import java.io.IOException; import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -113,7 +112,7 @@ public class SocialResource {
try { try {
initialRequest = new JWSInput(encodedState).readJsonContent(State.class); initialRequest = new JWSInput(encodedState).readJsonContent(State.class);
} catch (Throwable t) { } catch (Throwable t) {
logger.warn("Invalid social callback", t); logger.error("Invalid social callback", t);
return Flows.forms(session, null, null, uriInfo).setError("Unexpected callback").createErrorPage(); return Flows.forms(session, null, null, uriInfo).setError("Unexpected callback").createErrorPage();
} }
@ -218,7 +217,7 @@ public class SocialResource {
} }
session.users().addSocialLink(realm, authenticatedUser, socialLink); session.users().addSocialLink(realm, authenticatedUser, socialLink);
logger.debug("Social provider " + provider.getId() + " linked with user " + authenticatedUser.getUsername()); logger.debugv("Social provider {0} linked with user {1}", provider.getId(), authenticatedUser.getUsername());
audit.success(); audit.success();
return Response.status(302).location(UriBuilder.fromUri(redirectUri).build()).build(); return Response.status(302).location(UriBuilder.fromUri(redirectUri).build()).build();
@ -291,13 +290,11 @@ public class SocialResource {
ClientModel client = realm.findClient(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
audit.error(Errors.CLIENT_NOT_FOUND); audit.error(Errors.CLIENT_NOT_FOUND);
logger.warn("Unknown login requester: " + clientId);
return Flows.forms(session, realm, null, uriInfo).setError("Unknown login requester.").createErrorPage(); return Flows.forms(session, realm, null, uriInfo).setError("Unknown login requester.").createErrorPage();
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
audit.error(Errors.CLIENT_DISABLED); audit.error(Errors.CLIENT_DISABLED);
logger.warn("Login requester not enabled.");
return Flows.forms(session, realm, null, uriInfo).setError("Login requester not enabled.").createErrorPage(); return Flows.forms(session, realm, null, uriInfo).setError("Login requester not enabled.").createErrorPage();
} }
redirectUri = TokenService.verifyRedirectUri(uriInfo, redirectUri, realm, client); redirectUri = TokenService.verifyRedirectUri(uriInfo, redirectUri, realm, client);

View file

@ -420,7 +420,6 @@ public class TokenService {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response refreshAccessToken(final @HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, public Response refreshAccessToken(final @HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader,
final MultivaluedMap<String, String> form) { final MultivaluedMap<String, String> form) {
logger.info("--> refreshAccessToken");
if (!checkSsl()) { if (!checkSsl()) {
return createError("https_required", "HTTPS required", Response.Status.FORBIDDEN); return createError("https_required", "HTTPS required", Response.Status.FORBIDDEN);
} }
@ -434,7 +433,6 @@ public class TokenService {
error.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_REQUEST); error.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_REQUEST);
error.put(OAuth2Constants.ERROR_DESCRIPTION, "No refresh token"); error.put(OAuth2Constants.ERROR_DESCRIPTION, "No refresh token");
audit.error(Errors.INVALID_TOKEN); audit.error(Errors.INVALID_TOKEN);
logger.error("OAuth Error: no refresh token");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build(); return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
} }
AccessToken accessToken; AccessToken accessToken;
@ -445,7 +443,6 @@ public class TokenService {
error.put(OAuth2Constants.ERROR, e.getError()); error.put(OAuth2Constants.ERROR, e.getError());
if (e.getDescription() != null) error.put(OAuth2Constants.ERROR_DESCRIPTION, e.getDescription()); if (e.getDescription() != null) error.put(OAuth2Constants.ERROR_DESCRIPTION, e.getDescription());
audit.error(Errors.INVALID_TOKEN); audit.error(Errors.INVALID_TOKEN);
logger.error("OAuth Error", e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build(); return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
} }
@ -475,13 +472,10 @@ public class TokenService {
public Response processLogin(@QueryParam("client_id") final String clientId, @QueryParam("scope") final String scopeParam, public Response processLogin(@QueryParam("client_id") final String clientId, @QueryParam("scope") final String scopeParam,
@QueryParam("state") final String state, @QueryParam("redirect_uri") String redirect, @QueryParam("state") final String state, @QueryParam("redirect_uri") String redirect,
final MultivaluedMap<String, String> formData) { final MultivaluedMap<String, String> formData) {
logger.debug("TokenService.processLogin");
String username = formData.getFirst(AuthenticationManager.FORM_USERNAME); String username = formData.getFirst(AuthenticationManager.FORM_USERNAME);
String rememberMe = formData.getFirst("rememberMe"); String rememberMe = formData.getFirst("rememberMe");
boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on"); boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on");
logger.debug("*** Remember me: " + remember);
audit.event(EventType.LOGIN).client(clientId) audit.event(EventType.LOGIN).client(clientId)
.detail(Details.REDIRECT_URI, redirect) .detail(Details.REDIRECT_URI, redirect)
@ -600,19 +594,16 @@ public class TokenService {
OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager); OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager);
if (!realm.isEnabled()) { if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
audit.error(Errors.REALM_DISABLED); audit.error(Errors.REALM_DISABLED);
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
ClientModel client = realm.findClient(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester.");
audit.error(Errors.CLIENT_NOT_FOUND); audit.error(Errors.CLIENT_NOT_FOUND);
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
audit.error(Errors.CLIENT_DISABLED); audit.error(Errors.CLIENT_DISABLED);
return oauth.forwardToSecurityFailure("Login requester not enabled."); return oauth.forwardToSecurityFailure("Login requester not enabled.");
} }
@ -624,7 +615,6 @@ public class TokenService {
} }
if (!realm.isRegistrationAllowed()) { if (!realm.isRegistrationAllowed()) {
logger.warn("Registration not allowed");
audit.error(Errors.REGISTRATION_DISABLED); audit.error(Errors.REGISTRATION_DISABLED);
return oauth.forwardToSecurityFailure("Registration not allowed"); return oauth.forwardToSecurityFailure("Registration not allowed");
} }
@ -695,7 +685,9 @@ public class TokenService {
@OPTIONS @OPTIONS
@Produces("application/json") @Produces("application/json")
public Response accessCodeToTokenPreflight() { public Response accessCodeToTokenPreflight() {
if (logger.isDebugEnabled()) {
logger.debugv("cors request from: {0}", request.getHttpHeaders().getRequestHeaders().getFirst("Origin")); logger.debugv("cors request from: {0}", request.getHttpHeaders().getRequestHeaders().getFirst("Origin"));
}
return Cors.add(request, Response.ok()).auth().preflight().build(); return Cors.add(request, Response.ok()).auth().preflight().build();
} }
@ -712,8 +704,6 @@ public class TokenService {
@POST @POST
@Produces("application/json") @Produces("application/json")
public Response accessCodeToToken(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, final MultivaluedMap<String, String> formData) { public Response accessCodeToToken(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, final MultivaluedMap<String, String> formData) {
logger.debug("accessRequest <---");
if (!checkSsl()) { if (!checkSsl()) {
throw new ForbiddenException("HTTPS required"); throw new ForbiddenException("HTTPS required");
} }
@ -806,8 +796,6 @@ public class TokenService {
.build(); .build();
} }
logger.debug("accessRequest SUCCESS");
AccessToken token = tokenManager.createClientAccessToken(accessCode.getRequestedRoles(), realm, client, user, userSession); AccessToken token = tokenManager.createClientAccessToken(accessCode.getRequestedRoles(), realm, client, user, userSession);
try { try {
@ -841,7 +829,6 @@ public class TokenService {
client_id = usernameSecret[0]; client_id = usernameSecret[0];
clientSecret = usernameSecret[1]; clientSecret = usernameSecret[1];
} else { } else {
logger.info("no authorization header");
client_id = formData.getFirst(OAuth2Constants.CLIENT_ID); client_id = formData.getFirst(OAuth2Constants.CLIENT_ID);
clientSecret = formData.getFirst("client_secret"); clientSecret = formData.getFirst("client_secret");
} }
@ -911,8 +898,6 @@ public class TokenService {
@QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId, @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state, final @QueryParam("prompt") String prompt, final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state, final @QueryParam("prompt") String prompt,
final @QueryParam("login_hint") String loginHint) { final @QueryParam("login_hint") String loginHint) {
logger.info("TokenService.loginPage");
audit.event(EventType.LOGIN).client(clientId).detail(Details.REDIRECT_URI, redirect).detail(Details.RESPONSE_TYPE, "code"); audit.event(EventType.LOGIN).client(clientId).detail(Details.REDIRECT_URI, redirect).detail(Details.RESPONSE_TYPE, "code");
OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager); OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager);
@ -922,19 +907,16 @@ public class TokenService {
} }
if (!realm.isEnabled()) { if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
audit.error(Errors.REALM_DISABLED); audit.error(Errors.REALM_DISABLED);
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
ClientModel client = realm.findClient(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester: " + clientId);
audit.error(Errors.CLIENT_NOT_FOUND); audit.error(Errors.CLIENT_NOT_FOUND);
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
audit.error(Errors.CLIENT_DISABLED); audit.error(Errors.CLIENT_DISABLED);
return oauth.forwardToSecurityFailure("Login requester not enabled."); return oauth.forwardToSecurityFailure("Login requester not enabled.");
} }
@ -952,13 +934,11 @@ public class TokenService {
return oauth.forwardToSecurityFailure("Invalid redirect_uri."); return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
} }
logger.info("Checking cookie...");
AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm, uriInfo, clientConnection, headers); AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm, uriInfo, clientConnection, headers);
if (authResult != null) { if (authResult != null) {
UserModel user = authResult.getUser(); UserModel user = authResult.getUser();
UserSessionModel session = authResult.getSession(); UserSessionModel session = authResult.getSession();
logger.debug(user.getUsername() + " already logged in.");
audit.user(user).session(session).detail(Details.AUTH_METHOD, "sso"); audit.user(user).session(session).detail(Details.AUTH_METHOD, "sso");
return oauth.processAccessCode(scopeParam, state, redirect, client, user, session, audit); return oauth.processAccessCode(scopeParam, state, redirect, client, user, session, audit);
} }
@ -994,8 +974,6 @@ public class TokenService {
public Response registerPage(final @QueryParam("response_type") String responseType, public Response registerPage(final @QueryParam("response_type") String responseType,
@QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId, @QueryParam("redirect_uri") String redirect, final @QueryParam("client_id") String clientId,
final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state) { final @QueryParam("scope") String scopeParam, final @QueryParam("state") String state) {
logger.info("**********registerPage()");
audit.event(EventType.REGISTER).client(clientId).detail(Details.REDIRECT_URI, redirect).detail(Details.RESPONSE_TYPE, "code"); audit.event(EventType.REGISTER).client(clientId).detail(Details.REDIRECT_URI, redirect).detail(Details.RESPONSE_TYPE, "code");
OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager); OAuthFlows oauth = Flows.oauth(session, realm, request, uriInfo, clientConnection, authManager, tokenManager);
@ -1005,19 +983,16 @@ public class TokenService {
} }
if (!realm.isEnabled()) { if (!realm.isEnabled()) {
logger.warn("Realm not enabled");
audit.error(Errors.REALM_DISABLED); audit.error(Errors.REALM_DISABLED);
return oauth.forwardToSecurityFailure("Realm not enabled"); return oauth.forwardToSecurityFailure("Realm not enabled");
} }
ClientModel client = realm.findClient(clientId); ClientModel client = realm.findClient(clientId);
if (client == null) { if (client == null) {
logger.warn("Unknown login requester.");
audit.error(Errors.CLIENT_NOT_FOUND); audit.error(Errors.CLIENT_NOT_FOUND);
return oauth.forwardToSecurityFailure("Unknown login requester."); return oauth.forwardToSecurityFailure("Unknown login requester.");
} }
if (!client.isEnabled()) { if (!client.isEnabled()) {
logger.warn("Login requester not enabled.");
audit.error(Errors.CLIENT_DISABLED); audit.error(Errors.CLIENT_DISABLED);
return oauth.forwardToSecurityFailure("Login requester not enabled."); return oauth.forwardToSecurityFailure("Login requester not enabled.");
} }
@ -1029,7 +1004,6 @@ public class TokenService {
} }
if (!realm.isRegistrationAllowed()) { if (!realm.isRegistrationAllowed()) {
logger.warn("Registration not allowed");
audit.error(Errors.REGISTRATION_DISABLED); audit.error(Errors.REGISTRATION_DISABLED);
return oauth.forwardToSecurityFailure("Registration not allowed"); return oauth.forwardToSecurityFailure("Registration not allowed");
} }
@ -1092,7 +1066,6 @@ public class TokenService {
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response logoutToken(final @HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, public Response logoutToken(final @HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader,
final MultivaluedMap<String, String> form) { final MultivaluedMap<String, String> form) {
logger.info("--> logoutToken");
if (!checkSsl()) { if (!checkSsl()) {
throw new NotAcceptableException("HTTPS required"); throw new NotAcceptableException("HTTPS required");
} }
@ -1106,7 +1079,6 @@ public class TokenService {
error.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_REQUEST); error.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_REQUEST);
error.put(OAuth2Constants.ERROR_DESCRIPTION, "No refresh token"); error.put(OAuth2Constants.ERROR_DESCRIPTION, "No refresh token");
audit.error(Errors.INVALID_TOKEN); audit.error(Errors.INVALID_TOKEN);
logger.error("OAuth Error: no refresh token");
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build(); return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
} }
try { try {
@ -1120,7 +1092,6 @@ public class TokenService {
error.put(OAuth2Constants.ERROR, e.getError()); error.put(OAuth2Constants.ERROR, e.getError());
if (e.getDescription() != null) error.put(OAuth2Constants.ERROR_DESCRIPTION, e.getDescription()); if (e.getDescription() != null) error.put(OAuth2Constants.ERROR_DESCRIPTION, e.getDescription());
audit.error(Errors.INVALID_TOKEN); audit.error(Errors.INVALID_TOKEN);
logger.error("OAuth Error", e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build(); return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
} }
return Cors.add(request, Response.noContent()).auth().allowedOrigins(client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build(); return Cors.add(request, Response.noContent()).auth().allowedOrigins(client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
@ -1263,13 +1234,12 @@ public class TokenService {
} }
redirectUri = validRedirect; redirectUri = validRedirect;
} else if (validRedirects.isEmpty()) { } else if (validRedirects.isEmpty()) {
logger.error("No Redirect URIs supplied"); logger.debug("No Redirect URIs supplied");
redirectUri = null; redirectUri = null;
} else { } else {
String r = redirectUri.indexOf('?') != -1 ? redirectUri.substring(0, redirectUri.indexOf('?')) : redirectUri; String r = redirectUri.indexOf('?') != -1 ? redirectUri.substring(0, redirectUri.indexOf('?')) : redirectUri;
Set<String> resolveValidRedirects = resolveValidRedirects(uriInfo, validRedirects); Set<String> resolveValidRedirects = resolveValidRedirects(uriInfo, validRedirects);
boolean valid = matchesRedirects(resolveValidRedirects, r); boolean valid = matchesRedirects(resolveValidRedirects, r);
if (!valid && r.startsWith(Constants.INSTALLED_APP_URL) && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) { if (!valid && r.startsWith(Constants.INSTALLED_APP_URL) && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) {

View file

@ -200,11 +200,11 @@ public class AdminConsole {
throw new NotFoundException("No realm found"); throw new NotFoundException("No realm found");
boolean createRealm = false; boolean createRealm = false;
if (realm.equals(masterRealm)) { if (realm.equals(masterRealm)) {
logger.info("setting up realm access for a master realm user"); logger.debug("setting up realm access for a master realm user");
createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM)); createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
addMasterRealmAccess(realm, user, realmAccess); addMasterRealmAccess(realm, user, realmAccess);
} else { } else {
logger.info("setting up realm access for a realm user"); logger.debug("setting up realm access for a realm user");
addRealmAccess(realm, user, realmAccess); addRealmAccess(realm, user, realmAccess);
} }
if (realmAccess.size() == 0) { if (realmAccess.size() == 0) {
@ -290,7 +290,6 @@ public class AdminConsole {
@Path("js/keycloak.js") @Path("js/keycloak.js")
@Produces("text/javascript") @Produces("text/javascript")
public Response getKeycloakJs() { public Response getKeycloakJs() {
//logger.info("**** -> getting console keycloak.js" + " uri: " + uriInfo.getRequestUri().toString());
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("keycloak.js"); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("keycloak.js");
if (inputStream != null) { if (inputStream != null) {
return Response.ok(inputStream).build(); return Response.ok(inputStream).build();

View file

@ -179,14 +179,14 @@ public class AdminRoot {
@Path("realms") @Path("realms")
public RealmsAdminResource getRealmsAdmin(@Context final HttpHeaders headers) { public RealmsAdminResource getRealmsAdmin(@Context final HttpHeaders headers) {
if (request.getHttpMethod().equalsIgnoreCase("OPTIONS")) { if (request.getHttpMethod().equalsIgnoreCase("OPTIONS")) {
logger.info("*** CORS ADMIN PREFLIGHT!!!!"); logger.debug("Cors admin pre-flight");
Response response = Cors.add(request, Response.ok()).preflight().allowedMethods("GET", "PUT", "POST", "DELETE").auth().build(); Response response = Cors.add(request, Response.ok()).preflight().allowedMethods("GET", "PUT", "POST", "DELETE").auth().build();
throw new WebApplicationException(response); throw new WebApplicationException(response);
} }
AdminAuth auth = authenticateRealmAdminRequest(headers); AdminAuth auth = authenticateRealmAdminRequest(headers);
if (auth != null) { if (auth != null) {
logger.info("authenticated admin access for: " + auth.getUser().getUsername()); logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
} }
Cors.add(request).allowedOrigins(auth.getToken()).allowedMethods("GET", "PUT", "POST", "DELETE").auth().build(response); Cors.add(request).allowedOrigins(auth.getToken()).allowedMethods("GET", "PUT", "POST", "DELETE").auth().build(response);

View file

@ -7,4 +7,5 @@ log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] %m%n
log4j.logger.org.keycloak=info log4j.logger.org.keycloak=info
log4j.logger.org.xnio=off log4j.logger.org.xnio=off
log4j.logger.org.hibernate=info log4j.logger.org.hibernate=off
log4j.logger.org.jboss.resteasy=warn

View file

@ -32,11 +32,11 @@ public class BasicTimerProvider implements TimerProvider {
TimerTask existingTask = factory.putTask(taskName, task); TimerTask existingTask = factory.putTask(taskName, task);
if (existingTask != null) { if (existingTask != null) {
logger.infof("Existing timer task '%s' found. Cancelling it", taskName); logger.debugf("Existing timer task '%s' found. Cancelling it", taskName);
existingTask.cancel(); existingTask.cancel();
} }
logger.infof("Starting task '%s' with interval '%d'", taskName, interval); logger.debugf("Starting task '%s' with interval '%d'", taskName, interval);
timer.schedule(task, interval, interval); timer.schedule(task, interval, interval);
} }
@ -44,7 +44,7 @@ public class BasicTimerProvider implements TimerProvider {
public void cancelTask(String taskName) { public void cancelTask(String taskName) {
TimerTask existingTask = factory.removeTask(taskName); TimerTask existingTask = factory.removeTask(taskName);
if (existingTask != null) { if (existingTask != null) {
logger.infof("Cancelling task '%s'", taskName); logger.debugf("Cancelling task '%s'", taskName);
existingTask.cancel(); existingTask.cancel();
} }
} }