org.jasig.cas.services.RegisteredService Java Examples

The following examples show how to use org.jasig.cas.services.RegisteredService. 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: RegisteredServiceDefaultAttributeFilter.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> filter(final String principalId, final Map<String, Object> givenAttributes,
        final RegisteredService registeredService) {
    final Map<String, Object> attributes = new HashMap<String, Object>();

    if (registeredService.isIgnoreAttributes()) {
        logger.debug("Service [{}] is set to ignore attribute release policy. Releasing all attributes.",
                registeredService.getName());
        attributes.putAll(givenAttributes);
    } else {
        for (final String attribute : registeredService.getAllowedAttributes()) {
            final Object value = givenAttributes.get(attribute);

            if (value != null) {
                logger.debug("Found attribute [{}] in the list of allowed attributes for service [{}]", attribute,
                        registeredService.getName());
                attributes.put(attribute, value);
            }
        }
    }
    return Collections.unmodifiableMap(attributes);
}
 
Example #2
Source File: LogoutManagerImpl.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Determine logout url.
 *
 * @param registeredService the registered service
 * @param singleLogoutService the single logout service
 * @return the uRL
 */
private URL determineLogoutUrl(final RegisteredService registeredService, final SingleLogoutService singleLogoutService) {
    try {
        URL logoutUrl = new URL(singleLogoutService.getOriginalUrl());
        final URL serviceLogoutUrl = registeredService.getLogoutUrl();

        if (serviceLogoutUrl != null) {
            LOGGER.debug("Logout request will be sent to [{}] for service [{}]",
                    serviceLogoutUrl, singleLogoutService);
            logoutUrl = serviceLogoutUrl;
        }
        return logoutUrl;
    } catch (final Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #3
Source File: OAuth20AuthorizeControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRedirectUriDoesNotStartWithServiceId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(OTHER_REDIRECT_URI, CLIENT_ID));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.ERROR_VIEW, modelAndView.getViewName());
}
 
Example #4
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public RegisteredService findServiceById(final long id) {
    Connection connection = null;
    try {
        connection = this.connectionFactory.getConnection();

        final Response<SearchResult> response = searchForServiceById(connection, id);
        if (hasResults(response)) {
            return this.ldapServiceMapper.mapToRegisteredService(response.getResult().getEntry());
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }

    return null;
}
 
Example #5
Source File: OAuthRegisteredServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void checkSaveMethod() {
    final OAuthRegisteredService r = new OAuthRegisteredService();
    r.setName("checkSaveMethod");
    r.setServiceId("testId");
    r.setTheme("theme");
    r.setDescription("description");
    r.setClientId("clientid");
    r.setServiceId("secret");
    r.setBypassApprovalPrompt(true);
    final RegisteredService r2 = this.dao.save(r);
    assertTrue(r2 instanceof OAuthRegisteredService);
    this.dao.load();
    final RegisteredService r3 = this.dao.findServiceById(r2.getId());
    assertTrue(r3 instanceof OAuthRegisteredService);
    assertEquals(r, r2);
    assertEquals(r2, r3);
}
 
Example #6
Source File: SendTicketGrantingTicketAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Tries to determine if authentication was created as part of a "renew" event.
 * Renewed authentications can occur if the service is not allowed to participate
 * in SSO or if a "renew" request parameter is specified.
 *
 * @param ctx the request context
 * @return true if renewed
 */
private boolean isAuthenticationRenewed(final RequestContext ctx) {
    if (ctx.getRequestParameters().contains(CasProtocolConstants.PARAMETER_RENEW)) {
        LOGGER.debug("[{}] is specified for the request. The authentication session will be considered renewed.",
                CasProtocolConstants.PARAMETER_RENEW);
        return true;
    }

    final Service service = WebUtils.getService(ctx);
    if (service != null) {
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (registeredService != null) {
            final boolean isAllowedForSso = registeredService.getAccessStrategy().isServiceAccessAllowedForSso();
            LOGGER.debug("Located [{}] in registry. Service access to participate in SSO is set to [{}]",
                    registeredService.getServiceId(), isAllowedForSso);
            return !isAllowedForSso;
        }
    }

    return false;
}
 
Example #7
Source File: Cas30ResponseView.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Decide attribute release based on service attribute policy.
 *
 * @param attributes the attributes
 * @param attributeValue the attribute value
 * @param attributeName the attribute name
 * @param service the service
 * @param doesAttributePolicyAllow does attribute policy allow release of this attribute?
 */
protected void decideAttributeReleaseBasedOnServiceAttributePolicy(final Map<String, Object> attributes,
                                                                   final String attributeValue,
                                                                   final String attributeName,
                                                                   final RegisteredService service,
                                                                   final boolean doesAttributePolicyAllow) {
    if (StringUtils.isNotBlank(attributeValue)) {
        logger.debug("Obtained [{}] as an authentication attribute", attributeName);

        if (doesAttributePolicyAllow) {
            logger.debug("Obtained [{}] is passed to the CAS validation payload", attributeName);
            attributes.put(attributeName, Collections.singleton(attributeValue));
        } else {
            logger.debug("Attribute release policy for [{}] does not authorize the release of [{}]",
                    service.getServiceId(), attributeName);
        }
    } else {
        logger.trace("[{}] is not available and will not be released to the validation response.", attributeName);
    }
}
 
Example #8
Source File: OAuth20AccessTokenControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<RegisteredService>();
    services.add(getRegisteredService(REDIRECT_URI, WRONG_CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}
 
Example #9
Source File: Cas30ResponseView.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected void prepareMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request,
                                        final HttpServletResponse response) throws Exception {

    super.prepareMergedOutputModel(model, request, response);

    final Service service = super.getServiceFrom(model);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final Map<String, Object> attributes = new HashMap<>(getPrincipalAttributesAsMultiValuedAttributes(model));
    attributes.put(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE,
            Collections.singleton(getAuthenticationDate(model)));
    attributes.put(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN,
            Collections.singleton(isAssertionBackedByNewLogin(model)));
    attributes.put(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME,
            Collections.singleton(isRememberMeAuthentication(model)));

    decideIfCredentialPasswordShouldBeReleasedAsAttribute(attributes, model, registeredService);
    decideIfProxyGrantingTicketShouldBeReleasedAsAttribute(attributes, model, registeredService);

    super.putIntoModel(model,
            CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES,
            this.casAttributeEncoder.encodeAttributes(attributes, getServiceFrom(model)));
}
 
Example #10
Source File: DefaultCasAttributeEncoder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Encrypt, encode and put the attribute into attributes map.
 *
 * @param attributes the attributes
 * @param cachedAttributesToEncode the cached attributes to encode
 * @param cachedAttributeName the cached attribute name
 * @param cipher the cipher
 * @param registeredService the registered service
 */
protected final void encryptAndEncodeAndPutIntoAttributesMap(final Map<String, Object> attributes,
                                                       final Map<String, String> cachedAttributesToEncode,
                                                       final String cachedAttributeName,
                                                       final RegisteredServiceCipherExecutor cipher,
                                                       final RegisteredService registeredService) {
    final String cachedAttribute = cachedAttributesToEncode.remove(cachedAttributeName);
    if (StringUtils.isNotBlank(cachedAttribute)) {
        logger.debug("Retrieved [{}] as a cached model attribute...", cachedAttributeName);
        final String encodedValue = cipher.encode(cachedAttribute, registeredService);
        if (StringUtils.isNotBlank(encodedValue)) {
            attributes.put(cachedAttributeName, encodedValue);
            logger.debug("Encrypted and encoded [{}] as an attribute to [{}].",
                    cachedAttributeName, encodedValue);
        }
    } else {
        logger.debug("[{}] is not available as a cached model attribute to encrypt...", cachedAttributeName);
    }
}
 
Example #11
Source File: AbstractCasAttributeEncoder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public final Map<String, Object> encodeAttributes(final Map<String, Object> attributes,
                                                  final Service service) {
    logger.debug("Starting to encode attributes for release to service [{}]", service);
    final Map<String, Object> newEncodedAttributes = new HashMap<>(attributes);
    final Map<String, String> cachedAttributesToEncode = initialize(newEncodedAttributes);

    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        encodeAttributesInternal(newEncodedAttributes, cachedAttributesToEncode,
                this.cipherExecutor, registeredService);
        logger.debug("[{}] Encoded attributes are available for release to [{}]",
                newEncodedAttributes.size(), service);
    } else {
        logger.debug("Service [{}] is not found and/or enabled in the service registry. "
                + "No encoding has taken place.", service);
    }

    return newEncodedAttributes;
}
 
Example #12
Source File: OAuth20AccessTokenControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyWrongSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, WRONG_CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}
 
Example #13
Source File: RegisteredServiceSimpleFormControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyAddMockRegisteredService() throws Exception {
    final RegexRegisteredService svc = new RegexRegisteredService();
    svc.setDescription("description");
    svc.setServiceId("^serviceId");
    svc.setName("name");
    svc.setId(1000);
    svc.setEvaluationOrder(1000);

    final RegisteredServiceEditBean data = RegisteredServiceEditBean.fromRegisteredService(svc);
    this.controller.saveService(new MockHttpServletRequest(),
            new MockHttpServletResponse(),
            data.getServiceData(), mock(BindingResult.class));

    final Collection<RegisteredService> services = this.manager.getAllServices();
    assertEquals(1, services.size());
    for (final  RegisteredService rs : this.manager.getAllServices()) {
        assertTrue(rs instanceof RegisteredService);
    }
}
 
Example #14
Source File: ServiceAuthorizationCheckTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Before
public void setUpMocks() {
    RegisteredServiceImpl authorizedRegisteredService = new RegisteredServiceImpl();
    RegisteredServiceImpl unauthorizedRegisteredService = new RegisteredServiceImpl();
    unauthorizedRegisteredService.setEnabled(false);

    List<RegisteredService> list = new ArrayList<RegisteredService>();
    list.add(authorizedRegisteredService);
    list.add(unauthorizedRegisteredService);
    
    when(this.servicesManager.findServiceBy(this.authorizedService)).thenReturn(authorizedRegisteredService);
    when(this.servicesManager.findServiceBy(this.unauthorizedService)).thenReturn(unauthorizedRegisteredService);
    when(this.servicesManager.findServiceBy(this.undefinedService)).thenReturn(null);
    
    when(this.servicesManager.getAllServices()).thenReturn(list);
    
    this.serviceAuthorizationCheck = new ServiceAuthorizationCheck(this.servicesManager);
}
 
Example #15
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 #16
Source File: ManageRegisteredServicesMultiActionController.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Method to delete the RegisteredService by its ID. Will make sure
 * the default service that is the management app itself cannot be deleted
 * or the user will be locked out.
 *
 * @param idAsLong the id
 * @param response the response
 */
@RequestMapping(value="deleteRegisteredService.html", method={RequestMethod.POST})
public void deleteRegisteredService(@RequestParam("id") final long idAsLong,
                                    final HttpServletResponse response) {
    final RegisteredService svc = this.servicesManager.findServiceBy(this.defaultService);
    if (svc == null || svc.getId() == idAsLong) {
        throw new IllegalArgumentException("The default service " + defaultService.getId() + " cannot be deleted. "
                                   + "The definition is required for accessing the application.");
    }

    final RegisteredService r = this.servicesManager.delete(idAsLong);
    if (r == null) {
        throw new IllegalArgumentException("Service id " + idAsLong + " cannot be found.");
    }
    final Map<String, Object> model = new HashMap<>();
    model.put("serviceName", r.getName());
    model.put("status", HttpServletResponse.SC_OK);
    JsonViewUtils.render(model, response);
}
 
Example #17
Source File: RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractorTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceWithDifferentServiceType() {
    final List<ArgumentExtractor> set = new ArrayList<>();
    set.add(new CasArgumentExtractor());
    
    final MultiFactorWebApplicationServiceFactory factory = mock(MultiFactorWebApplicationServiceFactory.class);
    final AuthenticationMethodVerifier verifier = mock(AuthenticationMethodVerifier.class);
    
    final RegisteredService svc = mock(RegisteredService.class);
    when(svc.getId()).thenReturn(0L);
    when(svc.getServiceId()).thenReturn(CAS_SERVICE);
    
    final ServicesManager mgmr = mock(ServicesManager.class);
    when(mgmr.findServiceBy(anyInt())).thenReturn(svc);
    when(mgmr.findServiceBy(any(Service.class))).thenReturn(svc);
    
    final RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor extractor = 
            new RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor(set, factory, mgmr, verifier);

    final MultiFactorAuthenticationSupportingWebApplicationService webSvc =
            (MultiFactorAuthenticationSupportingWebApplicationService) extractor.extractService(getRequest());
    assertNull(webSvc);
}
 
Example #18
Source File: LdapServiceRegistryDaoTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyUpdatingServices() {
    this.dao.save(getRegisteredService());
    final List<RegisteredService> services = this.dao.load();

    final AbstractRegisteredService rs = (AbstractRegisteredService) this.dao.findServiceById(services.get(0).getId());
    assertNotNull(rs);
    rs.setEvaluationOrder(9999);
    rs.setUsernameAttributeProvider(new DefaultRegisteredServiceUsernameProvider());
    rs.setName("Another Test Service");
    rs.setDescription("The new description");
    rs.setServiceId("https://hello.world");
    rs.setProxyPolicy(new RegexMatchingRegisteredServiceProxyPolicy("https"));
    rs.setAttributeReleasePolicy(new ReturnAllowedAttributeReleasePolicy());
    assertNotNull(this.dao.save(rs));

    final RegisteredService rs3 = this.dao.findServiceById(rs.getId());
    assertEquals(rs3.getName(), rs.getName());
    assertEquals(rs3.getDescription(), rs.getDescription());
    assertEquals(rs3.getEvaluationOrder(), rs.getEvaluationOrder());
    assertEquals(rs3.getUsernameAttributeProvider(), rs.getUsernameAttributeProvider());
    assertEquals(rs3.getProxyPolicy(), rs.getProxyPolicy());
    assertEquals(rs3.getUsernameAttributeProvider(), rs.getUsernameAttributeProvider());
    assertEquals(rs3.getServiceId(), rs.getServiceId());
}
 
Example #19
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService rs) {
    if (rs.getId() != RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        return update(rs);
    }

    Connection connection = null;
    try {
        connection = getConnection();
        final AddOperation operation = new AddOperation(connection);

        final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
        operation.execute(new AddRequest(entry.getDn(), entry.getAttributes()));
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return rs;
}
 
Example #20
Source File: DefaultLdapRegisteredServiceMapper.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {
    try {
        if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
            ((AbstractRegisteredService) svc).setId(System.nanoTime());
        }
        final String newDn = getDnForRegisteredService(dn, svc);
        LOGGER.debug("Creating entry {}", newDn);

        final Collection<LdapAttribute> attrs = new ArrayList<>();
        attrs.add(new LdapAttribute(this.idAttribute, String.valueOf(svc.getId())));

        final StringWriter writer = new StringWriter();
        this.jsonSerializer.toJson(writer, svc);
        attrs.add(new LdapAttribute(this.serviceDefinitionAttribute, writer.toString()));
        attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, "top", this.objectClass));

        return new LdapEntry(newDn, attrs);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: RegisteredServiceSimpleFormControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyAddRegisteredServiceWithValues() throws Exception {
    final RegisteredServiceImpl svc = new RegisteredServiceImpl();
    svc.setDescription("description");
    svc.setServiceId("serviceId");
    svc.setName("name");
    svc.setEvaluationOrder(123);
    
    assertTrue(this.manager.getAllServices().isEmpty());
    final RegisteredServiceEditBean data = RegisteredServiceEditBean.fromRegisteredService(svc);
    this.controller.saveService(new MockHttpServletRequest(),
            new MockHttpServletResponse(),
            data.getServiceData(), mock(BindingResult.class));

    final Collection<RegisteredService> services = this.manager.getAllServices();
    assertEquals(1, services.size());
    for(final RegisteredService rs : this.manager.getAllServices()) {
        assertTrue(rs instanceof RegexRegisteredService);
    }
}
 
Example #22
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public List<RegisteredService> load() {
    Connection connection = null;
    final List<RegisteredService> list = new LinkedList<RegisteredService>();
    try {
        connection = this.connectionFactory.getConnection();
        final Response<SearchResult> response =
                executeSearchOperation(connection, new SearchFilter(this.loadFilter));
        if (hasResults(response)) {
            for (final LdapEntry entry : response.getResult().getEntries()) {
                final RegisteredService svc = this.ldapServiceMapper.mapToRegisteredService(entry);
                list.add(svc);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return list;
}
 
Example #23
Source File: RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractorTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceWithNoAttributeValue() {
    final List<ArgumentExtractor> set = new ArrayList<>();
    set.add(new CasArgumentExtractor());
    
    final MultiFactorWebApplicationServiceFactory factory = mock(MultiFactorWebApplicationServiceFactory.class);
    final AuthenticationMethodVerifier verifier = mock(AuthenticationMethodVerifier.class);

    final RegisteredService svc = TestUtils.getRegisteredService(CAS_SERVICE);
    final DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty();
    svc.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop);
    
    final ServicesManager mgmr = mock(ServicesManager.class);
    when(mgmr.findServiceBy(anyInt())).thenReturn(svc);
    when(mgmr.findServiceBy(any(Service.class))).thenReturn(svc);
    
    final RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor extractor = 
            new RegisteredServiceAttributeMultiFactorAuthenticationArgumentExtractor(set, factory, mgmr, verifier);
    
    final MultiFactorAuthenticationSupportingWebApplicationService webSvc =
            (MultiFactorAuthenticationSupportingWebApplicationService) extractor.extractService(getRequest());
    assertNull(webSvc);
}
 
Example #24
Source File: OAuth20AccessTokenControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRedirectUriDoesNotStartWithServiceId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(OTHER_REDIRECT_URI, CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}
 
Example #25
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 #26
Source File: Cas30ResponseView.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request,
                                        final HttpServletResponse response) throws Exception {

    super.prepareMergedOutputModel(model, request, response);

    final Service service = super.getServiceFrom(model);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final Map<String, Object> attributes = new HashMap<>(getPrincipalAttributesAsMultiValuedAttributes(model));
    attributes.put(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE,
            Collections.singleton(getAuthenticationDate(model)));
    attributes.put(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN,
            Collections.singleton(isAssertionBackedByNewLogin(model)));
    attributes.put(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME,
            Collections.singleton(isRememberMeAuthentication(model)));

    decideIfCredentialPasswordShouldBeReleasedAsAttribute(attributes, model, registeredService);
    decideIfProxyGrantingTicketShouldBeReleasedAsAttribute(attributes, model, registeredService);

    attributes.put(this.authenticationMethodResponseAttribute,
            getAuthenticationAttribute(model, MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD));

    super.putIntoModel(model,
            CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES,
            this.casAttributeEncoder.encodeAttributes(attributes, getServiceFrom(model)));
}
 
Example #27
Source File: LdapServiceRegistryDaoTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifySavingServices() {
    this.dao.save(getRegisteredService());
    this.dao.save(getRegexRegisteredService());
    final List<RegisteredService> services = this.dao.load();
    assertEquals(2, services.size());
}
 
Example #28
Source File: RegisteredServiceSimpleFormControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testEditMockRegisteredService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();

    final MockRegisteredService r = new MockRegisteredService();
    r.setId(1000);
    r.setName("Test Service");
    r.setServiceId("test");
    r.setDescription("description");

    this.manager.save(r);

    request.addParameter("description", "description");
    request.addParameter("serviceId", "serviceId1");
    request.addParameter("name", "name");
    request.addParameter("theme", "theme");
    request.addParameter("allowedToProxy", "true");
    request.addParameter("enabled", "true");
    request.addParameter("ssoEnabled", "true");
    request.addParameter("anonymousAccess", "false");
    request.addParameter("evaluationOrder", "2");
    request.addParameter("id", "1000");

    request.setMethod("POST");

    this.controller.handleRequest(request, response);

    assertFalse(this.manager.getAllServices().isEmpty());
    final RegisteredService r2 = this.manager.findServiceBy(1000);

    assertEquals("serviceId1", r2.getServiceId());
    assertTrue(r2 instanceof MockRegisteredService);
}
 
Example #29
Source File: LogoutAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response,
        final RequestContext context) throws Exception {

    boolean needFrontSlo = false;
    putLogoutIndex(context, 0);
    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    if (logoutRequests != null) {
        for (final LogoutRequest logoutRequest : logoutRequests) {
            // if some logout request must still be attempted
            if (logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED) {
                needFrontSlo = true;
                break;
            }
        }
    }

    final String service = request.getParameter("service");
    if (this.followServiceRedirects && service != null) {
        final Service webAppService = new SimpleWebApplicationServiceImpl(service);
        final RegisteredService rService = this.servicesManager.findServiceBy(webAppService);

        if (rService != null && rService.getAccessStrategy().isServiceAccessAllowed()) {
            context.getFlowScope().put("logoutRedirectUrl", service);
        }
    }

    // there are some front services to logout, perform front SLO
    if (needFrontSlo) {
        return new Event(this, FRONT_EVENT);
    } else {
        // otherwise, finish the logout process
        return new Event(this, FINISH_EVENT);
    }
}
 
Example #30
Source File: ManageRegisteredServicesMultiActionController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Gets services.
 *
 * @param response the response
 */
@RequestMapping(value="getServices.html", method={RequestMethod.GET})
public void getServices(final HttpServletResponse response) {
    ensureDefaultServiceExists();
    final Map<String, Object> model = new HashMap<>();
    final List<RegisteredServiceViewBean> serviceBeans = new ArrayList<>();
    final List<RegisteredService> services = new ArrayList<>(this.servicesManager.getAllServices());
    for (final RegisteredService svc : services) {
        serviceBeans.add(RegisteredServiceViewBean.fromRegisteredService(svc));
    }
    model.put("services", serviceBeans);
    model.put("status", HttpServletResponse.SC_OK);
    JsonViewUtils.render(model, response);
}