Search in sources :

Example 1 with CommonProfile

use of org.pac4j.core.profile.CommonProfile in project cas by apereo.

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        final String username = authentication.getPrincipal().toString();
        final Object credentials = authentication.getCredentials();
        final String password = credentials == null ? null : credentials.toString();
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        final AuthenticationRequest request = new AuthenticationRequest(username, new org.ldaptive.Credential(password), ReturnAttributes.ALL.value());
        final Authenticator authenticator = Beans.newLdaptiveAuthenticator(adminPagesSecurityProperties.getLdap());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        final AuthenticationResponse response = authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.getResult()) {
            final LdapEntry entry = response.getLdapEntry();
            final CommonProfile profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            this.authorizationGenerator.generate(WebUtils.getPac4jJ2EContext(), profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            final Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.addAll(profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            final RequireAnyRoleAuthorizer authorizer = new RequireAnyRoleAuthorizer(adminPagesSecurityProperties.getAdminRoles());
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            final J2EContext context = WebUtils.getPac4jJ2EContext();
            if (authorizer.isAllAuthorized(context, Arrays.asList(profile))) {
                return new UsernamePasswordAuthenticationToken(username, password, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) LdapEntry(org.ldaptive.LdapEntry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) J2EContext(org.pac4j.core.context.J2EContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) CommonProfile(org.pac4j.core.profile.CommonProfile) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) Authenticator(org.ldaptive.auth.Authenticator) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)

Example 2 with CommonProfile

use of org.pac4j.core.profile.CommonProfile in project cas by apereo.

the class DelegatedClientAuthenticationAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();
    // web context
    final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    LOGGER.debug("clientName: [{}]", clientName);
    if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
        return stopWebflow();
    }
    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        LOGGER.debug("Client: [{}]", client);
        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            LOGGER.debug("Retrieved credentials: [{}]", credentials);
        } catch (final Exception e) {
            LOGGER.debug("The request requires http action", e);
            return stopWebflow();
        }
        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
        context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
        LOGGER.debug("Retrieve service: [{}]", service);
        if (service != null) {
            request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, this.themeParamName);
        restoreRequestAttribute(request, session, this.localParamName);
        restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);
        // credentials not null -> try to authenticate
        if (credentials != null) {
            final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));
            final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }
    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
        return stopWebflow();
    }
    if (this.autoRedirect) {
        final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
        if (urls != null && urls.size() == 1) {
            final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
            LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
            response.sendRedirect(cfg.getRedirectUrl());
            final ExternalContext externalContext = context.getExternalContext();
            externalContext.recordResponseComplete();
            return stopWebflow();
        }
    }
    return error();
}
Also used : WebContext(org.pac4j.core.context.WebContext) HttpSession(javax.servlet.http.HttpSession) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Service(org.apereo.cas.authentication.principal.Service) BaseClient(org.pac4j.core.client.BaseClient) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) CommonProfile(org.pac4j.core.profile.CommonProfile) ExternalContext(org.springframework.webflow.context.ExternalContext) Credentials(org.pac4j.core.credentials.Credentials)

Aggregations

CommonProfile (org.pac4j.core.profile.CommonProfile)2 ArrayList (java.util.ArrayList)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)1 ClientCredential (org.apereo.cas.authentication.principal.ClientCredential)1 Service (org.apereo.cas.authentication.principal.Service)1 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)1 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)1 LdapEntry (org.ldaptive.LdapEntry)1 AuthenticationRequest (org.ldaptive.auth.AuthenticationRequest)1 AuthenticationResponse (org.ldaptive.auth.AuthenticationResponse)1 Authenticator (org.ldaptive.auth.Authenticator)1 RequireAnyRoleAuthorizer (org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)1 BaseClient (org.pac4j.core.client.BaseClient)1 J2EContext (org.pac4j.core.context.J2EContext)1 WebContext (org.pac4j.core.context.WebContext)1 Credentials (org.pac4j.core.credentials.Credentials)1