org.jasig.cas.authentication.principal.WebApplicationService Java Examples

The following examples show how to use org.jasig.cas.authentication.principal.WebApplicationService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceValidateController.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Generate the success view. The result will contain the assertion and the proxy iou.
 *
 * @param assertion the assertion
 * @param proxyIou the proxy iou
 * @param service the validated service
 * @param proxyGrantingTicket the proxy granting ticket
 * @return the model and view, pointed to the view name set by
 */
private ModelAndView generateSuccessView(final Assertion assertion, final String proxyIou,
                                         final WebApplicationService service,
                                         final TicketGrantingTicket proxyGrantingTicket) {

    final ModelAndView success = new ModelAndView(this.successView);
    success.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
    success.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, service);
    success.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU, proxyIou);
    if (proxyGrantingTicket != null) {
        success.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET, proxyGrantingTicket.getId());
    }
    final Map<String, ?> augmentedModelObjects = augmentSuccessViewModelObjects(assertion);
    if (augmentedModelObjects != null) {
        success.addAllObjects(augmentedModelObjects);
    }
    return success;
}
 
Example #2
Source File: AbstractMultiFactorAuthenticationArgumentExtractor.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
/**
 * Extract a target service. Delegates to wrapped argument extractors.
 *
 * @param request http request
 *
 * @return target service that would potentially be wrapped with an MFA supporting service
 */
private WebApplicationService getTargetService(final HttpServletRequest request) {
    WebApplicationService targetService = null;
    for (final ArgumentExtractor extractor : this.supportedArgumentExtractors) {
        targetService = extractor.extractService(request);
        if (targetService != null) {
            logger.debug("[{}] intercepted the request successfully for multifactor authentication",
                    extractor);
            break;
        }
    }

    if (targetService == null) {
        logger.debug("Request is unable to identify the target application");
        return null;
    }
    return targetService;
}
 
Example #3
Source File: AbstractMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
/**
 * Add the request to mfa transaction, re-rank and return the newly ranked one.
 *
 * @param mfaRequests the mfaRequest
 * @param context the context
 *
 * @return newly ranked mfa request in the current mfa transaction
 */
protected MultiFactorAuthenticationSupportingWebApplicationService
            addToMfaTransactionAndGetHighestRankedMfaRequest(final List<MultiFactorAuthenticationRequestContext> mfaRequests,
                                                 final RequestContext context) {

    MultiFactorAuthenticationTransactionContext mfaTx = MultiFactorRequestContextUtils.getMfaTransaction(context);
    if (mfaTx == null && !mfaRequests.isEmpty()) {
        final WebApplicationService svc = mfaRequests.get(0).getMfaService();
        mfaTx = new MultiFactorAuthenticationTransactionContext(svc.getId());
    }
    for (final MultiFactorAuthenticationRequestContext mfaRequest : mfaRequests) {
        mfaTx.addMfaRequest(mfaRequest);
    }

    MultiFactorRequestContextUtils.setMfaTransaction(context, mfaTx);
    return getHighestRankedMfaRequestFromMfaTransaction(context);
}
 
Example #4
Source File: DefaultAuthenticationMethodVerifier.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verifyAuthenticationMethod(final String authenticationMethod,
                                       final WebApplicationService targetService,
                                       final HttpServletRequest request) {

    if (!supportedAuthenticationMethodsConfig.containsAuthenticationMethod(authenticationMethod)) {
        logger.debug("CAS is not configured to support [{}] authentication method value [{}]."
                     + "The configuration of supported authentication methods is likely missing this method.",
                MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD,
                authenticationMethod);
        /**
         * Argument extractors are still going to be invoked, if the flow
         * decides to move the user experience to an error-view JSP. As such,
         * and since we are unable to touch request parameters removing the invalid
         * authn_method before that navigation takes place, there's a chance that an infinite
         * redirect loop might occur. The compromise here to is to "remember" that the exception
         * was handled once via a request attribute.
         */
        if (request.getAttribute(UnrecognizedAuthenticationMethodException.class.getName()) == null) {
            request.setAttribute(UnrecognizedAuthenticationMethodException.class.getName(), Boolean.TRUE.toString());
            throw new UnrecognizedAuthenticationMethodException(authenticationMethod, targetService.getId());
        }
        return false;
    }
    return true;
}
 
Example #5
Source File: AbstractSaml10ResponseView.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(
        final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.encoding);

    final WebApplicationService service = this.samlArgumentExtractor.extractService(request);
    final String serviceId = service != null ? service.getId() : "UNKNOWN";

    try {
        final Response samlResponse = this.samlObjectBuilder.newResponse(
                this.samlObjectBuilder.generateSecureRandomId(),
                DateTime.now().minusSeconds(this.skewAllowance), serviceId, service);

        prepareResponse(samlResponse, model);

        this.samlObjectBuilder.encodeSamlResponse(response, request, samlResponse);
    } catch (final Exception e) {
        logger.error("Error generating SAML response for service {}.", serviceId);
        throw e;
    }
}
 
Example #6
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySsoSessionCookieOnServiceSsoDisallowed() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();

    final WebApplicationService svc = mock(WebApplicationService.class);
    when(svc.getId()).thenReturn("TestSsoFalse");

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");
    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    this.context.getFlowScope().put("service", svc);
    this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(0, response.getCookies().length);
}
 
Example #7
Source File: PrincipalAttributeMultiFactorAuthenticationRequestResolver.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
/**
 * Gets mfa request context.
 *
 * @param method         the mfa method
 * @param authentication the authentication
 * @param targetService  the target service
 * @param responseType   the response type
 * @return the mfa request context
 */
private MultiFactorAuthenticationRequestContext getMfaRequestContext(final String method,
                                                                     final Authentication authentication,
                                                                     final WebApplicationService targetService,
                                                                     final ResponseType responseType) {

    final String mfaMethod = this.authenticationMethodTranslator.translate(targetService, method);
    if (StringUtils.isNotBlank(mfaMethod)) {
        logger.debug("Found mfa attribute [{}] with value [{}] for principal [{}]", this.authenticationMethodAttributeName,
                mfaMethod, authentication.getPrincipal().getId());

        if (!this.authenticationMethodConfiguration.containsAuthenticationMethod(mfaMethod)) {
            logger.info("MFA attribute [{}] with value [{}] is not supported by the authentication method configuration.",
                    this.authenticationMethodAttributeName,
                    mfaMethod);
            return null;
        }
        final int mfaMethodRank = this.authenticationMethodConfiguration.getAuthenticationMethod(mfaMethod).getRank();
        final MultiFactorAuthenticationSupportingWebApplicationService svc =
                this.mfaServiceFactory.create(targetService.getId(), targetService.getId(),
                        targetService.getArtifactId(), responseType, mfaMethod, AuthenticationMethodSource.PRINCIPAL_ATTRIBUTE);

        return new MultiFactorAuthenticationRequestContext(svc, mfaMethodRank);
    }
    return null;
}
 
Example #8
Source File: DefaultRegisteredServiceMfaRoleProcessorImplTest.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveWithoutIncompleteServiceMfaAttributes() throws Exception {
    final WebApplicationService was = getTargetService();
    final Authentication auth = getAuthentication(true);

    final RegisteredService rswa = TestUtils.getRegisteredService("test1");

    DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty();
    prop.setValues(Collections.singleton(CAS_AUTHN_METHOD));
    rswa.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop);

    prop = new DefaultRegisteredServiceProperty();
    prop.setValues(Collections.singleton(MEMBER_OF_VALUE));
    rswa.getProperties().put(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_PATTERN, prop);

    final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl(
            getMFWASF(was), getAMCP(), getServicesManager(rswa));

    final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was);
    assertNotNull(result);
    assertEquals(0, result.size());
}
 
Example #9
Source File: DefaultRegisteredServiceMfaRoleProcessorImplTest.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveServiceWithOnlyAuthnMethodAttribute() throws Exception {
    final WebApplicationService was = getTargetService();
    final Authentication auth = getAuthentication(true);

    final RegisteredService rswa = TestUtils.getRegisteredService("test1");

    final DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty();
    prop.setValues(Collections.singleton(CAS_AUTHN_METHOD));
    rswa.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop);

    final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl(
            getMFWASF(was), getAMCP(), getServicesManager(rswa));

    final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was);
    assertNotNull(result);
    assertEquals(0, result.size());
}
 
Example #10
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Create a new SAML response object.
 * @param id the id
 * @param issueInstant the issue instant
 * @param recipient the recipient
 * @param service the service
 * @return the response
 */
public Response newResponse(final String id, final DateTime issueInstant,
                            final String recipient, final WebApplicationService service) {

    final Response samlResponse = newSamlObject(Response.class);
    samlResponse.setID(id);
    samlResponse.setIssueInstant(issueInstant);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    if (service instanceof SamlService) {
        final SamlService samlService = (SamlService) service;

        final String requestId = samlService.getRequestID();
        if (StringUtils.isNotBlank(requestId)) {
            samlResponse.setInResponseTo(requestId);
        }
    }
    return samlResponse;
}
 
Example #11
Source File: Saml10ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Create a new SAML response object.
 * @param id the id
 * @param issueInstant the issue instant
 * @param recipient the recipient
 * @param service the service
 * @return the response
 */
public Response newResponse(final String id, final DateTime issueInstant,
                                     final String recipient, final WebApplicationService service) {

    final Response samlResponse = newSamlObject(Response.class);
    samlResponse.setID(id);
    samlResponse.setIssueInstant(issueInstant);
    samlResponse.setVersion(SAMLVersion.VERSION_11);
    samlResponse.setInResponseTo(recipient);
    if (service instanceof SamlService) {
        final SamlService samlService = (SamlService) service;

        final String requestId = samlService.getRequestID();
        if (StringUtils.isNotBlank(requestId)) {
            samlResponse.setInResponseTo(requestId);
        }
    }
    return samlResponse;
}
 
Example #12
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // save parameters in web session
    final WebApplicationService service = WebUtils.getService(context);
    logger.debug("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.debug("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #13
Source File: RegisteredServiceThemeBasedViewResolverTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetServiceWithDefault() throws Exception {
    final MockRequestContext requestContext = new MockRequestContext();
    RequestContextHolder.setRequestContext(requestContext);

    final WebApplicationService webApplicationService = new SimpleWebApplicationServiceImpl("myDefaultId");
    requestContext.getFlowScope().put("service", webApplicationService);

    assertEquals("/WEB-INF/view/jsp/defaultTheme/ui/casLoginView",
            this.registeredServiceThemeBasedViewResolver.buildView("casLoginView").getUrl());
}
 
Example #14
Source File: DefaultRegisteredServiceMfaRoleProcessorImplTest.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
private static WebApplicationService getTargetService() {
    final WebApplicationService was = Mockito.mock(WebApplicationService.class);
    when(was.getId()).thenReturn(CAS_SERVICE);
    when(was.getArtifactId()).thenReturn("test");

    return was;
}
 
Example #15
Source File: AbstractMultiFactorAuthenticationArgumentExtractor.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public final WebApplicationService extractService(final HttpServletRequest request) {
    final WebApplicationService targetService = getTargetService(request);
    if (targetService == null) {
        return null;
    }
    String authenticationMethod = this.getAuthenticationMethod(request, targetService);
    if (StringUtils.isBlank(authenticationMethod)) {
        return null;
    }
    authenticationMethod = this.authenticationMethodTranslator.translate(targetService, authenticationMethod);
    this.authenticationMethodVerifier.verifyAuthenticationMethod(authenticationMethod, targetService, request);

    // Grab the HTTP method for the response off of the request.
    final String method = request.getParameter(CONST_PARAM_METHOD);

    final MultiFactorAuthenticationSupportingWebApplicationService mfaService =
            this.mfaWebApplicationServiceFactory.create(targetService.getId(), targetService.getId(), targetService.getArtifactId(),
                    "POST".equalsIgnoreCase(method) ? ResponseType.POST : ResponseType.REDIRECT,
                    authenticationMethod, getAuthenticationMethodSource());

    logger.debug("Created multifactor authentication service instance for [{}] with [{}] as [{}] "
            + "and authentication method definition source [{}].",
            mfaService.getId(), CONST_PARAM_AUTHN_METHOD,
            mfaService.getAuthenticationMethod(),
            mfaService.getAuthenticationMethodSource());

    return mfaService;
}
 
Example #16
Source File: DefaultRegisteredServiceMfaRoleProcessorImplTest.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
private static MultiFactorWebApplicationServiceFactory getMFWASF(final WebApplicationService was) {
    final MultiFactorWebApplicationServiceFactory factory = mock(MultiFactorWebApplicationServiceFactory.class);
    when(factory.create(anyString(), anyString(), anyString(), any(Response.ResponseType.class), anyString(),
            any(MultiFactorAuthenticationSupportingWebApplicationService.AuthenticationMethodSource.class)))
            .thenReturn(getMfaService());
    return factory;
}
 
Example #17
Source File: MultiFactorAuthenticationRequestsCollectingArgumentExtractor.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public WebApplicationService extractService(final HttpServletRequest request) {
    MultiFactorAuthenticationTransactionContext mfaTxCtx = null;

    for (final AbstractMultiFactorAuthenticationArgumentExtractor extractor : this.mfaArgumentExstractors) {
        final MultiFactorAuthenticationSupportingWebApplicationService service =
                MultiFactorAuthenticationSupportingWebApplicationService.class.cast(extractor.extractService(request));

        if (service != null
            && this.authenticationMethodVerifier.verifyAuthenticationMethod(service.getAuthenticationMethod(), service, request)) {

            final AuthenticationMethod method =
                    this.authenticationMethodConfiguration.getAuthenticationMethod(service.getAuthenticationMethod());
            if (mfaTxCtx != null) {
                mfaTxCtx.addMfaRequest(createMfaRequest(service, method.getRank()));
            } else {
                mfaTxCtx = new MultiFactorAuthenticationTransactionContext(
                        service.getId()).addMfaRequest(createMfaRequest(service, method.getRank()));
            }

        }
    }

    if (mfaTxCtx != null) {
        //This is not unit testable (well in Java anyway, but would be possible if this class was written in Groovy),
        // but it's the only way to reach into the SWF context from here,
        //and since there is no desire to use <code>HttpServletRequest</code> attribute to get this object out.
        RequestContextHolder.getRequestContext().getConversationScope()
                .put(MultiFactorAuthenticationTransactionContext.class.getSimpleName(), mfaTxCtx);
    }
    //Always return null as we have collected all the mfa requests
    return null;
}
 
Example #18
Source File: RequestParameterMultiFactorAuthenticationArgumentExtractor.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthenticationMethod(final HttpServletRequest request, final WebApplicationService targetService) {
    logger.debug("Attempting to extract multifactor authentication parameters from the request");

    final String authenticationMethod =
            request.getParameter(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD);

    if (!StringUtils.hasText(authenticationMethod)) {
        logger.debug("Request has no request parameter [{}]. Delegating to the next argument extractor in the chain...",
                MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD);
        return null;
    }
    return authenticationMethod;
}
 
Example #19
Source File: WebUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public static WebApplicationService getService(
    final List<ArgumentExtractor> argumentExtractors,
    final HttpServletRequest request) {
    for (final ArgumentExtractor argumentExtractor : argumentExtractors) {
        final WebApplicationService service = argumentExtractor
            .extractService(request);

        if (service != null) {
            return service;
        }
    }

    return null;
}
 
Example #20
Source File: RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthenticationMethod(final HttpServletRequest request, final WebApplicationService targetService) {
    logger.debug("Attempting to extract multifactor authentication method from registered service attribute...");

    if (this.mfaRoleProcessor != null) {
        final String mfaRolesResult = checkMfaRoles(targetService);
        if (!StringUtils.isEmpty(mfaRolesResult)) {
            return mfaRolesResult;
        }
    }

    final RegisteredService registeredService = this.servicesManager.findServiceBy(targetService);
    if (registeredService == null) {
        logger.debug("No registered service is found. Delegating to the next argument extractor in the chain...");
        return null;
    }

    logger.debug("Located registered service [{}] with properties [{}]", registeredService, registeredService.getProperties());

    if (registeredService.getProperties().containsKey(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_NAME)
            || registeredService.getProperties().containsKey(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_PATTERN)) {
        logger.debug("Deferring mfa authn method for Principal Attribute Resolver");
        return null;
    }

    if (!registeredService.getProperties().containsKey(this.authenticationMethodAttribute)) {
        logger.debug("Registered service [{}] does not define authentication method attribute [{}]. ", registeredService,
                this.authenticationMethodAttribute);
        return determineDefaultAuthenticationMethod();
    }

    final String authenticationMethod = registeredService.getProperties().get(this.authenticationMethodAttribute).getValue();
    logger.debug("Found authentication method [{}] in properties of registered service [{}]", authenticationMethod, registeredService);
    return authenticationMethod;
}
 
Example #21
Source File: AbstractArgumentExtractor.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public final WebApplicationService extractService(final HttpServletRequest request) {
    final WebApplicationService service = extractServiceInternal(request);

    if (service == null) {
        logger.debug("Extractor did not generate service.");
    } else {
        logger.debug("Extractor generated service for: {}", service.getId());
    }

    return service;
}
 
Example #22
Source File: RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Adapts the current request to check user attributes.
 *
 * @param targetService the targeted service
 * @return the mfa authn method
 */
protected String checkMfaRoles(final WebApplicationService targetService) {
    final RequestContext context = RequestContextHolder.getRequestContext();
    if (context == null) {
        logger.debug("No request context is available, so skipping check for mfa role attributes.");
        return null;
    }

    final String tgt = context.getFlowScope().getString("ticketGrantingTicketId");
    if (StringUtils.isBlank(tgt)) {
        logger.debug("The tgt is not available in the flowscope, so skipping check for mfa role attributes.");
        return null;
    }

    final Authentication authentication = this.authenticationSupport.getAuthenticationFrom(tgt);
    if (authentication == null) {
        logger.debug("There is no current authentication, so skipping check for mfa role attributes.");
        return null;
    }

    final List<MultiFactorAuthenticationRequestContext> mfaRequestContexts = mfaRoleProcessor.resolve(authentication, targetService);
    if (mfaRequestContexts == null || mfaRequestContexts.isEmpty()) {
        logger.debug("No MFA role assignments were found in the authentication context");
        return null;
    }

    final String authnMethod = mfaRequestContexts.get(0).getMfaService().getAuthenticationMethod();
    logger.debug("MFA role returned is [{}]", authnMethod);
    return authnMethod;
}
 
Example #23
Source File: RegexAuthenticationMethodTranslator.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public String translate(final WebApplicationService targetService, final String triggerValue) {
    for (final Pattern pattern : translationMap.keySet()) {
        if (pattern.matcher(triggerValue).matches()) {
            return this.translationMap.get(pattern);
        }
    }

    if (this.defaultMfaMethod != null) {
        return defaultMfaMethod;
    }

    throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId());
}
 
Example #24
Source File: StubAuthenticationMethodTranslator.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public String translate(final WebApplicationService targetService, final String receivedAuthenticationMethod) {
    final Set<Set<String>> keys = this.translationMap.keySet();
    for (final Set<String> keyset : keys) {
        if (keyset.contains(receivedAuthenticationMethod)) {
            return this.translationMap.get(keyset);
        }
    }

    if (this.ignoreIfNoMatchIsFound) {
        return receivedAuthenticationMethod;
    }
    throw new UnrecognizedAuthenticationMethodException(receivedAuthenticationMethod, targetService.getId());
}
 
Example #25
Source File: AbstractSaml10ResponseView.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected void renderMergedOutputModel(
        final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.encoding);

    final WebApplicationService service = this.samlArgumentExtractor.extractService(request);
    final String serviceId = service != null ? service.getId() : "UNKNOWN";

    try {
        final Response samlResponse = newSamlObject(Response.class);
        samlResponse.setID(generateId());
        samlResponse.setIssueInstant(new DateTime());
        samlResponse.setVersion(SAMLVersion.VERSION_11);
        samlResponse.setRecipient(serviceId);
        if (service instanceof SamlService) {
            final SamlService samlService = (SamlService) service;

            if (samlService.getRequestID() != null) {
                samlResponse.setInResponseTo(samlService.getRequestID());
            }
        }
        prepareResponse(samlResponse, model);

        final BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
        messageContext.setOutboundMessageTransport(new HttpServletResponseAdapter(response, request.isSecure()));
        messageContext.setOutboundSAMLMessage(samlResponse);
        this.encoder.encode(messageContext);
    } catch (final Exception e) {
        logger.error("Error generating SAML response for service {}.", serviceId);
        throw e;
    }
}
 
Example #26
Source File: RegisteredServiceThemeBasedViewResolverTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetServiceWithTheme() throws Exception {
    final MockRequestContext requestContext = new MockRequestContext();
    RequestContextHolder.setRequestContext(requestContext);

    final WebApplicationService webApplicationService = new SimpleWebApplicationServiceImpl("myServiceId");
    requestContext.getFlowScope().put("service", webApplicationService);

    assertEquals("/WEB-INF/view/jsp/myTheme/ui/casLoginView",
            this.registeredServiceThemeBasedViewResolver.buildView("casLoginView").getUrl());
}
 
Example #27
Source File: RegisteredServiceThemeBasedViewResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Uses the viewName and the theme associated with the service.
 * being requested and returns the appropriate view.
 * @param viewName the name of the view to be resolved
 * @return a theme-based UrlBasedView
 * @throws Exception an exception
 */
@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service = WebUtils.getService(requestContext);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final String themeId = service != null && registeredService != null
            && registeredService.getAccessStrategy().isServiceAccessAllowed()
            && StringUtils.hasText(registeredService.getTheme()) ? registeredService.getTheme() : defaultThemeId;

    final String themePrefix = String.format("%s/%s/ui/", pathPrefix, themeId);
    LOGGER.debug("Prefix {} set for service {} with theme {}", themePrefix, service, themeId);

    //Build up the view like the base classes do, but we need to forcefully set the prefix for each request.
    //From UrlBasedViewResolver.buildView
    final InternalResourceView view = (InternalResourceView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(themePrefix + viewName + getSuffix());
    final String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }
    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    //From InternalResourceViewResolver.buildView
    view.setAlwaysInclude(false);
    view.setExposeContextBeansAsAttributes(false);
    view.setPreventDispatchLoop(true);

    LOGGER.debug("View resolved: {}", view.getUrl());

    return view;
}
 
Example #28
Source File: ServiceValidateController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Overrideable method to determine which credentials to use to grant a
 * proxy granting ticket. Default is to use the pgtUrl.
 *
 * @param service the webapp service requesting proxy
 * @param request the HttpServletRequest object.
 * @return the credentials or null if there was an error or no credentials
 * provided.
 */
protected Credential getServiceCredentialsFromRequest(final WebApplicationService service, final HttpServletRequest request) {
    final String pgtUrl = request.getParameter(CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL);
    if (StringUtils.hasText(pgtUrl)) {
        try {
            final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
            verifyRegisteredServiceProperties(registeredService, service);
            return new HttpBasedServiceCredential(new URL(pgtUrl), registeredService);
        } catch (final Exception e) {
            logger.error("Error constructing pgtUrl", e);
        }
    }

    return null;
}
 
Example #29
Source File: SamlServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyTargetMatchesingSamlService() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("TARGET", "https://some.service.edu/path/to/app");

    final SamlArgumentExtractor ext = new SamlArgumentExtractor();
    final WebApplicationService service = ext.extractService(request);

    final SamlService impl = SamlService.createServiceFrom(request);
    assertTrue(impl.matches(service));
}
 
Example #30
Source File: DefaultRegisteredServiceMfaRoleProcessorImpl.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Gets mfa request context.
 *
 * @param serviceMfaData service specific mfa settings
 * @param attributeValue the value found in the attribute
 * @param targetService  the target service
 * @return the mfa request context
 */
private MultiFactorAuthenticationRequestContext getMfaRequestContext(final ServiceMfaData serviceMfaData,
                                                                     final String attributeValue,
                                                                     final WebApplicationService targetService) {
    final RegisteredService registeredService = this.servicesManager.findServiceBy(targetService);

    String method = null;
    if (registeredService.getProperties().containsKey("method")) {
        method = registeredService.getProperties().get("method").getValue();
    }

    if (match(serviceMfaData.getAttributePattern(), attributeValue)) {
        if (!this.authenticationMethodConfiguration.containsAuthenticationMethod(serviceMfaData.getAuthenticationMethod())) {
            logger.info("MFA attribute [{}] with value [{}] is not supported by the authentication method configuration.",
                    serviceMfaData.getAttributeName(),
                    serviceMfaData.getAuthenticationMethod());
            return null;
        }
        final int mfaMethodRank = this.authenticationMethodConfiguration.getAuthenticationMethod(
                serviceMfaData.getAuthenticationMethod()).getRank();
        final MultiFactorAuthenticationSupportingWebApplicationService svc =
                this.mfaServiceFactory.create(targetService.getId(), targetService.getId(),
                        targetService.getArtifactId(), "POST".equals(method) ? ResponseType.POST : ResponseType.REDIRECT,
                        serviceMfaData.getAuthenticationMethod(),
                        MultiFactorAuthenticationSupportingWebApplicationService.AuthenticationMethodSource.PRINCIPAL_ATTRIBUTE);

        return new MultiFactorAuthenticationRequestContext(svc, mfaMethodRank);
    }

    logger.trace("{} did not match {}", attributeValue, serviceMfaData.getAttributePattern());
    return null;
}