use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class JaxrsOAuthClient method resolveBearerToken.
public String resolveBearerToken(String redirectUri, String code) {
redirectUri = stripOauthParametersFromRedirect(redirectUri);
Form codeForm = new Form().param(OAuth2Constants.GRANT_TYPE, "authorization_code").param(OAuth2Constants.CODE, code).param(OAuth2Constants.CLIENT_ID, clientId).param(OAuth2Constants.REDIRECT_URI, redirectUri);
for (Map.Entry<String, Object> entry : credentials.entrySet()) {
codeForm.param(entry.getKey(), (String) entry.getValue());
}
Response res = client.target(tokenUrl).request().post(Entity.form(codeForm));
try {
if (res.getStatus() == 400) {
throw new BadRequestException();
} else if (res.getStatus() != 200) {
throw new InternalServerErrorException(new Exception("Unknown error when getting acess token"));
}
AccessTokenResponse tokenResponse = res.readEntity(AccessTokenResponse.class);
return tokenResponse.getToken();
} finally {
res.close();
}
}
use of org.keycloak.representations.AccessTokenResponse in project indy by Commonjava.
the class BasicAuthenticationOAuthTranslator method authenticate.
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
if (!enabled) {
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
logger.debug("BASIC authenticate injector checking for " + AUTHORIZATION_HEADER + " header.");
final HeaderMap headers = exchange.getRequestHeaders();
final Collection<String> vals = headers.remove(AUTHORIZATION_HEADER);
String basicAuth = null;
String bearerAuth = null;
final List<String> resultValues = new ArrayList<>();
if (vals != null) {
for (final String value : vals) {
logger.debug("Found Authorization header: '{}'", value);
if (value.toLowerCase().startsWith(BASIC_AUTH_PREFIX)) {
logger.debug("detected basic auth");
basicAuth = value;
} else if (value.toLowerCase().startsWith(BEARER_AUTH_PREFIX)) {
bearerAuth = value;
resultValues.add(value);
} else {
resultValues.add(value);
}
}
}
if (bearerAuth == null && basicAuth != null) {
final UserPass userPass = UserPass.parse(basicAuth);
logger.debug("Parsed BASIC authorization: {}", userPass);
if (userPass != null) {
final AccessTokenResponse token = lookupToken(userPass);
if (token != null) {
final String encodedToken = token.getToken();
logger.debug("Raw token: {}", encodedToken);
final String value = BEARER_AUTH_PREFIX + " " + encodedToken;
logger.debug("Adding {} value: {}", AUTHORIZATION_HEADER, value);
logger.info("BASIC authentication translated into OAuth 2.0 bearer token. Handing off to Keycloak.");
resultValues.add(value);
// KeycloakBearerTokenDebug.debugToken( encodedToken );
exchange.getResponseHeaders().add(new HttpString(INDY_BEARER_TOKEN), encodedToken);
}
}
}
logger.debug("Re-adding {} values: {}", AUTHORIZATION_HEADER, resultValues);
headers.addAll(new HttpString(AUTHORIZATION_HEADER), resultValues);
// The best we can do is lookup the token for the given basic auth fields, and inject it for keycloak to use.
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
use of org.keycloak.representations.AccessTokenResponse in project midpoint by Evolveum.
the class TestAbstractOidcRestModule method prepareClient.
private WebClient prepareClient() {
AccessTokenResponse result = getAuthzClient().obtainAccessToken(USER_ADMINISTRATOR_USERNAME, USER_ADMINISTRATOR_PASSWORD);
WebClient client = prepareClient(result.getTokenType(), result.getToken());
client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value());
return client;
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class AuthUtil method ensureToken.
public static String ensureToken(ConfigData config) {
checkAuthInfo(config);
RealmConfigData realmConfig = config.sessionRealmConfigData();
long now = currentTimeMillis();
// if it's less than 5s to expiry, renew it
if (realmConfig.getExpiresAt() - now < 5000) {
// if it's less than 5s to expiry, fail with credentials expired
if (realmConfig.getRefreshExpiresAt() != null && realmConfig.getRefreshExpiresAt() - now < 5000) {
throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
}
if (realmConfig.getSigExpiresAt() != null && realmConfig.getSigExpiresAt() - now < 5000) {
throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
}
try {
String authorization = null;
StringBuilder body = new StringBuilder();
if (realmConfig.getRefreshToken() != null) {
body.append("grant_type=refresh_token").append("&refresh_token=").append(realmConfig.getRefreshToken());
} else {
body.append("grant_type=").append(realmConfig.getGrantTypeForAuthentication());
}
body.append("&client_id=").append(urlencode(realmConfig.getClientId()));
if (realmConfig.getSigningToken() != null) {
body.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer").append("&client_assertion=").append(realmConfig.getSigningToken());
} else if (realmConfig.getSecret() != null) {
authorization = BasicAuthHelper.createHeader(realmConfig.getClientId(), realmConfig.getSecret());
}
InputStream result = doPost(realmConfig.serverUrl() + "/realms/" + realmConfig.realm() + "/protocol/openid-connect/token", APPLICATION_FORM_URL_ENCODED, APPLICATION_JSON, body.toString(), authorization);
AccessTokenResponse token = JsonSerialization.readValue(result, AccessTokenResponse.class);
saveMergeConfig(cfg -> {
RealmConfigData realmData = cfg.sessionRealmConfigData();
realmData.setToken(token.getToken());
realmData.setRefreshToken(token.getRefreshToken());
realmData.setExpiresAt(currentTimeMillis() + token.getExpiresIn() * 1000);
if (token.getRefreshToken() != null) {
realmData.setRefreshExpiresAt(currentTimeMillis() + token.getRefreshExpiresIn() * 1000);
}
});
return token.getToken();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unexpected error", e);
} catch (IOException e) {
throw new RuntimeException("Failed to read Refresh Token response", e);
}
}
return realmConfig.getToken();
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class AbstractOAuth2IdentityProvider method exchangeSessionToken.
protected Response exchangeSessionToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
String accessToken = tokenUserSession.getNote(FEDERATED_ACCESS_TOKEN);
if (accessToken == null) {
event.detail(Details.REASON, "requested_issuer is not linked");
event.error(Errors.INVALID_TOKEN);
return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
AccessTokenResponse tokenResponse = new AccessTokenResponse();
tokenResponse.setToken(accessToken);
tokenResponse.setIdToken(null);
tokenResponse.setRefreshToken(null);
tokenResponse.setRefreshExpiresIn(0);
tokenResponse.getOtherClaims().clear();
tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
event.success();
return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
Aggregations