use of org.keycloak.representations.AccessTokenResponse in project indy by Commonjava.
the class BasicAuthenticationOAuthTranslator method lookupToken.
private AccessTokenResponse lookupToken(final UserPass userPass) {
final URI uri = KeycloakUriBuilder.fromUri(config.getUrl()).path(ServiceUrlConstants.TOKEN_PATH).build(config.getRealm());
logger.debug("Looking up token at: {}", uri);
final HttpPost request = new HttpPost(uri);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(USERNAME, userPass.getUser()));
params.add(new BasicNameValuePair(PASSWORD, userPass.getPassword()));
params.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
final String authorization = BasicAuthHelper.createHeader(config.getServerResource(), config.getServerCredentialSecret());
request.setHeader(AUTHORIZATION_HEADER, authorization);
CloseableHttpClient client = null;
AccessTokenResponse tokenResponse = null;
try {
client = http.createClient(uri.getHost());
final UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "UTF-8");
request.setEntity(form);
CloseableHttpResponse response = client.execute(request);
logger.debug("Got response status: {}", response.getStatusLine());
if (response.getStatusLine().getStatusCode() == 200) {
try (InputStream in = response.getEntity().getContent()) {
final String json = IOUtils.toString(in);
logger.debug("Token response:\n\n{}\n\n", json);
tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
}
}
} catch (IOException | IndyHttpException e) {
logger.error(String.format("Keycloak token request failed: %s", e.getMessage()), e);
} finally {
IOUtils.closeQuietly(client);
}
return tokenResponse;
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class BasicAuthRequestAuthenticator method authenticate.
public AuthOutcome authenticate(HttpFacade exchange) {
List<String> authHeaders = exchange.getRequest().getHeaders("Authorization");
if (authHeaders == null || authHeaders.isEmpty()) {
challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_AUTHORIZATION_HEADER, null, null);
return AuthOutcome.NOT_ATTEMPTED;
}
tokenString = null;
for (String authHeader : authHeaders) {
String[] split = authHeader.trim().split("\\s+");
if (split.length != 2)
continue;
if (!split[0].equalsIgnoreCase("Basic"))
continue;
tokenString = split[1];
}
if (tokenString == null) {
challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, null, null);
return AuthOutcome.NOT_ATTEMPTED;
}
AccessTokenResponse atr = null;
try {
String userpw = new String(Base64.decode(tokenString));
int seperatorIndex = userpw.indexOf(":");
String user = userpw.substring(0, seperatorIndex);
String pw = userpw.substring(seperatorIndex + 1);
atr = getToken(user, pw);
tokenString = atr.getToken();
} catch (Exception e) {
log.debug("Failed to obtain token", e);
challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "no_token", e.getMessage());
return AuthOutcome.FAILED;
}
return authenticateToken(exchange, atr.getToken());
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class KeycloakInstalled method processCode.
private void processCode(String code, String redirectUri, Pkce pkce) throws IOException, ServerRequest.HttpFailure, VerificationException {
AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken(deployment, code, redirectUri, null, pkce == null ? null : pkce.getCodeVerifier());
parseAccessToken(tokenResponse);
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class ConfigCredentialsCmd method process.
public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
// check server
if (server == null) {
throw new IllegalArgumentException("Required option not specified: --server");
}
try {
new URL(server);
} catch (Exception e) {
throw new RuntimeException("Invalid server endpoint url: " + server, e);
}
if (realm == null)
throw new IllegalArgumentException("Required option not specified: --realm");
String signedRequestToken = null;
boolean clientSet = clientId != null;
applyDefaultOptionValues();
String grantTypeForAuthentication = null;
if (user != null) {
grantTypeForAuthentication = OAuth2Constants.PASSWORD;
printErr("Logging into " + server + " as user " + user + " of realm " + realm);
// if user was set there needs to be a password so we can authenticate
if (password == null) {
password = readSecret("Enter password: ", commandInvocation);
}
// if secret was set to be read from stdin, then ask for it
if ("-".equals(secret) && keystore == null) {
secret = readSecret("Enter client secret: ", commandInvocation);
}
} else if (keystore != null || secret != null || clientSet) {
grantTypeForAuthentication = OAuth2Constants.CLIENT_CREDENTIALS;
printErr("Logging into " + server + " as " + "service-account-" + clientId + " of realm " + realm);
if (keystore == null) {
if (secret == null) {
secret = readSecret("Enter client secret: ", commandInvocation);
}
}
}
if (keystore != null) {
if (secret != null) {
throw new IllegalArgumentException("Can't use both --keystore and --secret");
}
if (!new File(keystore).isFile()) {
throw new RuntimeException("No such keystore file: " + keystore);
}
if (storePass == null) {
storePass = readSecret("Enter keystore password: ", commandInvocation);
keyPass = readSecret("Enter key password: ", commandInvocation);
}
if (keyPass == null) {
keyPass = storePass;
}
if (alias == null) {
alias = clientId;
}
String realmInfoUrl = server + "/realms/" + realm;
signedRequestToken = AuthUtil.getSignedRequestToken(keystore, storePass, keyPass, alias, sigLifetime, clientId, realmInfoUrl);
}
// if only server and realm are set, just save config and be done
if (user == null && secret == null && keystore == null) {
getHandler().saveMergeConfig(config -> {
config.setServerUrl(server);
config.setRealm(realm);
});
return CommandResult.SUCCESS;
}
setupTruststore(copyWithServerInfo(loadConfig()), commandInvocation);
// now use the token endpoint to retrieve access token, and refresh token
AccessTokenResponse tokens = signedRequestToken != null ? getAuthTokensByJWT(server, realm, user, password, clientId, signedRequestToken) : secret != null ? getAuthTokensBySecret(server, realm, user, password, clientId, secret) : getAuthTokens(server, realm, user, password, clientId);
Long sigExpiresAt = signedRequestToken == null ? null : System.currentTimeMillis() + sigLifetime * 1000;
// save tokens to config file
saveTokens(tokens, server, realm, clientId, signedRequestToken, sigExpiresAt, secret, grantTypeForAuthentication);
return CommandResult.SUCCESS;
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class AdminConsolePermissionsCalculatedTest method changeRealmTokenAlgorithm.
@Test
public void changeRealmTokenAlgorithm() throws Exception {
try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString());
Creator c = Creator.create(adminClient, RealmBuilder.create().name(REALM_NAME).build())) {
AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
assertNotNull(adminClient.realms().findAll());
String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami";
JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson();
assertTrue("Permissions for " + Config.getAdminRealm() + " realm.", jsonNode.at("/realm_access/" + Config.getAdminRealm()).isArray());
assertTrue("Permissions for " + REALM_NAME + " realm.", jsonNode.at("/realm_access/" + REALM_NAME).isArray());
}
}
Aggregations