use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class BackchannelAuthenticationCallbackEndpoint method verifyAuthenticationRequest.
private BackchannelAuthCallbackContext verifyAuthenticationRequest(HttpHeaders headers) {
String rawBearerToken = AppAuthManager.extractAuthorizationHeaderTokenOrReturnNull(headers);
if (rawBearerToken == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.UNAUTHORIZED);
}
AccessToken bearerToken;
try {
bearerToken = TokenVerifier.createWithoutSignature(session.tokens().decode(rawBearerToken, AccessToken.class)).withDefaultChecks().realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).checkActive(true).audience(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).verify().getToken();
} catch (Exception e) {
event.error(Errors.INVALID_TOKEN);
// authentication channel id format is invalid or it has already been used
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
OAuth2DeviceCodeModel deviceCode = store.getByUserCode(realm, bearerToken.getId());
if (deviceCode == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
if (!deviceCode.isPending()) {
cancelRequest(bearerToken.getId());
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
}
ClientModel issuedFor = realm.getClientByClientId(bearerToken.getIssuedFor());
if (issuedFor == null || !issuedFor.isEnabled()) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid token recipient", Response.Status.BAD_REQUEST);
}
if (!deviceCode.getClientId().equals(issuedFor.getClientId())) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Token recipient mismatch", Response.Status.BAD_REQUEST);
}
session.getContext().setClient(issuedFor);
event.client(issuedFor);
return new BackchannelAuthCallbackContext(bearerToken, deviceCode);
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class BackchannelAuthenticationCallbackEndpoint method processAuthenticationChannelResult.
@Path("/")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response processAuthenticationChannelResult(AuthenticationChannelResponse response) {
event.event(EventType.LOGIN);
BackchannelAuthCallbackContext ctx = verifyAuthenticationRequest(httpRequest.getHttpHeaders());
AccessToken bearerToken = ctx.bearerToken;
OAuth2DeviceCodeModel deviceModel = ctx.deviceModel;
Status status = response.getStatus();
if (status == null) {
event.error(Errors.INVALID_REQUEST);
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authentication status", Response.Status.BAD_REQUEST);
}
switch(status) {
case SUCCEED:
approveRequest(bearerToken, response.getAdditionalParams());
break;
case CANCELLED:
case UNAUTHORIZED:
denyRequest(bearerToken, status);
break;
}
// Call the notification endpoint
ClientModel client = session.getContext().getClient();
CibaConfig cibaConfig = realm.getCibaPolicy();
if (cibaConfig.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
sendClientNotificationRequest(client, cibaConfig, deviceModel);
}
return Response.ok(MediaType.APPLICATION_JSON_TYPE).build();
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class HttpAuthenticationChannelProvider method createBearerToken.
private String createBearerToken(CIBAAuthenticationRequest request, ClientModel client) {
AccessToken bearerToken = new AccessToken();
bearerToken.type(TokenUtil.TOKEN_TYPE_BEARER);
bearerToken.issuer(request.getIssuer());
bearerToken.id(request.getAuthResultId());
bearerToken.issuedFor(client.getClientId());
bearerToken.audience(request.getIssuer());
bearerToken.exp(request.getExp());
bearerToken.subject(request.getSubject());
return session.tokens().encode(bearerToken);
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class AbstractUserRoleMappingMapper method checkAccessToken.
// Special case when roles are put to the access token via "realmAcces, resourceAccess" properties
private static boolean checkAccessToken(IDToken idToken, List<String> path, Object attributeValue) {
if (!(idToken instanceof AccessToken)) {
return false;
}
if (!(attributeValue instanceof Collection)) {
return false;
}
Collection<String> roles = (Collection<String>) attributeValue;
AccessToken token = (AccessToken) idToken;
AccessToken.Access access = null;
if (path.size() == 2 && "realm_access".equals(path.get(0)) && "roles".equals(path.get(1))) {
access = token.getRealmAccess();
if (access == null) {
access = new AccessToken.Access();
token.setRealmAccess(access);
}
} else if (path.size() == 3 && "resource_access".equals(path.get(0)) && "roles".equals(path.get(2))) {
String clientId = path.get(1);
access = token.addAccess(clientId);
} else {
return false;
}
for (String role : roles) {
access.addRole(role);
}
return true;
}
use of org.keycloak.representations.AccessToken in project keycloak by keycloak.
the class LinkAndExchangeServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Cache-Control", "no-cache");
if (request.getRequestURI().endsWith("/link") && request.getParameter("response") == null) {
String provider = request.getParameter("provider");
String realm = request.getParameter("realm");
KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
AccessToken token = session.getToken();
String tokenString = session.getTokenString();
String clientId = token.getIssuedFor();
String linkUrl = null;
try {
AccessTokenResponse response = doTokenExchange(realm, tokenString, provider, clientId, "password");
String error = response.getError();
if (error != null) {
System.out.println("*** error : " + error);
System.out.println("*** link-url: " + response.getOtherClaims().get("account-link-url"));
linkUrl = (String) response.getOtherClaims().get("account-link-url");
} else {
Assert.assertNotNull(response.getToken());
resp.setStatus(200);
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
pw.println("Account Linked");
pw.print("</body></html>");
pw.flush();
return;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
String redirectUri = KeycloakUriBuilder.fromUri(request.getRequestURL().toString()).replaceQuery(null).queryParam("response", "true").queryParam("realm", realm).queryParam("provider", provider).build().toString();
String accountLinkUrl = KeycloakUriBuilder.fromUri(linkUrl).queryParam("redirect_uri", redirectUri).build().toString();
resp.setStatus(302);
resp.setHeader("Location", accountLinkUrl);
} else if (request.getRequestURI().endsWith("/link") && request.getParameter("response") != null) {
resp.setStatus(200);
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
String error = request.getParameter("link_error");
if (error != null) {
pw.println("Link error: " + error);
} else {
pw.println("Account Linked");
}
pw.println("trying exchange");
try {
String provider = request.getParameter("provider");
String realm = request.getParameter("realm");
KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
AccessToken token = session.getToken();
String clientId = token.getIssuedFor();
String tokenString = session.getTokenString();
AccessTokenResponse response = doTokenExchange(realm, tokenString, provider, clientId, "password");
error = (String) response.getOtherClaims().get("error");
if (error == null) {
if (response.getToken() != null)
pw.println("Exchange token received");
} else {
pw.print("Error with exchange: " + error);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
pw.print("</body></html>");
pw.flush();
} else {
resp.setStatus(200);
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
pw.println("Unknown request: " + request.getRequestURL().toString());
pw.print("</body></html>");
pw.flush();
}
}
Aggregations