Search in sources :

Example 21 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project dhis2-core by dhis2.

the class AuthenticationLoggerListener method onApplicationEvent.

public void onApplicationEvent(AbstractAuthenticationEvent event) {
    if (!log.isWarnEnabled()) {
        return;
    }
    if (SessionFixationProtectionEvent.class.isAssignableFrom(event.getClass()) || InteractiveAuthenticationSuccessEvent.class.isAssignableFrom(event.getClass())) {
        return;
    }
    String eventClassName = String.format("Authentication event: %s; ", ClassUtils.getShortName(event.getClass()));
    String authName = StringUtils.firstNonEmpty(event.getAuthentication().getName(), "");
    String ipAddress = "";
    String sessionId = "";
    String exceptionMessage = "";
    if (event instanceof AbstractAuthenticationFailureEvent) {
        exceptionMessage = "exception: " + ((AbstractAuthenticationFailureEvent) event).getException().getMessage();
    }
    Object details = event.getAuthentication().getDetails();
    if (details != null && ForwardedIpAwareWebAuthenticationDetails.class.isAssignableFrom(details.getClass())) {
        ForwardedIpAwareWebAuthenticationDetails authDetails = (ForwardedIpAwareWebAuthenticationDetails) details;
        ipAddress = String.format("ip: %s; ", authDetails.getIp());
        sessionId = hashSessionId(authDetails.getSessionId());
    } else if (OAuth2LoginAuthenticationToken.class.isAssignableFrom(event.getAuthentication().getClass())) {
        OAuth2LoginAuthenticationToken authenticationToken = (OAuth2LoginAuthenticationToken) event.getAuthentication();
        DhisOidcUser principal = (DhisOidcUser) authenticationToken.getPrincipal();
        if (principal != null) {
            User user = principal.getUser();
            authName = user.getUsername();
        }
        WebAuthenticationDetails oauthDetails = (WebAuthenticationDetails) authenticationToken.getDetails();
        ipAddress = String.format("ip: %s; ", oauthDetails.getRemoteAddress());
        sessionId = hashSessionId(oauthDetails.getSessionId());
    } else if (OAuth2AuthenticationToken.class.isAssignableFrom(event.getSource().getClass())) {
        OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) event.getSource();
        DhisOidcUser principal = (DhisOidcUser) authenticationToken.getPrincipal();
        if (principal != null) {
            User user = principal.getUser();
            authName = user.getUsername();
        }
    }
    String userNamePrefix = Strings.isNullOrEmpty(authName) ? "" : String.format("username: %s; ", authName);
    log.info(TextUtils.removeNonEssentialChars(eventClassName + userNamePrefix + ipAddress + sessionId + exceptionMessage));
}
Also used : InteractiveAuthenticationSuccessEvent(org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent) DhisOidcUser(org.hisp.dhis.security.oidc.DhisOidcUser) DhisOidcUser(org.hisp.dhis.security.oidc.DhisOidcUser) User(org.hisp.dhis.user.User) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) SessionFixationProtectionEvent(org.springframework.security.web.authentication.session.SessionFixationProtectionEvent) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) AbstractAuthenticationFailureEvent(org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent)

Example 22 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project dhis2-core by dhis2.

the class AuthenticationListener method handleAuthenticationSuccess.

@EventListener({ InteractiveAuthenticationSuccessEvent.class, AuthenticationSuccessEvent.class })
public void handleAuthenticationSuccess(AbstractAuthenticationEvent event) {
    Authentication auth = event.getAuthentication();
    String username = event.getAuthentication().getName();
    Object details = auth.getDetails();
    if (TwoFactorWebAuthenticationDetails.class.isAssignableFrom(details.getClass())) {
        TwoFactorWebAuthenticationDetails authDetails = (TwoFactorWebAuthenticationDetails) details;
        log.debug(String.format("Login attempt succeeded for remote IP: %s", authDetails.getIp()));
    }
    if (OAuth2LoginAuthenticationToken.class.isAssignableFrom(auth.getClass())) {
        OAuth2LoginAuthenticationToken authenticationToken = (OAuth2LoginAuthenticationToken) auth;
        DhisOidcUser principal = (DhisOidcUser) authenticationToken.getPrincipal();
        username = principal.getUser().getUsername();
        WebAuthenticationDetails tokenDetails = (WebAuthenticationDetails) authenticationToken.getDetails();
        String remoteAddress = tokenDetails.getRemoteAddress();
        log.debug(String.format("OIDC login attempt succeeded for remote IP: %s", remoteAddress));
    }
    registerSuccessfulLogin(username);
}
Also used : TwoFactorWebAuthenticationDetails(org.hisp.dhis.security.spring2fa.TwoFactorWebAuthenticationDetails) DhisOidcUser(org.hisp.dhis.security.oidc.DhisOidcUser) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) TwoFactorWebAuthenticationDetails(org.hisp.dhis.security.spring2fa.TwoFactorWebAuthenticationDetails) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) EventListener(org.springframework.context.event.EventListener)

Example 23 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project midpoint by Evolveum.

the class OidcClientModuleAuthenticationImpl method clone.

@Override
public ModuleAuthenticationImpl clone() {
    OidcClientModuleAuthenticationImpl module = new OidcClientModuleAuthenticationImpl();
    module.setClientsRepository(this.getClientsRepository());
    module.setProviders(this.getProviders());
    Authentication actualAuth = SecurityContextHolder.getContext().getAuthentication();
    Authentication newAuthentication = this.getAuthentication();
    if (actualAuth instanceof MidpointAuthentication && ((MidpointAuthentication) actualAuth).getAuthentications() != null && !((MidpointAuthentication) actualAuth).getAuthentications().isEmpty()) {
        ModuleAuthentication actualModule = ((MidpointAuthentication) actualAuth).getAuthentications().get(0);
        if (actualModule instanceof OidcClientModuleAuthenticationImpl && actualModule.getAuthentication() instanceof OAuth2LoginAuthenticationToken) {
            newAuthentication = actualModule.getAuthentication();
        }
    }
    module.setAuthentication(newAuthentication);
    super.clone(module);
    return module;
}
Also used : RemoteModuleAuthentication(com.evolveum.midpoint.authentication.api.config.RemoteModuleAuthentication) ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) RemoteModuleAuthentication(com.evolveum.midpoint.authentication.api.config.RemoteModuleAuthentication) ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) Authentication(org.springframework.security.core.Authentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 24 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project midpoint by Evolveum.

the class OidcLoginAuthenticationFilter method attemptAuthentication.

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    MultiValueMap<String, String> params = toMultiMap(request.getParameterMap());
    if (!isAuthorizationResponse(params)) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_REQUEST_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
    } else {
        OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
        if (authorizationRequest == null) {
            OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
        } else {
            String registrationId = authorizationRequest.getAttribute("registration_id");
            ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
            if (clientRegistration == null) {
                OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
                throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
            } else {
                String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null).build().toUriString();
                OAuth2AuthorizationResponse authorizationResponse = convert(params, redirectUri);
                OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
                MidpointAuthentication authenticationResult = (MidpointAuthentication) this.getAuthenticationManager().authenticate(authenticationRequest);
                Assert.notNull(authenticationResult, "authentication result cannot be null");
                return authenticationResult;
            }
        }
    }
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 25 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project midpoint by Evolveum.

the class OidcClientLogoutSuccessHandler method determineTargetUrl.

protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String targetUrl = null;
    if (authentication instanceof MidpointAuthentication) {
        MidpointAuthentication mPAuthentication = (MidpointAuthentication) authentication;
        ModuleAuthentication moduleAuthentication = mPAuthentication.getProcessingModuleAuthentication();
        if (moduleAuthentication instanceof OidcClientModuleAuthenticationImpl) {
            Authentication internalAuthentication = moduleAuthentication.getAuthentication();
            if (internalAuthentication instanceof PreAuthenticatedAuthenticationToken || internalAuthentication instanceof AnonymousAuthenticationToken) {
                Object details = internalAuthentication.getDetails();
                if (details instanceof OAuth2LoginAuthenticationToken && ((OAuth2LoginAuthenticationToken) details).getDetails() instanceof OidcUser) {
                    OAuth2LoginAuthenticationToken oidcAuthentication = (OAuth2LoginAuthenticationToken) details;
                    String registrationId = oidcAuthentication.getClientRegistration().getRegistrationId();
                    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
                    URI endSessionEndpoint = this.endSessionEndpoint(clientRegistration);
                    if (endSessionEndpoint != null) {
                        String idToken = this.idToken(oidcAuthentication);
                        String postLogoutRedirectUri = this.postLogoutRedirectUri(request);
                        targetUrl = this.endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri);
                    }
                }
            }
        }
    }
    return targetUrl != null ? targetUrl : super.determineTargetUrl(request, response);
}
Also used : ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) OidcClientModuleAuthenticationImpl(com.evolveum.midpoint.authentication.impl.module.authentication.OidcClientModuleAuthenticationImpl) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) URI(java.net.URI) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser)

Aggregations

OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)29 Test (org.junit.jupiter.api.Test)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)21 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)20 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)15 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)15 Authentication (org.springframework.security.core.Authentication)13 HashMap (java.util.HashMap)12 Map (java.util.Map)12 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)11 BDDMockito.given (org.mockito.BDDMockito.given)11 Mockito.mock (org.mockito.Mockito.mock)11 Answer (org.mockito.stubbing.Answer)11 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)11 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)11