Search in sources :

Example 81 with UsernamePasswordCredential

use of org.apereo.cas.authentication.credential.UsernamePasswordCredential in project cas by apereo.

the class CasReleaseAttributesReportEndpoint method releasePrincipalAttributes.

/**
 * Release principal attributes map.
 *
 * @param username the username
 * @param password the password
 * @param service  the service
 * @return the map
 */
@ReadOperation
@Operation(summary = "Get collection of released attributes for the user and application", parameters = { @Parameter(name = "username", required = true), @Parameter(name = "password", required = true), @Parameter(name = "service", required = true) })
public Map<String, Object> releasePrincipalAttributes(final String username, final String password, final String service) {
    val selectedService = this.serviceFactory.createService(service);
    val registeredService = this.servicesManager.findServiceBy(selectedService);
    val credential = new UsernamePasswordCredential(username, password);
    val result = this.authenticationSystemSupport.finalizeAuthenticationTransaction(selectedService, credential);
    val authentication = result.getAuthentication();
    val principal = authentication.getPrincipal();
    val context = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(selectedService).principal(principal).build();
    val attributesToRelease = registeredService.getAttributeReleasePolicy().getAttributes(context);
    val builder = DefaultAuthenticationBuilder.of(principal, this.principalFactory, attributesToRelease, selectedService, registeredService, authentication);
    val finalAuthentication = builder.build();
    val assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(CollectionUtils.wrap(finalAuthentication)).build();
    val resValidation = new LinkedHashMap<String, Object>();
    resValidation.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
    resValidation.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, selectedService);
    resValidation.put("registeredService", registeredService);
    return resValidation;
}
Also used : lombok.val(lombok.val) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) LinkedHashMap(java.util.LinkedHashMap) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) ReadOperation(org.springframework.boot.actuate.endpoint.annotation.ReadOperation) WriteOperation(org.springframework.boot.actuate.endpoint.annotation.WriteOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 82 with UsernamePasswordCredential

use of org.apereo.cas.authentication.credential.UsernamePasswordCredential in project cas by apereo.

the class RegisteredServiceResource method authenticateRequest.

private Authentication authenticateRequest(final HttpServletRequest request, final HttpServletResponse response) {
    val extractor = new BasicAuthExtractor();
    val webContext = new JEEContext(request, response);
    val credentialsResult = extractor.extract(webContext, JEESessionStore.INSTANCE);
    val credentials = (UsernamePasswordCredentials) credentialsResult.get();
    LOGGER.debug("Received basic authentication request from credentials [{}]", credentials);
    val c = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
    val serviceRequest = this.serviceFactory.createService(request);
    val result = authenticationSystemSupport.finalizeAuthenticationTransaction(serviceRequest, c);
    if (result == null) {
        throw new BadRestRequestException("Unable to establish authentication using provided credentials for " + c.getUsername());
    }
    return result.getAuthentication();
}
Also used : lombok.val(lombok.val) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) JEEContext(org.pac4j.core.context.JEEContext) BadRestRequestException(org.apereo.cas.rest.BadRestRequestException) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 83 with UsernamePasswordCredential

use of org.apereo.cas.authentication.credential.UsernamePasswordCredential in project cas by apereo.

the class TicketGrantingTicketResourceTests method initialize.

@BeforeEach
public void initialize() {
    val httpRequestCredentialFactory = new UsernamePasswordRestHttpRequestCredentialFactory() {

        @Override
        public List<Credential> fromAuthentication(final HttpServletRequest request, final MultiValueMap<String, String> requestBody, final Authentication authentication, final MultifactorAuthenticationProvider provider) {
            if (provider.getId().contains("unknown")) {
                return List.of();
            }
            return List.of(new UsernamePasswordCredential("mfa-user", "mfa-user"));
        }
    };
    val publisher = mock(ApplicationEventPublisher.class);
    val manager = mock(AuthenticationManager.class);
    lenient().when(manager.authenticate(any(AuthenticationTransaction.class))).thenReturn(CoreAuthenticationTestUtils.getAuthentication());
    lenient().when(ticketSupport.getAuthenticationFrom(anyString())).thenReturn(CoreAuthenticationTestUtils.getAuthentication());
    lenient().when(requestedContextValidator.validateAuthenticationContext(any(), any(), any(), any(), any())).thenReturn(AuthenticationContextValidationResult.builder().success(true).build());
    lenient().when(multifactorTriggerSelectionStrategy.resolve(any(), any(), any(), any(), any())).thenReturn(Optional.empty());
    val authenticationSystemSupport = new DefaultAuthenticationSystemSupport(new DefaultAuthenticationTransactionManager(publisher, manager), new DefaultPrincipalElectionStrategy(), new DefaultAuthenticationResultBuilderFactory(), new DefaultAuthenticationTransactionFactory());
    val api = new DefaultRestAuthenticationService(authenticationSystemSupport, httpRequestCredentialFactory, new WebApplicationServiceFactory(), multifactorTriggerSelectionStrategy, servicesManager, requestedContextValidator);
    val logoutManager = new DefaultLogoutManager(false, new DefaultLogoutExecutionPlan());
    val applicationContext = new StaticApplicationContext();
    applicationContext.refresh();
    this.ticketGrantingTicketResourceUnderTest = new TicketGrantingTicketResource(api, casMock, new DefaultTicketGrantingTicketResourceEntityResponseFactory(), new GenericWebApplicationContext(), new DefaultSingleLogoutRequestExecutor(casMock, logoutManager, applicationContext));
    this.mockMvc = MockMvcBuilders.standaloneSetup(this.ticketGrantingTicketResourceUnderTest).defaultRequest(get("/").contextPath("/cas").contentType(MediaType.APPLICATION_FORM_URLENCODED)).build();
}
Also used : lombok.val(lombok.val) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) Credential(org.apereo.cas.authentication.Credential) DefaultLogoutExecutionPlan(org.apereo.cas.logout.DefaultLogoutExecutionPlan) TicketGrantingTicketResource(org.apereo.cas.support.rest.resources.TicketGrantingTicketResource) DefaultLogoutManager(org.apereo.cas.logout.DefaultLogoutManager) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) UsernamePasswordRestHttpRequestCredentialFactory(org.apereo.cas.rest.factory.UsernamePasswordRestHttpRequestCredentialFactory) MultifactorAuthenticationProvider(org.apereo.cas.authentication.MultifactorAuthenticationProvider) TestMultifactorAuthenticationProvider(org.apereo.cas.authentication.mfa.TestMultifactorAuthenticationProvider) DefaultAuthenticationTransactionFactory(org.apereo.cas.authentication.DefaultAuthenticationTransactionFactory) DefaultAuthenticationTransactionManager(org.apereo.cas.authentication.DefaultAuthenticationTransactionManager) DefaultRestAuthenticationService(org.apereo.cas.rest.authentication.DefaultRestAuthenticationService) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultPrincipalElectionStrategy(org.apereo.cas.authentication.principal.DefaultPrincipalElectionStrategy) DefaultAuthenticationResultBuilderFactory(org.apereo.cas.authentication.DefaultAuthenticationResultBuilderFactory) Authentication(org.apereo.cas.authentication.Authentication) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) DefaultTicketGrantingTicketResourceEntityResponseFactory(org.apereo.cas.rest.factory.DefaultTicketGrantingTicketResourceEntityResponseFactory) DefaultAuthenticationSystemSupport(org.apereo.cas.authentication.DefaultAuthenticationSystemSupport) DefaultSingleLogoutRequestExecutor(org.apereo.cas.logout.slo.DefaultSingleLogoutRequestExecutor) AuthenticationTransaction(org.apereo.cas.authentication.AuthenticationTransaction) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) MultiValueMap(org.springframework.util.MultiValueMap) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 84 with UsernamePasswordCredential

use of org.apereo.cas.authentication.credential.UsernamePasswordCredential in project cas by apereo.

the class UserAuthenticationResourceTests method initialize.

@BeforeEach
public void initialize() {
    val httpRequestCredentialFactory = new UsernamePasswordRestHttpRequestCredentialFactory() {

        @Override
        public List<Credential> fromAuthentication(final HttpServletRequest request, final MultiValueMap<String, String> requestBody, final Authentication authentication, final MultifactorAuthenticationProvider provider) {
            if (provider.getId().contains("unknown")) {
                return List.of();
            }
            return List.of(new UsernamePasswordCredential("mfa-user", "mfa-user"));
        }
    };
    val api = new DefaultRestAuthenticationService(authenticationSupport, httpRequestCredentialFactory, new WebApplicationServiceFactory(), multifactorTriggerSelectionStrategy, servicesManager, requestedContextValidator);
    this.userAuthenticationResource = new UserAuthenticationResource(api, new DefaultUserAuthenticationResourceEntityResponseFactory(), new GenericApplicationContext());
    this.mockMvc = MockMvcBuilders.standaloneSetup(this.userAuthenticationResource).defaultRequest(get("/").contextPath("/cas").contentType(MediaType.APPLICATION_FORM_URLENCODED)).build();
}
Also used : lombok.val(lombok.val) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) Credential(org.apereo.cas.authentication.Credential) UserAuthenticationResource(org.apereo.cas.support.rest.resources.UserAuthenticationResource) UsernamePasswordRestHttpRequestCredentialFactory(org.apereo.cas.rest.factory.UsernamePasswordRestHttpRequestCredentialFactory) MultifactorAuthenticationProvider(org.apereo.cas.authentication.MultifactorAuthenticationProvider) TestMultifactorAuthenticationProvider(org.apereo.cas.authentication.mfa.TestMultifactorAuthenticationProvider) DefaultRestAuthenticationService(org.apereo.cas.rest.authentication.DefaultRestAuthenticationService) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultUserAuthenticationResourceEntityResponseFactory(org.apereo.cas.rest.factory.DefaultUserAuthenticationResourceEntityResponseFactory) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) Authentication(org.apereo.cas.authentication.Authentication) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) MultiValueMap(org.springframework.util.MultiValueMap) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 85 with UsernamePasswordCredential

use of org.apereo.cas.authentication.credential.UsernamePasswordCredential in project cas by apereo.

the class SurrogateSelectionAction method doExecute.

@Audit(action = AuditableActions.SURROGATE_AUTHENTICATION_ELIGIBILITY_SELECTION, actionResolverName = AuditActionResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_SELECTION_ACTION_RESOLVER, resourceResolverName = AuditResourceResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_SELECTION_RESOURCE_RESOLVER)
@Override
protected Event doExecute(final RequestContext requestContext) {
    val resultMap = new HashMap<String, Object>();
    try {
        val credential = WebUtils.getCredential(requestContext);
        if (credential instanceof UsernamePasswordCredential) {
            val target = requestContext.getExternalContext().getRequestParameterMap().get(PARAMETER_NAME_SURROGATE_TARGET);
            LOGGER.debug("Located surrogate target as [{}]", target);
            if (StringUtils.isNotBlank(target)) {
                val currentAuth = WebUtils.getAuthentication(requestContext);
                AuthenticationCredentialsThreadLocalBinder.bindCurrent(currentAuth);
                resultMap.put(PARAMETER_NAME_SURROGATE_TARGET, target);
                val registeredService = WebUtils.getRegisteredService(requestContext);
                val builder = WebUtils.getAuthenticationResultBuilder(requestContext);
                val result = surrogatePrincipalBuilder.buildSurrogateAuthenticationResult(builder, credential, target, registeredService);
                result.ifPresent(bldr -> WebUtils.putAuthenticationResultBuilder(bldr, requestContext));
            } else {
                LOGGER.warn("No surrogate identifier was selected or provided");
            }
            resultMap.put("primary", credential.getId());
        } else {
            LOGGER.debug("Current credential in the webflow is not one of [{}]", UsernamePasswordCredential.class.getName());
        }
        return success(resultMap);
    } catch (final Exception e) {
        WebUtils.addErrorMessageToContext(requestContext, "screen.surrogates.account.selection.error", "Unable to accept or authorize selection");
        LoggingUtils.error(LOGGER, e);
        return error(e);
    }
}
Also used : lombok.val(lombok.val) HashMap(java.util.HashMap) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) Audit(org.apereo.inspektr.audit.annotation.Audit)

Aggregations

lombok.val (lombok.val)111 UsernamePasswordCredential (org.apereo.cas.authentication.credential.UsernamePasswordCredential)111 Test (org.junit.jupiter.api.Test)74 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)30 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)14 SimpleTestUsernamePasswordAuthenticationHandler (org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler)12 HashMap (java.util.HashMap)8 Map (java.util.Map)8 BasicCredentialMetaData (org.apereo.cas.authentication.metadata.BasicCredentialMetaData)8 LinkedHashMap (java.util.LinkedHashMap)7 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)7 Executable (org.junit.jupiter.api.function.Executable)7 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 ServletExternalContext (org.springframework.webflow.context.servlet.ServletExternalContext)6 MockRequestContext (org.springframework.webflow.test.MockRequestContext)6 ArrayList (java.util.ArrayList)5 ClassPathResource (org.springframework.core.io.ClassPathResource)5 MockServletContext (org.springframework.mock.web.MockServletContext)5 FailedLoginException (javax.security.auth.login.FailedLoginException)4 SurrogateUsernamePasswordCredential (org.apereo.cas.authentication.SurrogateUsernamePasswordCredential)4