Merge pull request #1048 from stianst/oidc

Change adapters to use auth and token endpoints
This commit is contained in:
Stian Thorgersen 2015-03-16 10:28:06 +01:00
commit 7ab0597989
43 changed files with 192 additions and 196 deletions

View file

@ -18,8 +18,7 @@ public class AbstractOAuthClient {
protected String clientId;
protected Map<String, String> credentials;
protected String authUrl;
protected String codeUrl;
protected String refreshUrl;
protected String tokenUrl;
protected RelativeUrlsUsed relativeUrlsUsed;
protected String scope;
protected String stateCookieName = OAUTH_TOKEN_REQUEST_STATE;
@ -54,20 +53,12 @@ public class AbstractOAuthClient {
this.authUrl = authUrl;
}
public String getCodeUrl() {
return codeUrl;
public String getTokenUrl() {
return tokenUrl;
}
public void setCodeUrl(String codeUrl) {
this.codeUrl = codeUrl;
}
public String getRefreshUrl() {
return refreshUrl;
}
public void setRefreshUrl(String refreshUrl) {
this.refreshUrl = refreshUrl;
public void setTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
}
public String getScope() {

View file

@ -6,11 +6,9 @@ package org.keycloak.constants;
*/
public interface ServiceUrlConstants {
public static final String TOKEN_SERVICE_LOGIN_PATH = "/realms/{realm-name}/protocol/openid-connect/login";
public static final String TOKEN_SERVICE_ACCESS_CODE_PATH = "/realms/{realm-name}/protocol/openid-connect/access/codes";
public static final String TOKEN_SERVICE_REFRESH_PATH = "/realms/{realm-name}/protocol/openid-connect/refresh";
public static final String AUTH_PATH = "/realms/{realm-name}/protocol/openid-connect/auth";
public static final String TOKEN_PATH = "/realms/{realm-name}/protocol/openid-connect/token";
public static final String TOKEN_SERVICE_LOGOUT_PATH = "/realms/{realm-name}/protocol/openid-connect/logout";
public static final String TOKEN_SERVICE_DIRECT_GRANT_PATH = "/realms/{realm-name}/protocol/openid-connect/grants/access";
public static final String ACCOUNT_SERVICE_PATH = "/realms/{realm-name}/account";
public static final String REALM_INFO_PATH = "/realms/{realm-name}";
public static final String CLIENTS_MANAGEMENT_REGISTER_NODE_PATH = "/realms/{realm-name}/clients-managements/register-node";

View file

@ -76,7 +76,7 @@ public class AdminClient {
try {
HttpPost post = new HttpPost(KeycloakUriBuilder.fromUri(getBaseUrl(request) + "/auth")
.path(ServiceUrlConstants.TOKEN_SERVICE_DIRECT_GRANT_PATH).build("demo"));
.path(ServiceUrlConstants.TOKEN_PATH).build("demo"));
List <NameValuePair> formparams = new ArrayList <NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "password"));

View file

@ -109,7 +109,7 @@ public class DatabaseClient {
return UriUtils.getOrigin(request.getRequestURL().toString());
case BROWSER_ONLY:
// Resolve baseURI from the codeURL (This is already non-relative and based on our hostname)
return UriUtils.getOrigin(oauthClient.getCodeUrl());
return UriUtils.getOrigin(oauthClient.getTokenUrl());
case NEVER:
return "";
default:

View file

@ -104,7 +104,7 @@ public class ProductDatabaseClient {
return UriUtils.getOrigin(request.getRequestURL().toString());
case BROWSER_ONLY:
// Resolve baseURI from the codeURL (This is already non-relative and based on our hostname)
return UriUtils.getOrigin(oAuthClient.getCodeUrl());
return UriUtils.getOrigin(oAuthClient.getTokenUrl());
case NEVER:
return "";
default:

View file

@ -26,7 +26,7 @@
<script src="${resourceUrl}/lib/fileupload/angular-file-upload.min.js"></script>
<script src="${resourceUrl}/lib/filesaver/FileSaver.js"></script>
<script src="/auth/js/keycloak.js" type="text/javascript"></script>
<script src="/auth/js/${resourceVersion}/keycloak.js" type="text/javascript"></script>
<script src="${resourceUrl}/js/app.js" type="text/javascript"></script>
<script src="${resourceUrl}/js/controllers/realm.js" type="text/javascript"></script>

View file

@ -168,13 +168,8 @@ public class AdapterDeploymentContext {
}
@Override
public String getCodeUrl() {
return (this.codeUrl != null) ? this.codeUrl : delegate.getCodeUrl();
}
@Override
public String getRefreshUrl() {
return (this.refreshUrl != null) ? this.refreshUrl : delegate.getRefreshUrl();
public String getTokenUrl() {
return (this.tokenUrl != null) ? this.tokenUrl : delegate.getTokenUrl();
}
@Override

View file

@ -38,7 +38,7 @@ public class AdapterUtils {
return UriUtils.getOrigin(browserRequestURL);
case BROWSER_ONLY:
// Resolve baseURI from the codeURL (This is already non-relative and based on our hostname)
return UriUtils.getOrigin(deployment.getCodeUrl());
return UriUtils.getOrigin(deployment.getTokenUrl());
default:
return "";
}

View file

@ -69,8 +69,9 @@ public class BasicAuthRequestAuthenticator extends BearerTokenRequestAuthenticat
try {
HttpPost post = new HttpPost(
KeycloakUriBuilder.fromUri(deployment.getAuthServerBaseUrl())
.path(ServiceUrlConstants.TOKEN_SERVICE_DIRECT_GRANT_PATH).build(deployment.getRealm()));
.path(ServiceUrlConstants.TOKEN_PATH).build(deployment.getRealm()));
java.util.List <NameValuePair> formparams = new java.util.ArrayList <NameValuePair>();
formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
formparams.add(new BasicNameValuePair("username", username));
formparams.add(new BasicNameValuePair("password", password));

View file

@ -28,8 +28,7 @@ public class KeycloakDeployment {
protected String authServerBaseUrl;
protected String realmInfoUrl;
protected KeycloakUriBuilder authUrl;
protected String codeUrl;
protected String refreshUrl;
protected String tokenUrl;
protected KeycloakUriBuilder logoutUrl;
protected String accountUrl;
protected String registerNodeUrl;
@ -131,7 +130,7 @@ public class KeycloakDeployment {
log.debug("resolveBrowserUrls");
}
String login = authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGIN_PATH).build(getRealm()).toString();
String login = authUrlBuilder.clone().path(ServiceUrlConstants.AUTH_PATH).build(getRealm()).toString();
authUrl = KeycloakUriBuilder.fromUri(login);
}
@ -143,11 +142,10 @@ public class KeycloakDeployment {
log.debug("resolveNonBrowserUrls");
}
refreshUrl = authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_REFRESH_PATH).build(getRealm()).toString();
tokenUrl = authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_PATH).build(getRealm()).toString();
logoutUrl = KeycloakUriBuilder.fromUri(authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH).build(getRealm()).toString());
accountUrl = authUrlBuilder.clone().path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH).build(getRealm()).toString();
realmInfoUrl = authUrlBuilder.clone().path(ServiceUrlConstants.REALM_INFO_PATH).build(getRealm()).toString();
codeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_ACCESS_CODE_PATH).build(getRealm()).toString();
registerNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_REGISTER_NODE_PATH).build(getRealm()).toString();
unregisterNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_UNREGISTER_NODE_PATH).build(getRealm()).toString();
}
@ -164,12 +162,8 @@ public class KeycloakDeployment {
return authUrl;
}
public String getCodeUrl() {
return codeUrl;
}
public String getRefreshUrl() {
return refreshUrl;
public String getTokenUrl() {
return tokenUrl;
}
public KeycloakUriBuilder getLogoutUrl() {

View file

@ -85,7 +85,7 @@ public class KeycloakDeploymentBuilder {
}
deployment.setAuthServerBaseUrl(adapterConfig);
log.debug("Use authServerUrl: " + deployment.getAuthServerBaseUrl() + ", codeUrl: " + deployment.getCodeUrl() + ", relativeUrls: " + deployment.getRelativeUrls());
log.debug("Use authServerUrl: " + deployment.getAuthServerBaseUrl() + ", tokenUrl: " + deployment.getTokenUrl() + ", relativeUrls: " + deployment.getRelativeUrls());
return deployment;
}

View file

@ -136,6 +136,7 @@ public class OAuthRequestAuthenticator {
url = UriUtils.stripQueryParam(url, K_IDP_HINT);
KeycloakUriBuilder redirectUriBuilder = deployment.getAuthUrl().clone()
.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
.queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName())
.queryParam(OAuth2Constants.REDIRECT_URI, url)
.queryParam(OAuth2Constants.STATE, state)

View file

@ -87,15 +87,15 @@ public class ServerRequest {
}
public static AccessTokenResponse invokeAccessCodeToToken(KeycloakDeployment deployment, String code, String redirectUri, String sessionId) throws HttpFailure, IOException {
String codeUrl = deployment.getCodeUrl();
String tokenUrl = deployment.getTokenUrl();
String client_id = deployment.getResourceName();
Map<String, String> credentials = deployment.getResourceCredentials();
HttpClient client = deployment.getClient();
return invokeAccessCodeToToken(client, deployment.isPublicClient(), code, codeUrl, redirectUri, client_id, credentials, sessionId);
return invokeAccessCodeToToken(client, deployment.isPublicClient(), code, tokenUrl, redirectUri, client_id, credentials, sessionId);
}
public static AccessTokenResponse invokeAccessCodeToToken(HttpClient client, boolean publicClient, String code, String codeUrl, String redirectUri, String client_id, Map<String, String> credentials, String sessionId) throws IOException, HttpFailure {
public static AccessTokenResponse invokeAccessCodeToToken(HttpClient client, boolean publicClient, String code, String tokenUrl, String redirectUri, String client_id, Map<String, String> credentials, String sessionId) throws IOException, HttpFailure {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
redirectUri = stripOauthParametersFromRedirect(redirectUri);
formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, "authorization_code"));
@ -106,7 +106,7 @@ public class ServerRequest {
formparams.add(new BasicNameValuePair(AdapterConstants.APPLICATION_SESSION_HOST, HostUtils.getHostName()));
}
HttpResponse response = null;
HttpPost post = new HttpPost(codeUrl);
HttpPost post = new HttpPost(tokenUrl);
if (!publicClient) {
String clientSecret = credentials.get(CredentialRepresentation.SECRET);
if (clientSecret != null) {
@ -152,15 +152,15 @@ public class ServerRequest {
}
public static AccessTokenResponse invokeRefresh(KeycloakDeployment deployment, String refreshToken) throws IOException, HttpFailure {
String refreshUrl = deployment.getRefreshUrl();
String tokenUrl = deployment.getTokenUrl();
String client_id = deployment.getResourceName();
Map<String, String> credentials = deployment.getResourceCredentials();
HttpClient client = deployment.getClient();
return invokeRefresh(client, deployment.isPublicClient(), refreshToken, refreshUrl, client_id, credentials);
return invokeRefresh(client, deployment.isPublicClient(), refreshToken, tokenUrl, client_id, credentials);
}
public static AccessTokenResponse invokeRefresh(HttpClient client, boolean publicClient, String refreshToken, String refreshUrl, String client_id, Map<String, String> credentials) throws IOException, HttpFailure {
public static AccessTokenResponse invokeRefresh(HttpClient client, boolean publicClient, String refreshToken, String tokenUrl, String client_id, Map<String, String> credentials) throws IOException, HttpFailure {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : credentials.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
@ -168,7 +168,7 @@ public class ServerRequest {
formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN));
formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
HttpResponse response = null;
HttpPost post = new HttpPost(refreshUrl);
HttpPost post = new HttpPost(tokenUrl);
if (!publicClient) {
String clientSecret = credentials.get(CredentialRepresentation.SECRET);
if (clientSecret != null) {

View file

@ -64,10 +64,11 @@ public class DirectAccessGrantsLoginModule extends AbstractKeycloakLoginModule {
protected Auth directGrantAuth(String username, String password) throws IOException, VerificationException {
String authServerBaseUrl = deployment.getAuthServerBaseUrl();
URI directGrantUri = KeycloakUriBuilder.fromUri(authServerBaseUrl).path(ServiceUrlConstants.TOKEN_SERVICE_DIRECT_GRANT_PATH).build(deployment.getRealm());
URI directGrantUri = KeycloakUriBuilder.fromUri(authServerBaseUrl).path(ServiceUrlConstants.TOKEN_PATH).build(deployment.getRealm());
HttpPost post = new HttpPost(directGrantUri);
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
formparams.add(new BasicNameValuePair("username", username));
formparams.add(new BasicNameValuePair("password", password));

View file

@ -20,7 +20,7 @@ public class KeycloakDeploymentBuilderTest {
assertEquals("demo", deployment.getRealm());
assertEquals("customer-portal", deployment.getResourceName());
assertEquals(PemUtils.decodePublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB"), deployment.getRealmKey());
assertEquals("https://localhost:8443/auth/realms/demo/protocol/openid-connect/login", deployment.getAuthUrl().build().toString());
assertEquals("https://localhost:8443/auth/realms/demo/protocol/openid-connect/auth", deployment.getAuthUrl().build().toString());
assertEquals(SslRequired.EXTERNAL, deployment.getSslRequired());
assertTrue(deployment.isUseResourceRoleMappings());
assertTrue(deployment.isCors());
@ -33,7 +33,7 @@ public class KeycloakDeploymentBuilderTest {
assertTrue(deployment.isExposeToken());
assertEquals("234234-234234-234234", deployment.getResourceCredentials().get("secret"));
assertEquals(20, ((ThreadSafeClientConnManager) deployment.getClient().getConnectionManager()).getMaxTotal());
assertEquals("https://localhost:8443/auth/realms/demo/protocol/openid-connect/refresh", deployment.getRefreshUrl());
assertEquals("https://localhost:8443/auth/realms/demo/protocol/openid-connect/token", deployment.getTokenUrl());
assertTrue(deployment.isAlwaysRefreshToken());
assertTrue(deployment.isRegisterNodeAtStartup());
assertEquals(1000, deployment.getRegisterNodePeriod());

View file

@ -97,6 +97,7 @@ public class KeycloakInstalled {
String state = UUID.randomUUID().toString();
String authUrl = deployment.getAuthUrl().clone()
.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
.queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName())
.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
.queryParam(OAuth2Constants.STATE, state)
@ -153,6 +154,7 @@ public class KeycloakInstalled {
String redirectUri = "urn:ietf:wg:oauth:2.0:oob";
String authUrl = deployment.getAuthUrl().clone()
.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
.queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName())
.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
.build().toString();

View file

@ -53,7 +53,7 @@ public class JaxrsOAuthClient extends AbstractOAuthClient {
for (Map.Entry<String, String> entry : credentials.entrySet()) {
codeForm.param(entry.getKey(), entry.getValue());
}
Response res = client.target(codeUrl).request().post(Entity.form(codeForm));
Response res = client.target(tokenUrl).request().post(Entity.form(codeForm));
try {
if (res.getStatus() == 400) {
throw new BadRequestException();

View file

@ -140,7 +140,7 @@
sessionStorage.oauthState = JSON.stringify({ state: state, redirectUri: encodeURIComponent(redirectUri) });
var action = 'login';
var action = 'auth';
if (options && options.action == 'register') {
action = 'registrations';
}
@ -284,7 +284,7 @@
promise.setSuccess(false);
} else {
var params = 'grant_type=refresh_token&' + 'refresh_token=' + kc.refreshToken;
var url = getRealmUrl() + '/protocol/openid-connect/refresh';
var url = getRealmUrl() + '/protocol/openid-connect/token';
refreshQueue.push(promise);
@ -358,8 +358,8 @@
var prompt = oauth.prompt;
if (code) {
var params = 'code=' + code;
var url = getRealmUrl() + '/protocol/openid-connect/access/codes';
var params = 'code=' + code + '&grant_type=authorization_code';
var url = getRealmUrl() + '/protocol/openid-connect/token';
var req = new XMLHttpRequest();
req.open('POST', url, true);

View file

@ -42,7 +42,7 @@ public class ServletOAuthClient extends AbstractOAuthClient {
private AccessTokenResponse resolveBearerToken(HttpServletRequest request, String redirectUri, String code) throws IOException, ServerRequest.HttpFailure {
// Don't send sessionId in oauth clients for now
return ServerRequest.invokeAccessCodeToToken(client, publicClient, code, getUrl(request, codeUrl, false), redirectUri, clientId, credentials, null);
return ServerRequest.invokeAccessCodeToToken(client, publicClient, code, getUrl(request, tokenUrl, false), redirectUri, clientId, credentials, null);
}
/**
@ -148,7 +148,7 @@ public class ServletOAuthClient extends AbstractOAuthClient {
}
public AccessTokenResponse refreshToken(HttpServletRequest request, String refreshToken) throws IOException, ServerRequest.HttpFailure {
return ServerRequest.invokeRefresh(client, publicClient, refreshToken, getUrl(request, refreshUrl, false), clientId, credentials);
return ServerRequest.invokeRefresh(client, publicClient, refreshToken, getUrl(request, tokenUrl, false), clientId, credentials);
}
public static IDToken extractIdToken(String idToken) {

View file

@ -54,25 +54,20 @@ public class ServletOAuthClientBuilder {
RelativeUrlsUsed useRelative = relativeUrls(serverBuilder, adapterConfig);
oauthClient.setRelativeUrlsUsed(useRelative);
String authUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGIN_PATH).build(adapterConfig.getRealm()).toString();
String authUrl = serverBuilder.clone().path(ServiceUrlConstants.AUTH_PATH).build(adapterConfig.getRealm()).toString();
KeycloakUriBuilder tokenUrlBuilder;
KeycloakUriBuilder refreshUrlBuilder;
if (useRelative == RelativeUrlsUsed.BROWSER_ONLY) {
// Use absolute URI for refreshToken and codeToToken requests
KeycloakUriBuilder nonBrowsersServerBuilder = KeycloakUriBuilder.fromUri(adapterConfig.getAuthServerUrlForBackendRequests());
tokenUrlBuilder = nonBrowsersServerBuilder.clone();
refreshUrlBuilder = nonBrowsersServerBuilder.clone();
} else {
tokenUrlBuilder = serverBuilder.clone();
refreshUrlBuilder = serverBuilder.clone();
}
String tokenUrl = tokenUrlBuilder.path(ServiceUrlConstants.TOKEN_SERVICE_ACCESS_CODE_PATH).build(adapterConfig.getRealm()).toString();
String refreshUrl = refreshUrlBuilder.path(ServiceUrlConstants.TOKEN_SERVICE_REFRESH_PATH).build(adapterConfig.getRealm()).toString();
String tokenUrl = tokenUrlBuilder.path(ServiceUrlConstants.TOKEN_PATH).build(adapterConfig.getRealm()).toString();
oauthClient.setAuthUrl(authUrl);
oauthClient.setCodeUrl(tokenUrl);
oauthClient.setRefreshUrl(refreshUrl);
oauthClient.setTokenUrl(tokenUrl);
}
private static RelativeUrlsUsed relativeUrls(KeycloakUriBuilder serverBuilder, AdapterConfig adapterConfig) {

View file

@ -86,9 +86,19 @@ public class OIDCLoginProtocolService {
return baseUriBuilder.path(RealmsResource.class).path("{realm}/protocol/" + OIDCLoginProtocol.LOGIN_PROTOCOL);
}
public static UriBuilder accessCodeToTokenUrl(UriBuilder baseUriBuilder) {
public static UriBuilder authUrl(UriInfo uriInfo) {
UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
return authUrl(baseUriBuilder);
}
public static UriBuilder authUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "accessCodeToToken");
return uriBuilder.path(OIDCLoginProtocolService.class, "auth");
}
public static UriBuilder tokenUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "token");
}
public static UriBuilder validateAccessTokenUrl(UriBuilder baseUriBuilder) {
@ -96,21 +106,6 @@ public class OIDCLoginProtocolService {
return uriBuilder.path(OIDCLoginProtocolService.class, "validateAccessToken");
}
public static UriBuilder grantAccessTokenUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "grantAccessToken");
}
public static UriBuilder loginPageUrl(UriInfo uriInfo) {
UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
return loginPageUrl(baseUriBuilder);
}
public static UriBuilder loginPageUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "loginPage");
}
public static UriBuilder logoutUrl(UriInfo uriInfo) {
UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
return logoutUrl(baseUriBuilder);
@ -121,11 +116,6 @@ public class OIDCLoginProtocolService {
return uriBuilder.path(OIDCLoginProtocolService.class, "logout");
}
public static UriBuilder refreshUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "refreshAccessToken");
}
/**
* Authorization endpoint
*/

View file

@ -106,8 +106,7 @@ public class AuthorizationEndpoint {
* @deprecated
*/
public AuthorizationEndpoint legacy(String legacyResponseType) {
// TODO Change to warn once adapters has been updated
logger.debugv("Invoking deprecated endpoint {0}", uriInfo.getRequestUri());
logger.warnv("Invoking deprecated endpoint {0}", uriInfo.getRequestUri());
this.legacyResponseType = legacyResponseType;
return this;
}

View file

@ -47,6 +47,8 @@ import java.util.Map;
public class TokenEndpoint {
private static final Logger logger = Logger.getLogger(TokenEndpoint.class);
private MultivaluedMap<String, String> formParams;
private ClientModel client;
private enum Action {
AUTHORIZATION_CODE, REFRESH_TOKEN, PASSWORD
@ -74,10 +76,7 @@ public class TokenEndpoint {
private Action action;
private String clientId;
private String grantType;
private String code;
private String redirectUri;
private String legacyGrantType;
@ -89,15 +88,14 @@ public class TokenEndpoint {
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response build(final MultivaluedMap<String, String> formData) {
public Response build() {
switch (action) {
case AUTHORIZATION_CODE:
return buildAuthorizationCodeAccessTokenResponse(formData);
return buildAuthorizationCodeAccessTokenResponse();
case REFRESH_TOKEN:
return buildRefreshToken(formData);
return buildRefreshToken();
case PASSWORD:
return buildResourceOwnerPasswordCredentialsGrant(formData);
return buildResourceOwnerPasswordCredentialsGrant();
}
throw new RuntimeException("Unknown action " + action);
@ -115,23 +113,19 @@ public class TokenEndpoint {
* @deprecated
*/
public TokenEndpoint legacy(String legacyGrantType) {
// TODO Change to warn once adapters has been updated
logger.debugv("Invoking deprecated endpoint {0}", uriInfo.getRequestUri());
logger.warnv("Invoking deprecated endpoint {0}", uriInfo.getRequestUri());
this.legacyGrantType = legacyGrantType;
return this;
}
public TokenEndpoint init() {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
clientId = params.getFirst(OIDCLoginProtocol.CLIENT_ID_PARAM);
grantType = params.getFirst(OIDCLoginProtocol.GRANT_TYPE_PARAM);
code = params.getFirst(OIDCLoginProtocol.CODE_PARAM);
redirectUri = params.getFirst(OIDCLoginProtocol.REDIRECT_URI_PARAM);
formParams = request.getDecodedFormParameters();
grantType = formParams.getFirst(OIDCLoginProtocol.GRANT_TYPE_PARAM);
checkSsl();
checkRealm();
checkGrantType();
checkClient();
return this;
}
@ -148,15 +142,13 @@ public class TokenEndpoint {
}
}
private ClientModel authorizeClient(final MultivaluedMap<String, String> formData) {
private void checkClient() {
String authorizationHeader = headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
ClientModel client = AuthorizeClientUtil.authorizeClient(authorizationHeader, formData, event, realm);
client = AuthorizeClientUtil.authorizeClient(authorizationHeader, formParams, event, realm);
if ((client instanceof ApplicationModel) && ((ApplicationModel) client).isBearerOnly()) {
throw new ErrorResponseException("invalid_client", "Bearer-only not allowed", Response.Status.BAD_REQUEST);
}
return client;
}
private void checkGrantType() {
@ -182,8 +174,8 @@ public class TokenEndpoint {
}
}
public Response buildAuthorizationCodeAccessTokenResponse(final MultivaluedMap<String, String> formData) {
String code = formData.getFirst(OAuth2Constants.CODE);
public Response buildAuthorizationCodeAccessTokenResponse() {
String code = formParams.getFirst(OAuth2Constants.CODE);
if (code == null) {
event.error(Errors.INVALID_CODE);
throw new ErrorResponseException("invalid_request", "Missing parameter: " + OAuth2Constants.CODE, Response.Status.BAD_REQUEST);
@ -214,10 +206,8 @@ public class TokenEndpoint {
event.user(userSession.getUser());
event.session(userSession.getId());
ClientModel client = authorizeClient(formData);
String redirectUri = clientSession.getNote(OIDCLoginProtocol.REDIRECT_URI_PARAM);
if (redirectUri != null && !redirectUri.equals(formData.getFirst(OAuth2Constants.REDIRECT_URI))) {
if (redirectUri != null && !redirectUri.equals(formParams.getFirst(OAuth2Constants.REDIRECT_URI))) {
event.error(Errors.INVALID_CODE);
throw new ErrorResponseException("invalid_grant", "Incorrect redirect_uri", Response.Status.BAD_REQUEST);
}
@ -243,9 +233,9 @@ public class TokenEndpoint {
throw new ErrorResponseException("invalid_grant", "Session not active", Response.Status.BAD_REQUEST);
}
String adapterSessionId = formData.getFirst(AdapterConstants.APPLICATION_SESSION_STATE);
String adapterSessionId = formParams.getFirst(AdapterConstants.APPLICATION_SESSION_STATE);
if (adapterSessionId != null) {
String adapterSessionHost = formData.getFirst(AdapterConstants.APPLICATION_SESSION_HOST);
String adapterSessionHost = formParams.getFirst(AdapterConstants.APPLICATION_SESSION_HOST);
logger.debugf("Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'", adapterSessionId, client.getClientId(), adapterSessionHost);
event.detail(AdapterConstants.APPLICATION_SESSION_STATE, adapterSessionId);
@ -266,10 +256,8 @@ public class TokenEndpoint {
return Cors.add(request, Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).auth().allowedOrigins(client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
}
public Response buildRefreshToken(final MultivaluedMap<String, String> formData) {
ClientModel client = authorizeClient(formData);
String refreshToken = formData.getFirst(OAuth2Constants.REFRESH_TOKEN);
public Response buildRefreshToken() {
String refreshToken = formParams.getFirst(OAuth2Constants.REFRESH_TOKEN);
if (refreshToken == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "No refresh token", Response.Status.BAD_REQUEST);
}
@ -287,14 +275,14 @@ public class TokenEndpoint {
return Cors.add(request, Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).auth().allowedOrigins(client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
}
public Response buildResourceOwnerPasswordCredentialsGrant(final MultivaluedMap<String, String> formData) {
public Response buildResourceOwnerPasswordCredentialsGrant() {
if (!realm.isPasswordCredentialGrantAllowed()) {
throw new ErrorResponseException("not_enabled", "Direct Grant REST API not enabled", Response.Status.FORBIDDEN);
}
event.detail(Details.AUTH_METHOD, "oauth_credentials").detail(Details.RESPONSE_TYPE, "token");
String username = formData.getFirst(AuthenticationManager.FORM_USERNAME);
String username = formParams.getFirst(AuthenticationManager.FORM_USERNAME);
if (username == null) {
event.error(Errors.USERNAME_MISSING);
throw new ErrorResponseException("invalid_request", "Missing parameter: username", Response.Status.UNAUTHORIZED);
@ -304,9 +292,7 @@ public class TokenEndpoint {
UserModel user = KeycloakModelUtils.findUserByNameOrEmail(session, realm, username);
if (user != null) event.user(user);
ClientModel client = authorizeClient(formData);
AuthenticationManager.AuthenticationStatus authenticationStatus = authManager.authenticateForm(session, clientConnection, realm, formData);
AuthenticationManager.AuthenticationStatus authenticationStatus = authManager.authenticateForm(session, clientConnection, realm, formParams);
Map<String, String> err;
switch (authenticationStatus) {
@ -324,7 +310,7 @@ public class TokenEndpoint {
throw new ErrorResponseException("invalid_grant", "Invalid user credentials", Response.Status.UNAUTHORIZED);
}
String scope = formData.getFirst(OAuth2Constants.SCOPE);
String scope = formParams.getFirst(OAuth2Constants.SCOPE);
UserSessionProvider sessions = session.sessions();

View file

@ -25,6 +25,7 @@ import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.BadRequestException;
import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.ClientConnection;
import org.keycloak.OAuth2Constants;
import org.keycloak.account.AccountPages;
import org.keycloak.account.AccountProvider;
import org.keycloak.events.Details;
@ -763,7 +764,7 @@ public class AccountService {
private Response login(String path) {
OAuthRedirect oauth = new OAuthRedirect();
String authUrl = OIDCLoginProtocolService.loginPageUrl(uriInfo).build(realm.getName()).toString();
String authUrl = OIDCLoginProtocolService.authUrl(uriInfo).build(realm.getName()).toString();
oauth.setAuthUrl(authUrl);
oauth.setClientId(Constants.ACCOUNT_MANAGEMENT_APP);

View file

@ -1,9 +1,11 @@
package org.keycloak.services.resources;
import org.keycloak.Config;
import org.keycloak.Version;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Response;
@ -38,6 +40,17 @@ public class JsResource {
}
}
@GET
@Path("/{version}/keycloak.js")
@Produces("text/javascript")
public Response getJsWithVersion(@PathParam("version") String version) {
if (!version.equals(Version.RESOURCES_VERSION)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return getJs();
}
@GET
@Path("/keycloak.min.js")
@Produces("text/javascript")
@ -54,4 +67,15 @@ public class JsResource {
}
}
@GET
@Path("/{version}/keycloak.min.js")
@Produces("text/javascript")
public Response getMinJsWithVersion(@PathParam("version") String version) {
if (!version.equals(Version.RESOURCES_VERSION)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return getMinJs();
}
}

View file

@ -2,6 +2,7 @@ package org.keycloak.services.resources;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.Version;
import org.keycloak.freemarker.Theme;
import org.keycloak.freemarker.ThemeProvider;
import org.keycloak.models.KeycloakSession;
@ -38,7 +39,11 @@ public class ThemeResource {
*/
@GET
@Path("/{version}/{themeType}/{themeName}/{path:.*}")
public Response getResource(@PathParam("themeType") String themType, @PathParam("themeName") String themeName, @PathParam("path") String path) {
public Response getResource(@PathParam("version") String version, @PathParam("themeType") String themType, @PathParam("themeName") String themeName, @PathParam("path") String path) {
if (!version.equals(Version.RESOURCES_VERSION)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
try {
ThemeProvider themeProvider = session.getProvider(ThemeProvider.class, "extending");
Theme theme = themeProvider.getTheme(themeName, Theme.Type.valueOf(themType.toUpperCase()));

View file

@ -8,6 +8,7 @@ import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
import org.keycloak.ClientConnection;
import org.keycloak.Config;
import org.keycloak.Version;
import org.keycloak.freemarker.BrowserSecurityHeaderSetup;
import org.keycloak.freemarker.FreeMarkerException;
import org.keycloak.freemarker.FreeMarkerUtil;
@ -290,6 +291,7 @@ public class AdminConsole {
map.put("authUrl", authUrl);
map.put("resourceUrl", Urls.themeRoot(baseUri) + "/admin/" + adminTheme);
map.put("resourceVersion", Version.RESOURCES_VERSION);
ThemeProvider themeProvider = session.getProvider(ThemeProvider.class, "extending");
Theme theme = themeProvider.getTheme(realm.getAdminTheme(), Theme.Type.ADMIN);

View file

@ -34,7 +34,8 @@ public class OAuthRedirect extends AbstractOAuthClient {
UriBuilder uriBuilder = UriBuilder.fromUri(authUrl)
.queryParam(OAuth2Constants.CLIENT_ID, clientId)
.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
.queryParam(OAuth2Constants.STATE, state);
.queryParam(OAuth2Constants.STATE, state)
.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE);
if (scope != null) {
uriBuilder.queryParam(OAuth2Constants.SCOPE, scope);
}

View file

@ -46,12 +46,27 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class KeycloakServer {
static {
try {
File f = new File(System.getProperty("user.home"), ".keycloak-test.properties");
if (f.isFile()) {
Properties p = new Properties();
p.load(new FileInputStream(f));
System.getProperties().putAll(p);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final Logger log = Logger.getLogger(KeycloakServer.class);
private boolean sysout = false;

View file

@ -67,10 +67,6 @@ public class OAuthClient {
private String realm = "test";
private String responseType = OAuth2Constants.CODE;
private String grantType = "authorization_code";
private String clientId = "test-app";
private String redirectUri = "http://localhost:8081/app/auth";
@ -113,9 +109,8 @@ public class OAuthClient {
HttpPost post = new HttpPost(getAccessTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
if (grantType != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, grantType));
}
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
if (code != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
}
@ -153,6 +148,7 @@ public class OAuthClient {
post.setHeader("Authorization", authorization);
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
@ -199,9 +195,8 @@ public class OAuthClient {
HttpPost post = new HttpPost(getRefreshTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
if (grantType != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, grantType));
}
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN));
if (refreshToken != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
}
@ -290,10 +285,8 @@ public class OAuthClient {
}
public String getLoginFormUrl() {
UriBuilder b = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri(baseUrl));
if (responseType != null) {
b.queryParam(OAuth2Constants.RESPONSE_TYPE, responseType);
}
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(baseUrl));
b.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE);
if (clientId != null) {
b.queryParam(OAuth2Constants.CLIENT_ID, clientId);
}
@ -307,7 +300,7 @@ public class OAuthClient {
}
public String getAccessTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.accessCodeToTokenUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
@ -323,12 +316,12 @@ public class OAuthClient {
}
public String getResourceOwnerPasswordCredentialGrantUrl() {
UriBuilder b = OIDCLoginProtocolService.grantAccessTokenUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getRefreshTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.refreshUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
@ -351,11 +344,6 @@ public class OAuthClient {
return this;
}
public OAuthClient responseType(String responseType) {
this.responseType = responseType;
return this;
}
public OAuthClient state(String state) {
this.state = state;
return this;

View file

@ -92,7 +92,7 @@ public class AdapterTestStrategy extends ExternalResource {
@WebResource
protected InputPage inputPage;
protected String LOGIN_URL = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri(AUTH_SERVER_URL)).build("demo").toString();
protected String LOGIN_URL = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(AUTH_SERVER_URL)).build("demo").toString();
public AdapterTestStrategy(String AUTH_SERVER_URL, String APP_SERVER_BASE_URL, AbstractKeycloakRule keycloakRule) {
this.AUTH_SERVER_URL = AUTH_SERVER_URL;
@ -420,11 +420,12 @@ public class AdapterTestStrategy extends ExternalResource {
public void testBadUser() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_URL);
URI uri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("demo");
URI uri = OIDCLoginProtocolService.tokenUrl(builder).build("demo");
WebTarget target = client.target(uri);
String header = BasicAuthHelper.createHeader("customer-portal", "password");
Form form = new Form();
form.param("username", "monkey@redhat.com")
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "monkey@redhat.com")
.param("password", "password");
Response response = target.request()
.header(HttpHeaders.AUTHORIZATION, header)

View file

@ -31,7 +31,7 @@ import org.openqa.selenium.WebDriver;
*/
public class CookieTokenStoreAdapterTest {
public static final String LOGIN_URL = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
public static final String LOGIN_URL = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
@ClassRule
public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule() {

View file

@ -126,7 +126,7 @@ public class MultiTenancyTest {
}
private void doTenantRequests(String tenant, boolean logout) {
String tenantLoginUrl = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build(tenant).toString();
String tenantLoginUrl = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build(tenant).toString();
driver.navigate().to("http://localhost:8081/multi-tenant?realm="+tenant);
System.out.println("Current url: " + driver.getCurrentUrl());

View file

@ -66,7 +66,7 @@ import java.util.Map;
*/
public class RelativeUriAdapterTest {
public static final String LOGIN_URL = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
public static final String LOGIN_URL = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
public static PublicKey realmPublicKey;
@ClassRule
public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule(){

View file

@ -175,7 +175,7 @@ public abstract class AbstractIdentityProviderTest {
driver.navigate().to("http://localhost:8081/test-app/logout");
driver.navigate().to("http://localhost:8081/test-app");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
} finally {
getRealm().setRegistrationEmailAsUsername(false);
@ -215,7 +215,7 @@ public abstract class AbstractIdentityProviderTest {
this.driver.navigate().to("http://localhost:8081/test-app/");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
try {
this.driver.findElement(By.className(getProviderId()));
@ -245,7 +245,7 @@ public abstract class AbstractIdentityProviderTest {
this.driver.navigate().to("http://localhost:8081/test-app/");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
try {
this.driver.findElement(By.className(getProviderId()));
@ -267,7 +267,7 @@ public abstract class AbstractIdentityProviderTest {
public void testUserAlreadyExistsWhenUpdatingProfile() {
this.driver.navigate().to("http://localhost:8081/test-app/");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
// choose the identity provider
this.loginPage.clickSocial(getProviderId());
@ -306,7 +306,7 @@ public abstract class AbstractIdentityProviderTest {
this.driver.navigate().to("http://localhost:8081/test-app/");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
// choose the identity provider
this.loginPage.clickSocial(getProviderId());
@ -374,7 +374,7 @@ public abstract class AbstractIdentityProviderTest {
public void testIdentityProviderNotAllowed() {
this.driver.navigate().to("http://localhost:8081/test-app/");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
driver.findElement(By.className("model-oidc-idp"));
}
@ -438,7 +438,7 @@ public abstract class AbstractIdentityProviderTest {
driver.navigate().to("http://localhost:8081/test-app/logout");
driver.navigate().to("http://localhost:8081/test-app");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
}
@Test
@ -533,13 +533,13 @@ public abstract class AbstractIdentityProviderTest {
driver.navigate().to("http://localhost:8081/test-app/logout");
driver.navigate().to("http://localhost:8081/test-app");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
}
private void authenticateWithIdentityProvider(IdentityProviderModel identityProviderModel, String username) {
driver.navigate().to("http://localhost:8081/test-app");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
// choose the identity provider
this.loginPage.clickSocial(getProviderId());

View file

@ -74,7 +74,7 @@ public class IdentityProviderHintTest {
public void testInvalidIdentityProviderHint() {
this.driver.navigate().to("http://localhost:8081/test-app?k_idp_hint=invalid-idp-id");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
assertEquals("Could not find an identity provider with the identifier [invalid-idp-id].", this.driver.findElement(By.className("instruction")).getText());
}

View file

@ -149,7 +149,7 @@ public class AccessTokenTest {
AccessTokenResponse response = oauth.doAccessTokenRequest(code, "invalid");
Assert.assertEquals(400, response.getStatusCode());
AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_client_credentials").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID);
AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_client_credentials").clearDetails().user((String) null).session((String) null);
expectedEvent.assertEvent();
}
@ -190,7 +190,7 @@ public class AccessTokenTest {
assertNull(tokenResponse.getAccessToken());
assertNull(tokenResponse.getRefreshToken());
events.expectCodeToToken(codeId, sessionId).removeDetail(Details.TOKEN_ID).client((String) null).user((String) null).session((String) null).removeDetail(Details.REFRESH_TOKEN_ID).error(Errors.INVALID_CODE).assertEvent();
events.expectCodeToToken(codeId, sessionId).removeDetail(Details.TOKEN_ID).user((String) null).session((String) null).removeDetail(Details.REFRESH_TOKEN_ID).error(Errors.INVALID_CODE).assertEvent();
events.clear();
}
@ -222,7 +222,7 @@ public class AccessTokenTest {
Assert.assertEquals(400, response.getStatusCode());
AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, null);
expectedEvent.error("invalid_code").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID).client((String) null).user((String) null);
expectedEvent.error("invalid_code").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID).user((String) null);
expectedEvent.assertEvent();
events.clear();
@ -254,7 +254,7 @@ public class AccessTokenTest {
Assert.assertEquals(400, response.getStatusCode());
AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, null);
expectedEvent.error("invalid_code").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID).client((String) null).user((String) null);
expectedEvent.error("invalid_code").removeDetail(Details.TOKEN_ID).removeDetail(Details.REFRESH_TOKEN_ID).user((String) null);
expectedEvent.assertEvent();
events.clear();
@ -335,7 +335,7 @@ public class AccessTokenTest {
public void testValidateAccessToken() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI grantUri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("test");
URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget grantTarget = client.target(grantUri);
builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI validateUri = OIDCLoginProtocolService.validateAccessTokenUrl(builder).build("test");
@ -392,7 +392,7 @@ public class AccessTokenTest {
public void testGrantAccessToken() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI grantUri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("test");
URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget grantTarget = client.target(grantUri);
{ // test checkSsl
@ -421,6 +421,7 @@ public class AccessTokenTest {
{ // test null username
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
form.param("password", "password");
Response response = grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)
@ -432,6 +433,7 @@ public class AccessTokenTest {
{ // test no password
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
form.param("username", "test-user@localhost");
Response response = grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)
@ -443,6 +445,7 @@ public class AccessTokenTest {
{ // test invalid password
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
form.param("username", "test-user@localhost");
form.param("password", "invalid");
Response response = grantTarget.request()
@ -598,7 +601,7 @@ public class AccessTokenTest {
public void testTokenMapping() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI grantUri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("test");
URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget grantTarget = client.target(grantUri);
{
KeycloakSession session = keycloakRule.startSession();
@ -721,7 +724,8 @@ public class AccessTokenTest {
protected Response executeGrantAccessTokenRequest(WebTarget grantTarget) {
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param("username", "test-user@localhost")
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "test-user@localhost")
.param("password", "password");
return grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)

View file

@ -97,7 +97,7 @@ public class RefreshTokenTest {
public void nullRefreshToken() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI uri = OIDCLoginProtocolService.refreshUrl(builder).build("test");
URI uri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget target = client.target(uri);
org.keycloak.representations.AccessTokenResponse tokenResponse = null;
@ -389,10 +389,10 @@ public class RefreshTokenTest {
public void testCheckSsl() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI grantUri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("test");
URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget grantTarget = client.target(grantUri);
builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI uri = OIDCLoginProtocolService.refreshUrl(builder).build("test");
URI uri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget refreshTarget = client.target(uri);
String refreshToken = null;
@ -452,6 +452,7 @@ public class RefreshTokenTest {
protected Response executeRefreshToken(WebTarget refreshTarget, String refreshToken) {
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN);
form.param("refresh_token", refreshToken);
return refreshTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)
@ -461,7 +462,8 @@ public class RefreshTokenTest {
protected Response executeGrantAccessTokenRequest(WebTarget grantTarget) {
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param("username", "test-user@localhost")
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "test-user@localhost")
.param("password", "password");
return grantTarget.request()
.header(HttpHeaders.AUTHORIZATION, header)

View file

@ -181,11 +181,9 @@ public class ResourceOwnerPasswordCredentialsGrantTest {
events.expectLogin()
.client("resource-owner")
.session((String) null)
.detail(Details.AUTH_METHOD, "oauth_credentials")
.detail(Details.RESPONSE_TYPE, "token")
.removeDetail(Details.CODE_ID)
.removeDetail(Details.REDIRECT_URI)
.clearDetails()
.error(Errors.INVALID_CLIENT_CREDENTIALS)
.user((String) null)
.assertEvent();
}

View file

@ -24,6 +24,7 @@ package org.keycloak.testsuite.oidc;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessTokenResponse;
@ -68,7 +69,7 @@ public class UserInfoTest {
public void testSuccessfulUserInfoRequest() throws Exception {
Client client = ClientBuilder.newClient();
UriBuilder builder = UriBuilder.fromUri(org.keycloak.testsuite.Constants.AUTH_SERVER_ROOT);
URI grantUri = OIDCLoginProtocolService.grantAccessTokenUrl(builder).build("test");
URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
WebTarget grantTarget = client.target(grantUri);
AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(grantTarget);
Response response = executeUserInfoRequest(accessTokenResponse.getToken());
@ -99,7 +100,8 @@ public class UserInfoTest {
private AccessTokenResponse executeGrantAccessTokenRequest(WebTarget grantTarget) {
String header = BasicAuthHelper.createHeader("test-app", "password");
Form form = new Form();
form.param("username", "test-user@localhost")
form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
.param("username", "test-user@localhost")
.param("password", "password");
Response response = grantTarget.request()

View file

@ -136,7 +136,7 @@ public class AccessTokenPerfTest {
}
public String getLoginFormUrl(String state) {
UriBuilder b = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(baseUrl));
if (responseType != null) {
b.queryParam(OAuth2Constants.RESPONSE_TYPE, responseType);
}
@ -204,7 +204,7 @@ public class AccessTokenPerfTest {
String authorization = BasicAuthHelper.createHeader(clientId, "password");
String res = client.target(OIDCLoginProtocolService.accessCodeToTokenUrl(UriBuilder.fromUri(baseUrl)).build(realm)).request()
String res = client.target(OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl)).build(realm)).request()
.header(HttpHeaders.AUTHORIZATION, authorization)
.post(Entity.form(form), String.class);
count.incrementAndGet();

View file

@ -199,7 +199,7 @@ public class OAuthClient {
}
public String getLoginFormUrl() {
UriBuilder b = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(baseUrl));
if (responseType != null) {
b.queryParam(OAuth2Constants.RESPONSE_TYPE, responseType);
}
@ -216,7 +216,7 @@ public class OAuthClient {
}
public String getAccessTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.accessCodeToTokenUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
@ -232,12 +232,12 @@ public class OAuthClient {
}
public String getResourceOwnerPasswordCredentialGrantUrl() {
UriBuilder b = OIDCLoginProtocolService.grantAccessTokenUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getRefreshTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.refreshUrl(UriBuilder.fromUri(baseUrl));
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}

View file

@ -188,7 +188,7 @@ public class ProxyTest {
@WebResource
protected LoginPage loginPage;
public static final String LOGIN_URL = OIDCLoginProtocolService.loginPageUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
public static final String LOGIN_URL = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri("http://localhost:8081/auth")).build("demo").toString();
@Test
public void testHttp() throws Exception {