use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.
the class SkeletonKeyTokenTest method testRSA.
@Test
public void testRSA() throws Exception {
AccessToken token = createSimpleToken();
token.id("111");
token.addAccess("foo").addRole("admin");
token.addAccess("bar").addRole("user");
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String encoded = new JWSBuilder().jsonContent(token).rsa256(keyPair.getPrivate());
JWSInput input = new JWSInput(encoded);
token = input.readJsonContent(AccessToken.class);
Assert.assertEquals("111", token.getId());
Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.
the class OIDCIdentityProvider method validateToken.
protected JsonWebToken validateToken(String encodedToken, boolean ignoreAudience) {
if (encodedToken == null) {
throw new IdentityBrokerException("No token from server.");
}
JsonWebToken token;
try {
JWSInput jws = new JWSInput(encodedToken);
if (!verify(jws)) {
throw new IdentityBrokerException("token signature validation failed");
}
token = jws.readJsonContent(JsonWebToken.class);
} catch (JWSInputException e) {
throw new IdentityBrokerException("Invalid token", e);
}
String iss = token.getIssuer();
if (!token.isActive(getConfig().getAllowedClockSkew())) {
throw new IdentityBrokerException("Token is no longer valid");
}
if (!ignoreAudience && !token.hasAudience(getConfig().getClientId())) {
throw new IdentityBrokerException("Wrong audience from token.");
}
if (!ignoreAudience && (token.getIssuedFor() != null && !getConfig().getClientId().equals(token.getIssuedFor()))) {
throw new IdentityBrokerException("Token issued for does not match client id");
}
String trustedIssuers = getConfig().getIssuer();
if (trustedIssuers != null && trustedIssuers.length() > 0) {
String[] issuers = trustedIssuers.split(",");
for (String trustedIssuer : issuers) {
if (iss != null && iss.equals(trustedIssuer.trim())) {
return token;
}
}
throw new IdentityBrokerException("Wrong issuer from token. Got: " + iss + " expected: " + getConfig().getIssuer());
}
return token;
}
use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.
the class AdminController method showTokens.
@RequestMapping(path = "/TokenServlet", method = RequestMethod.GET)
public String showTokens(WebRequest req, Model model, @RequestParam Map<String, String> attributes) throws IOException {
String timeOffset = attributes.get("timeOffset");
if (!StringUtils.isEmpty(timeOffset)) {
int offset;
try {
offset = Integer.parseInt(timeOffset, 10);
} catch (NumberFormatException e) {
offset = 0;
}
Time.setOffset(offset);
}
RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName(), WebRequest.SCOPE_REQUEST);
String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(ctx.getToken());
RefreshToken refreshToken;
try {
refreshToken = new JWSInput(ctx.getRefreshToken()).readJsonContent(RefreshToken.class);
} catch (JWSInputException e) {
throw new IOException(e);
}
String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken);
model.addAttribute("accessToken", accessTokenPretty);
model.addAttribute("refreshToken", refreshTokenPretty);
model.addAttribute("accessTokenString", ctx.getTokenString());
return "tokens";
}
use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.
the class MyResourcesTest method createResource.
private ResourceRepresentation createResource(AuthzClient authzClient, AuthorizationResource authorization, int i) {
ResourceRepresentation resource = new ResourceRepresentation();
resource.setOwnerManagedAccess(true);
try {
final byte[] content = new JWSInput(authzClient.obtainAccessToken("jdoe", PASSWORD).getToken()).getContent();
final AccessToken accessToken = JsonSerialization.readValue(content, AccessToken.class);
resource.setOwner(accessToken.getSubject());
} catch (Exception e) {
throw new RuntimeException(e);
}
resource.setName("Resource " + i);
resource.setDisplayName("Display Name " + i);
resource.setIconUri("Icon Uri " + i);
resource.addScope("Scope A", "Scope B", "Scope C", "Scope D");
resource.setUri("http://resourceServer.com/resources/" + i);
try (Response response1 = authorization.resources().create(resource)) {
resource.setId(response1.readEntity(ResourceRepresentation.class).getId());
}
return resource;
}
use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.
the class ClientPoliciesTest method testSecureResponseTypeExecutor.
@Test
public void testSecureResponseTypeExecutor() throws Exception {
// register profiles
String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
updateProfiles(json);
// register policies
json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "A Primeira Politica", Boolean.TRUE).addCondition(ClientRolesConditionFactory.PROVIDER_ID, createClientRolesConditionConfig(Arrays.asList(SAMPLE_CLIENT_ROLE))).addProfile(PROFILE_NAME).toRepresentation()).toString();
updatePolicies(json);
String clientId = generateSuffixedName(CLIENT_NAME);
String clientSecret = "secret";
String cid = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
clientRep.setSecret(clientSecret);
clientRep.setStandardFlowEnabled(Boolean.TRUE);
clientRep.setImplicitFlowEnabled(Boolean.TRUE);
clientRep.setPublicClient(Boolean.FALSE);
});
adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(SAMPLE_CLIENT_ROLE).build());
oauth.clientId(clientId);
oauth.openLoginForm();
assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
assertEquals("invalid response_type", oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
oauth.nonce("vbwe566fsfffds");
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
String sessionId = loginEvent.getSessionId();
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
assertEquals(200, res.getStatusCode());
events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
oauth.doLogout(res.getRefreshToken(), clientSecret);
events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
// update profiles
json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.TRUE)).toRepresentation()).toString();
updateProfiles(json);
// token response type allowed
oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
oauth.nonce("cie8cjcwiw");
oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
loginEvent = events.expectLogin().client(clientId).assertEvent();
sessionId = loginEvent.getSessionId();
codeId = loginEvent.getDetails().get(Details.CODE_ID);
code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
res = oauth.doAccessTokenRequest(code, clientSecret);
assertEquals(200, res.getStatusCode());
events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
oauth.doLogout(res.getRefreshToken(), clientSecret);
events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
// shall allow code using response_mode jwt
oauth.responseType(OIDCResponseType.CODE);
oauth.responseMode("jwt");
OAuthClient.AuthorizationEndpointResponse authzResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
String jwsResponse = authzResponse.getResponse();
AuthorizationResponseToken responseObject = oauth.verifyAuthorizationResponseToken(jwsResponse);
code = (String) responseObject.getOtherClaims().get(OAuth2Constants.CODE);
res = oauth.doAccessTokenRequest(code, clientSecret);
assertEquals(200, res.getStatusCode());
// update profiles
json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.FALSE)).toRepresentation()).toString();
updateProfiles(json);
oauth.openLogout();
// token response type allowed
oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
oauth.responseMode("jwt");
oauth.openLoginForm();
final JWSInput errorJws = new JWSInput(new OAuthClient.AuthorizationEndpointResponse(oauth).getResponse());
JsonNode errorClaims = JsonSerialization.readValue(errorJws.getContent(), JsonNode.class);
assertEquals(OAuthErrorException.INVALID_REQUEST, errorClaims.get("error").asText());
}
Aggregations