Java源码示例:org.keycloak.events.EventBuilder
示例1
@Override
protected BrokeredIdentityContext exchangeExternalImpl(EventBuilder event, MultivaluedMap<String, String> params) {
if (!supportsExternalExchange()) return null;
String subjectToken = params.getFirst(OAuth2Constants.SUBJECT_TOKEN);
if (subjectToken == null) {
event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN + " param unset");
event.error(Errors.INVALID_TOKEN);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "token not set", Response.Status.BAD_REQUEST);
}
String subjectTokenType = params.getFirst(OAuth2Constants.SUBJECT_TOKEN_TYPE);
if (subjectTokenType == null) {
subjectTokenType = OAuth2Constants.ACCESS_TOKEN_TYPE;
}
if (OAuth2Constants.JWT_TOKEN_TYPE.equals(subjectTokenType) || OAuth2Constants.ID_TOKEN_TYPE.equals(subjectTokenType)) {
return validateJwt(event, subjectToken, subjectTokenType);
} else if (OAuth2Constants.ACCESS_TOKEN_TYPE.equals(subjectTokenType)) {
return validateExternalTokenThroughUserInfo(event, subjectToken, subjectTokenType);
} else {
event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN_TYPE + " invalid");
event.error(Errors.INVALID_TOKEN_TYPE);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token type", Response.Status.BAD_REQUEST);
}
}
示例2
public SessionCodeChecks(RealmModel realm, UriInfo uriInfo, HttpRequest request, ClientConnection clientConnection, KeycloakSession session, EventBuilder event,
String authSessionId, String code, String execution, String clientId, String tabId, String flowPath) {
this.realm = realm;
this.uriInfo = uriInfo;
this.request = request;
this.clientConnection = clientConnection;
this.session = session;
this.event = event;
this.code = code;
this.execution = execution;
this.clientId = clientId;
this.tabId = tabId;
this.flowPath = flowPath;
this.authSessionId = authSessionId;
}
示例3
public static <CLIENT_SESSION extends CommonClientSessionModel> ParseResult<CLIENT_SESSION> parseResult(String code, String tabId,
KeycloakSession session, RealmModel realm, ClientModel client,
EventBuilder event, Class<CLIENT_SESSION> sessionClass) {
ParseResult<CLIENT_SESSION> result = new ParseResult<>();
if (code == null) {
result.illegalHash = true;
return result;
}
try {
CodeGenerateUtil.ClientSessionParser<CLIENT_SESSION> clientSessionParser = CodeGenerateUtil.getParser(sessionClass);
result.clientSession = getClientSession(code, tabId, session, realm, client, event, clientSessionParser);
return parseResult(code, session, realm, result, clientSessionParser);
} catch (RuntimeException e) {
result.illegalHash = true;
return result;
}
}
示例4
public static AuthenticationProcessor getAuthenticationProcessor(KeycloakSession session, EventBuilder event) {
RealmModel realm = session.getContext().getRealm();
AuthenticationFlowModel clientAuthFlow = realm.getClientAuthenticationFlow();
String flowId = clientAuthFlow.getId();
AuthenticationProcessor processor = new AuthenticationProcessor();
processor.setFlowId(flowId)
.setConnection(session.getContext().getConnection())
.setEventBuilder(event)
.setRealm(realm)
.setSession(session)
.setUriInfo(session.getContext().getUri())
.setRequest(session.getContext().getContextObject(HttpRequest.class));
return processor;
}
示例5
@Override
public void processAction(RequiredActionContext context) {
EventBuilder event = context.getEvent().clone().event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, context.getUser().getEmail());
String code = context.getAuthenticationSession().getAuthNote(Constants.VERIFY_EMAIL_CODE);
if (code == null) {
requiredActionChallenge(context);
return;
}
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
String emailCode = formData.getFirst(EMAIL_CODE);
if (!code.equals(emailCode)) {
context.challenge(
challenge(context).message(Messages.INVALID_CODE)
);
event.error(Errors.INVALID_CODE);
return;
}
event.success();
context.success();
}
示例6
@Override
protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode node) {
JsonNode profile = node.get("items").get(0);
BrokeredIdentityContext user = new BrokeredIdentityContext(getJsonProperty(profile, "user_id"));
String username = extractUsernameFromProfileURL(getJsonProperty(profile, "link"));
user.setUsername(username);
user.setName(unescapeHtml3(getJsonProperty(profile, "display_name")));
// email is not provided
// user.setEmail(getJsonProperty(profile, "email"));
user.setIdpConfig(getConfig());
user.setIdp(this);
AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());
return user;
}
示例7
@Path("{realm}/protocol/{protocol}")
public Object getProtocol(final @PathParam("realm") String name,
final @PathParam("protocol") String protocol) {
RealmModel realm = init(name);
LoginProtocolFactory factory = (LoginProtocolFactory)session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, protocol);
if(factory == null){
logger.debugf("protocol %s not found", protocol);
throw new NotFoundException("Protocol not found");
}
EventBuilder event = new EventBuilder(realm, session, clientConnection);
Object endpoint = factory.createProtocolEndpoint(realm, event);
ResteasyProviderFactory.getInstance().injectProperties(endpoint);
return endpoint;
}
示例8
@Override
protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode profile) {
BrokeredIdentityContext user = new BrokeredIdentityContext(getJsonProperty(profile, "id"));
String username = getJsonProperty(profile, "login");
user.setUsername(username);
user.setName(getJsonProperty(profile, "name"));
user.setEmail(getJsonProperty(profile, "email"));
user.setIdpConfig(getConfig());
user.setIdp(this);
AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());
return user;
}
示例9
@Override
public Response exchangeFromToken(UriInfo uriInfo, EventBuilder builder, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject, MultivaluedMap<String, String> params) {
String requestedType = params.getFirst(OAuth2Constants.REQUESTED_TOKEN_TYPE);
if (requestedType != null && !requestedType.equals(TWITTER_TOKEN_TYPE)) {
return exchangeUnsupportedRequiredType();
}
if (!getConfig().isStoreToken()) {
String brokerId = tokenUserSession.getNote(Details.IDENTITY_PROVIDER);
if (brokerId == null || !brokerId.equals(getConfig().getAlias())) {
return exchangeNotLinkedNoStore(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
return exchangeSessionToken(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
} else {
return exchangeStoredToken(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
}
示例10
public CASLoginProtocol(KeycloakSession session, RealmModel realm, UriInfo uriInfo, HttpHeaders headers, EventBuilder event) {
this.session = session;
this.realm = realm;
this.uriInfo = uriInfo;
this.headers = headers;
this.event = event;
}
示例11
@Override
protected String getProfileEndpointForValidation(EventBuilder event) {
String userInfoUrl = getUserInfoUrl();
if (getConfig().isDisableUserInfoService() || userInfoUrl == null || userInfoUrl.isEmpty()) {
event.detail(Details.REASON, "user info service disabled");
event.error(Errors.INVALID_TOKEN);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
}
return userInfoUrl;
}
示例12
public DockerAuthV2Protocol(final KeycloakSession session, final RealmModel realm, final UriInfo uriInfo, final HttpHeaders headers, final EventBuilder event) {
this.session = session;
this.realm = realm;
this.uriInfo = uriInfo;
this.headers = headers;
this.event = event;
}
示例13
public AccessTokenResponseBuilder(RealmModel realm, ClientModel client, EventBuilder event, KeycloakSession session,
UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
this.realm = realm;
this.client = client;
this.event = event;
this.session = session;
this.userSession = userSession;
this.clientSessionCtx = clientSessionCtx;
}
示例14
@Override
public Response exchangeFromToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject, MultivaluedMap<String, String> params) {
// check to see if we have a token exchange in session
// in other words check to see if this session was created by an external exchange
Response tokenResponse = hasExternalExchangeToken(event, tokenUserSession, params);
if (tokenResponse != null) return tokenResponse;
// going further we only support access token type? Why?
String requestedType = params.getFirst(OAuth2Constants.REQUESTED_TOKEN_TYPE);
if (requestedType != null && !requestedType.equals(OAuth2Constants.ACCESS_TOKEN_TYPE)) {
event.detail(Details.REASON, "requested_token_type unsupported");
event.error(Errors.INVALID_REQUEST);
return exchangeUnsupportedRequiredType();
}
if (!getConfig().isStoreToken()) {
// if token isn't stored, we need to see if this session has been linked
String brokerId = tokenUserSession.getNote(Details.IDENTITY_PROVIDER);
brokerId = brokerId == null ? tokenUserSession.getNote(IdentityProvider.EXTERNAL_IDENTITY_PROVIDER) : brokerId;
if (brokerId == null || !brokerId.equals(getConfig().getAlias())) {
event.detail(Details.REASON, "requested_issuer has not linked");
event.error(Errors.INVALID_REQUEST);
return exchangeNotLinkedNoStore(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
}
return exchangeSessionToken(uriInfo, event, authorizedClient, tokenUserSession, tokenSubject);
} else {
return exchangeStoredToken(uriInfo, event, authorizedClient, tokenUserSession, tokenSubject);
}
}
示例15
public static String getClientId(EventBuilder event, KeycloakSession session, MultivaluedMap<String, String> requestParams) {
List<String> clientParam = requestParams.get(OIDCLoginProtocol.CLIENT_ID_PARAM);
if (clientParam != null && clientParam.size() == 1) {
return clientParam.get(0);
} else {
event.error(Errors.INVALID_REQUEST);
throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
}
}
示例16
public AccountCredentialResource(KeycloakSession session, EventBuilder event, UserModel user, Auth auth) {
this.session = session;
this.event = event;
this.user = user;
this.auth = auth;
realm = session.getContext().getRealm();
}
示例17
@Path("{realm}/login-actions")
public LoginActionsService getLoginActionsService(final @PathParam("realm") String name) {
RealmModel realm = init(name);
EventBuilder event = new EventBuilder(realm, session, clientConnection);
LoginActionsService service = new LoginActionsService(realm, event);
ResteasyProviderFactory.getInstance().injectProperties(service);
return service;
}
示例18
@Override
protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode userInfo) {
String id = getJsonProperty(userInfo, "sub");
if (id == null) {
event.detail(Details.REASON, "sub claim is null from user info json");
event.error(Errors.INVALID_TOKEN);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
}
BrokeredIdentityContext identity = new BrokeredIdentityContext(id);
String name = getJsonProperty(userInfo, "name");
String preferredUsername = getUsernameFromUserInfo(userInfo);
String email = getJsonProperty(userInfo, "email");
AbstractJsonUserAttributeMapper.storeUserProfileForMapper(identity, userInfo, getConfig().getAlias());
identity.setId(id);
identity.setName(name);
identity.setEmail(email);
identity.setBrokerUserId(getConfig().getAlias() + "." + id);
if (preferredUsername == null) {
preferredUsername = email;
}
if (preferredUsername == null) {
preferredUsername = id;
}
identity.setUsername(preferredUsername);
return identity;
}
示例19
public static ClientAuthResult authorizeClient(KeycloakSession session, EventBuilder event) {
AuthenticationProcessor processor = getAuthenticationProcessor(session, event);
Response response = processor.authenticateClient();
if (response != null) {
throw new WebApplicationException(response);
}
ClientModel client = processor.getClient();
if (client == null) {
throw new ErrorResponseException(Errors.INVALID_CLIENT, "Client authentication ended, but client is null", Response.Status.BAD_REQUEST);
}
String protocol = client.getProtocol();
if (protocol == null) {
logger.warnf("Client '%s' doesn't have protocol set. Fallback to openid-connect. Please fix client configuration", client.getClientId());
protocol = OIDCLoginProtocol.LOGIN_PROTOCOL;
}
if (!protocol.equals(OIDCLoginProtocol.LOGIN_PROTOCOL)) {
event.error(Errors.INVALID_CLIENT);
throw new ErrorResponseException(Errors.INVALID_CLIENT, "Wrong client protocol.", Response.Status.BAD_REQUEST);
}
session.getContext().setClient(client);
return new ClientAuthResult(client, processor.getClientAuthAttributes());
}
示例20
protected static Response executionActions(KeycloakSession session, AuthenticationSessionModel authSession,
HttpRequest request, EventBuilder event, RealmModel realm, UserModel user,
Set<String> requiredActions) {
List<RequiredActionProviderModel> sortedRequiredActions = sortRequiredActionsByPriority(realm, requiredActions);
for (RequiredActionProviderModel model : sortedRequiredActions) {
Response response = executeAction(session, authSession, model, request, event, realm, user, false);
if (response != null) {
return response;
}
}
String kcAction = authSession.getClientNote(Constants.KC_ACTION);
if (kcAction != null) {
for (RequiredActionProviderModel m : realm.getRequiredActionProviders()) {
if (m.getProviderId().equals(kcAction)) {
return executeAction(session, authSession, m, request, event, realm, user, true);
}
}
logger.debugv("Requested action {0} not configured for realm", kcAction);
setKcActionStatus(kcAction, RequiredActionContext.KcActionStatus.ERROR, authSession);
}
return null;
}
示例21
public OIDCLoginProtocol(KeycloakSession session, RealmModel realm, UriInfo uriInfo, HttpHeaders headers, EventBuilder event) {
this.session = session;
this.realm = realm;
this.uriInfo = uriInfo;
this.headers = headers;
this.event = event;
}
示例22
public static Response nextActionAfterAuthentication(KeycloakSession session, AuthenticationSessionModel authSession,
ClientConnection clientConnection,
HttpRequest request, UriInfo uriInfo, EventBuilder event) {
Response requiredAction = actionRequired(session, authSession, clientConnection, request, uriInfo, event);
if (requiredAction != null) return requiredAction;
return finishedRequiredActions(session, authSession, null, clientConnection, request, uriInfo, event);
}
示例23
@Override
public void processAction(RequiredActionContext context) {
EventBuilder event = context.getEvent();
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
event.event(EventType.UPDATE_PASSWORD);
String passwordNew = formData.getFirst(PASSWORD_NEW);
String passwordConfirm = formData.getFirst(PASSWORD_CONFIRM);
EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR)
.client(context.getAuthenticationSession().getClient())
.user(context.getAuthenticationSession().getAuthenticatedUser());
if (Validation.isBlank(passwordNew)) {
context.challenge(challenge(context).message(Messages.MISSING_PASSWORD));
errorEvent.error(Errors.PASSWORD_MISSING);
return;
} else if (!passwordNew.equals(passwordConfirm)) {
context.challenge(challenge(context).message(Messages.NOTMATCH_PASSWORD));
errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
return;
}
try {
context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew, false));
context.success();
} catch (ModelException me) {
errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
context.challenge(challenge(context).text(me.getMessage()));
return;
} catch (Exception ape) {
errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
context.challenge(challenge(context).text(ape.getMessage()));
return;
}
}
示例24
private Response sendVerifyEmail(KeycloakSession session, LoginFormsProvider forms, UserModel user, AuthenticationSessionModel authSession, EventBuilder event) throws UriBuilderException, IllegalArgumentException {
RealmModel realm = session.getContext().getRealm();
UriInfo uriInfo = session.getContext().getUri();
int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(VerifyEmailActionToken.TOKEN_TYPE);
int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
VerifyEmailActionToken token = new VerifyEmailActionToken(user.getId(), absoluteExpirationInSecs, authSessionEncodedId, user.getEmail(), authSession.getClient().getClientId());
UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
authSession.getClient().getClientId(), authSession.getTabId());
String link = builder.build(realm.getName()).toString();
long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);
try {
session
.getProvider(EmailTemplateProvider.class)
.setAuthenticationSession(authSession)
.setRealm(realm)
.setUser(user)
.sendVerifyEmail(link, expirationInMinutes);
event.success();
} catch (EmailException e) {
logger.error("Failed to send verification email", e);
event.error(Errors.EMAIL_SEND_FAILED);
}
return forms.createResponse(UserModel.RequiredAction.VERIFY_EMAIL);
}
示例25
public ActionTokenContext(KeycloakSession session, RealmModel realm, UriInfo uriInfo,
ClientConnection clientConnection, HttpRequest request,
EventBuilder event, ActionTokenHandler<T> handler, String executionId,
ProcessAuthenticateFlow processFlow, ProcessBrokerFlow processBrokerFlow) {
this.session = session;
this.realm = realm;
this.uriInfo = uriInfo;
this.clientConnection = clientConnection;
this.request = request;
this.event = event;
this.handler = handler;
this.executionId = executionId;
this.processAuthenticateFlow = processFlow;
this.processBrokerFlow = processBrokerFlow;
}
示例26
public AccountRestService(KeycloakSession session, Auth auth, ClientModel client, EventBuilder event) {
this.session = session;
this.auth = auth;
this.realm = auth.getRealm();
this.user = auth.getUser();
this.client = client;
this.event = event;
this.locale = session.getContext().resolveLocale(user);
}
示例27
public Response execute(String samlRequest, String samlResponse, String relayState, String clientId) {
event = new EventBuilder(realm, session, clientConnection);
Response response = basicChecks(samlRequest, samlResponse);
if (response != null) return response;
if (samlRequest != null) return handleSamlRequest(samlRequest, relayState);
else return handleSamlResponse(samlResponse, relayState, clientId);
}
示例28
@Override
protected BrokeredIdentityContext exchangeExternalImpl(EventBuilder event, MultivaluedMap<String, String> params) {
String subjectToken = params.getFirst(OAuth2Constants.SUBJECT_TOKEN);
if (subjectToken == null) {
event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN + " param unset");
event.error(Errors.INVALID_TOKEN);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "token not set", Response.Status.BAD_REQUEST);
}
String subjectTokenType = params.getFirst(OAuth2Constants.SUBJECT_TOKEN_TYPE);
if (subjectTokenType == null) {
subjectTokenType = OAuth2Constants.ACCESS_TOKEN_TYPE;
}
return validateJwt(event, subjectToken, subjectTokenType);
}
示例29
@Override
protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode profile) {
String id = getJsonProperty(profile, "id");
if (id == null) {
event.detail(Details.REASON, "id claim is null from user info json");
event.error(Errors.INVALID_TOKEN);
throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
}
return gitlabExtractFromProfile(profile);
}
示例30
private Object fetchCrossRealmData(KeycloakSession session) {
RealmModel targetRealm = session.realms().getRealmByName("services-demo");
ClientModel serviceClient = targetRealm.getClientByClientId("simple-service");
if (!serviceClient.isServiceAccountsEnabled()) {
return null;
}
String loopback = "127.0.0.1";
EventBuilder event = new EventBuilder(targetRealm, session, new ClientConnection() {
public String getRemoteAddr() {
return loopback;
}
public String getRemoteHost() {
return loopback;
}
public int getRemotePort() {
return 8080;
}
public String getLocalAddr() {
return loopback;
}
public int getLocalPort() {
return 8080;
}
});
UserModel serviceAccountUser = session.users().getServiceAccount(serviceClient);
if (!serviceAccountUser.isEnabled()) {
return null;
}
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(targetRealm, false);
AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(serviceClient);
authSession.setAuthenticatedUser(serviceAccountUser);
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), targetRealm.getName()));
authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, "openid profile roles");
UserSessionModel serviceAccountUserSession = session.sessions().createUserSession(authSession.getParentSession().getId(), targetRealm, serviceAccountUser, serviceAccountUser.getUsername(),
loopback, ServiceAccountConstants.CLIENT_AUTH, false, null, null);
AuthenticationManager.setClientScopesInSession(authSession);
ClientSessionContext clientSessionContext = TokenManager.attachAuthenticationSession(session, serviceAccountUserSession, authSession);
// Notes about serviceClient details
serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_ID, serviceClient.getClientId());
serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_HOST, loopback);
serviceAccountUserSession.setNote(ServiceAccountConstants.CLIENT_ADDRESS, loopback);
TokenManager tokenManager = new TokenManager();
TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(targetRealm, serviceClient, event, session, serviceAccountUserSession, clientSessionContext)
.generateAccessToken();
AccessTokenResponse accessTokenResponse = responseBuilder.build();
String accessToken = accessTokenResponse.getToken();
LOGGER.infof("AccessToken: %s", accessToken);
return null;
}