use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class UserInfoTest method testSuccess_dotsInClientId.
// KEYCLOAK-8838
@Test
public void testSuccess_dotsInClientId() throws Exception {
// Create client with dot in the name
ClientRepresentation clientRep = org.keycloak.testsuite.util.ClientBuilder.create().clientId("my.foo.client").addRedirectUri("http://foo.host").secret("password").directAccessGrants().build();
RealmResource realm = adminClient.realm("test");
Response resp = realm.clients().create(clientRep);
String clientUUID = ApiUtil.getCreatedId(resp);
resp.close();
getCleanup().addClientUuid(clientUUID);
// Create role with dot in the name
realm.clients().get(clientUUID).roles().create(RoleBuilder.create().name("my.foo.role").build());
// Assign role to the user
RoleRepresentation fooRole = realm.clients().get(clientUUID).roles().get("my.foo.role").toRepresentation();
UserResource userResource = ApiUtil.findUserByUsernameId(realm, "test-user@localhost");
userResource.roles().clientLevel(clientUUID).add(Collections.singletonList(fooRole));
// Login to the new client
OAuthClient.AccessTokenResponse accessTokenResponse = oauth.clientId("my.foo.client").doGrantAccessTokenRequest("password", "test-user@localhost", "password");
AccessToken accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken());
Assert.assertNames(accessToken.getResourceAccess("my.foo.client").getRoles(), "my.foo.role");
events.clear();
// Send UserInfo request and ensure it is correct
Client client = AdminClientUtil.createResteasyClient();
try {
Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
testSuccessfulUserInfoResponse(response, "my.foo.client");
} finally {
client.close();
}
}
use of org.keycloak.representations.AccessTokenResponse in project keycloak by keycloak.
the class UserInfoTest method testAccessTokenExpired.
@Test
public void testAccessTokenExpired() {
Client client = AdminClientUtil.createResteasyClient();
try {
AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);
setTimeOffset(600);
Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String wwwAuthHeader = response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(wwwAuthHeader);
assertThat(wwwAuthHeader, CoreMatchers.containsString("Bearer"));
assertThat(wwwAuthHeader, CoreMatchers.containsString("error=\"" + OAuthErrorException.INVALID_TOKEN + "\""));
response.close();
events.expect(EventType.USER_INFO_REQUEST_ERROR).error(Errors.INVALID_TOKEN).user(Matchers.nullValue(String.class)).session(Matchers.nullValue(String.class)).detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN).client((String) null).assertEvent();
} finally {
client.close();
}
}
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 TokenEndpoint method createTokenResponse.
public Response createTokenResponse(UserModel user, UserSessionModel userSession, ClientSessionContext clientSessionCtx, String scopeParam, boolean code) {
AccessToken token = tokenManager.createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, event, session, userSession, clientSessionCtx).accessToken(token);
if (OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken()) {
responseBuilder.generateRefreshToken();
}
checkMtlsHoKToken(responseBuilder, OIDCAdvancedConfigWrapper.fromClientModel(client).isUseRefreshToken());
if (TokenUtil.isOIDCRequest(scopeParam)) {
responseBuilder.generateIDToken().generateAccessTokenHash();
}
AccessTokenResponse res = null;
if (code) {
try {
res = responseBuilder.build();
} catch (RuntimeException re) {
if ("can not get encryption KEK".equals(re.getMessage())) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "can not get encryption KEK", Response.Status.BAD_REQUEST);
} else {
throw re;
}
}
} else {
res = responseBuilder.build();
}
event.success();
return cors.builder(Response.ok(res).type(MediaType.APPLICATION_JSON_TYPE)).build();
}
Aggregations