use of org.keycloak.protocol.oidc.endpoints.TokenEndpoint.TokenExchangeSamlProtocol in project keycloak by keycloak.
the class DefaultTokenExchangeProvider method exchangeClientToSAML2Client.
protected Response exchangeClientToSAML2Client(UserModel targetUser, UserSessionModel targetUserSession, String requestedTokenType, ClientModel targetClient, String audience, String scope) {
// Create authSession with target SAML 2.0 client and authenticated user
LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
SamlService samlService = (SamlService) factory.createProtocolEndpoint(realm, event);
ResteasyProviderFactory.getInstance().injectProperties(samlService);
AuthenticationSessionModel authSession = samlService.getOrCreateLoginSessionForIdpInitiatedSso(session, realm, targetClient, null);
if (authSession == null) {
logger.error("SAML assertion consumer url not set up");
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_CLIENT, "Client requires assertion consumer url set up", Response.Status.BAD_REQUEST);
}
authSession.setAuthenticatedUser(targetUser);
event.session(targetUserSession);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(this.session, targetUserSession, authSession);
updateUserSessionFromClientAuth(targetUserSession);
// Create SAML 2.0 Assertion Response
SamlClient samlClient = new SamlClient(targetClient);
SamlProtocol samlProtocol = new TokenExchangeSamlProtocol(samlClient).setEventBuilder(event).setHttpHeaders(headers).setRealm(realm).setSession(session).setUriInfo(session.getContext().getUri());
Response samlAssertion = samlProtocol.authenticated(authSession, targetUserSession, clientSessionCtx);
if (samlAssertion.getStatus() != 200) {
throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Can not get SAML 2.0 token", Response.Status.BAD_REQUEST);
}
String xmlString = (String) samlAssertion.getEntity();
String encodedXML = Base64Url.encode(xmlString.getBytes(GeneralConstants.SAML_CHARSET));
int assertionLifespan = samlClient.getAssertionLifespan();
AccessTokenResponse res = new AccessTokenResponse();
res.setToken(encodedXML);
res.setTokenType("Bearer");
res.setExpiresIn(assertionLifespan <= 0 ? realm.getAccessCodeLifespan() : assertionLifespan);
res.setOtherClaims(OAuth2Constants.ISSUED_TOKEN_TYPE, requestedTokenType);
event.detail(Details.AUDIENCE, targetClient.getClientId());
event.success();
return cors.builder(Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).build();
}
Aggregations