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

The following examples show how to use org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl. 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: X509CertificateCredentialsNonInteractiveActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new X509CertificateCredentialsNonInteractiveAction();
    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<String, UniqueTicketIdGenerator>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final X509CredentialsAuthenticationHandler handler = new X509CredentialsAuthenticationHandler();
    handler.setTrustedIssuerDnPattern("CN=\\w+,DC=jasig,DC=org");

    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    handler, new X509SerialNumberPrincipalResolver()));

    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));

    this.action.setCentralAuthenticationService(centralAuthenticationService);
    this.action.afterPropertiesSet();
}
 
Example #2
Source File: FrontChannelLogoutActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID,
            new SimpleWebApplicationServiceImpl(TEST_URL),
            new URL(TEST_URL));
    final Event event = getLogoutEvent(Arrays.asList(logoutRequest));

    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
    assertTrue(url.startsWith(TEST_URL + "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="));
    final byte[] samlMessage = CompressionUtils.decodeBase64ToByteArray(
            URLDecoder.decode(StringUtils.substringAfter(url, "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}
 
Example #3
Source File: FrontChannelLogoutActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutOneLogoutRequestNotAttempted() throws Exception {
    final String FAKE_URL = "http://url";
    LogoutRequest logoutRequest = new LogoutRequest(TICKET_ID, new SimpleWebApplicationServiceImpl(FAKE_URL));
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    this.requestContext.getFlowScope().put(FrontChannelLogoutAction.LOGOUT_INDEX, 0);
    final Event event = this.frontChannelLogoutAction.doExecute(this.requestContext);
    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get("logoutUrl");
    assertTrue(url.startsWith(FAKE_URL + "?SAMLRequest="));
    final byte[] samlMessage = Base64.decodeBase64(URLDecoder.decode(StringUtils.substringAfter(url,  "?SAMLRequest="), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.indexOf("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>") >= 0);
}
 
Example #4
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction();

    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    new PrincipalBearingCredentialsAuthenticationHandler(),
                    new PrincipalBearingPrincipalResolver()));

    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));

    this.action.setCentralAuthenticationService(centralAuthenticationService);
}
 
Example #5
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction();

    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    new PrincipalBearingCredentialsAuthenticationHandler(),
                    new PrincipalBearingPrincipalResolver()));
    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));
    this.action.setCentralAuthenticationService(centralAuthenticationService);
}
 
Example #6
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction();

    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<String, UniqueTicketIdGenerator>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    new PrincipalBearingCredentialsAuthenticationHandler(),
                    new PrincipalBearingPrincipalResolver()));

    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));

    this.action.setCentralAuthenticationService(centralAuthenticationService);
}
 
Example #7
Source File: LogoutManagerImplTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Before
public void setUp() {

    when(client.isValidEndPoint(any(String.class))).thenReturn(true);
    when(client.isValidEndPoint(any(URL.class))).thenReturn(true);
    when(client.sendMessageToEndPoint(any(HttpMessage.class))).thenReturn(true);
    this.logoutManager = new LogoutManagerImpl(servicesManager, client, new SamlCompliantLogoutMessageCreator());

    this.services = new HashMap<>();
    this.simpleWebApplicationServiceImpl = new SimpleWebApplicationServiceImpl(URL);
    this.services.put(ID, this.simpleWebApplicationServiceImpl);
    when(this.tgt.getServices()).thenReturn(this.services);

    this.registeredService = new RegisteredServiceImpl();
    when(servicesManager.findServiceBy(this.simpleWebApplicationServiceImpl)).thenReturn(this.registeredService);
}
 
Example #8
Source File: TicketGrantingTicketImplTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyGetChainedPrincipalsWithTwo() {
    final Authentication authentication = TestUtils.getAuthentication();
    final Authentication authentication1 = TestUtils.getAuthentication("test1");
    final List<Authentication> principals = new ArrayList<>();
    principals.add(authentication);
    principals.add(authentication1);

    final TicketGrantingTicketImpl t1 = new TicketGrantingTicketImpl("test", null, null,
        authentication1, new NeverExpiresExpirationPolicy());
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test",
            new SimpleWebApplicationServiceImpl("gantor"), t1,
        authentication, new NeverExpiresExpirationPolicy());

    assertEquals(principals, t.getChainedAuthentications());
}
 
Example #9
Source File: X509CertificateCredentialsNonInteractiveActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new X509CertificateCredentialsNonInteractiveAction();
    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final X509CredentialsAuthenticationHandler handler = new X509CredentialsAuthenticationHandler();
    handler.setTrustedIssuerDnPattern("CN=\\w+,DC=jasig,DC=org");

    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    handler, new X509SerialNumberPrincipalResolver()));

    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));

    this.action.setCentralAuthenticationService(centralAuthenticationService);
    this.action.afterPropertiesSet();
}
 
Example #10
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.action = new PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction();

    final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<String, UniqueTicketIdGenerator>();
    idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator());


    final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager(
            Collections.<AuthenticationHandler, PrincipalResolver>singletonMap(
                    new PrincipalBearingCredentialsAuthenticationHandler(),
                    new PrincipalBearingPrincipalResolver()));
    final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl(
            new DefaultTicketRegistry(), null, authenticationManager, new DefaultUniqueTicketIdGenerator(),
            idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(),
            mock(ServicesManager.class), mock(LogoutManager.class));
    this.action.setCentralAuthenticationService(centralAuthenticationService);
}
 
Example #11
Source File: LogoutAction.java    From cas4.0.x-server-wechat with Apache License 2.0 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 (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 RegisteredService rService = this.servicesManager.findServiceBy(new SimpleWebApplicationServiceImpl(service));

        if (rService != null && rService.isEnabled()) {
            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 #12
Source File: ClientActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(ClientAction.THEME, MY_THEME);
    mockRequest.setParameter(ClientAction.LOCALE, MY_LOCALE);
    mockRequest.setParameter(ClientAction.METHOD, MY_METHOD);

    final MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);
    mockRequestContext.getFlowScope().put(ClientAction.SERVICE, new SimpleWebApplicationServiceImpl(MY_SERVICE));

    final FacebookClient facebookClient = new FacebookClient(MY_KEY, MY_SECRET);
    final TwitterClient twitterClient = new TwitterClient(MY_KEY, MY_SECRET);
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient, twitterClient);
    final ClientAction action = new ClientAction(mock(CentralAuthenticationService.class), clients);

    final Event event = action.execute(mockRequestContext);
    assertEquals("error", event.getId());
    assertEquals(MY_THEME, mockSession.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockSession.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockSession.getAttribute(ClientAction.METHOD));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    assertTrue(((String) flowScope.get("FacebookClientUrl"))
            .startsWith("https://www.facebook.com/v2.2/dialog/oauth?client_id=my_key&redirect_uri=http%3A%2F%2Fcasserver%2Flogin%3F"
                    + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "%3DFacebookClient&state="));
    assertEquals(MY_LOGIN_URL + "?" + Clients.DEFAULT_CLIENT_NAME_PARAMETER
            + "=TwitterClient&needs_client_redirection=true", flowScope.get("TwitterClientUrl"));
}
 
Example #13
Source File: ClientActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");

    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(ClientAction.THEME, MY_THEME);
    mockSession.setAttribute(ClientAction.LOCALE, MY_LOCALE);
    mockSession.setAttribute(ClientAction.METHOD, MY_METHOD);
    final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE);
    mockSession.setAttribute(ClientAction.SERVICE, service);
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final FacebookClient facebookClient = new MockFacebookClient();
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);

    final ClientAction action = new ClientAction(mock(CentralAuthenticationService.class), clients);
    final Event event = action.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockRequest.getAttribute(ClientAction.METHOD));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    assertEquals(service, flowScope.get(ClientAction.SERVICE));
}
 
Example #14
Source File: JBossCacheTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<Ticket>();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                "TEST" + i, TestUtils.getAuthentication(),
                new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket(
                "tests" + i, SimpleWebApplicationServiceImpl.createServiceFrom(request),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals(
                "The size of the registry is not the same as the collection.",
                ticketRegistryTickets.size(), tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example #15
Source File: ManageRegisteredServicesMultiActionController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Instantiates a new manage registered services multi action controller.
 *
 * @param servicesManager the services manager
 * @param defaultServiceUrl the default service url
 */
@Autowired
public ManageRegisteredServicesMultiActionController(final ServicesManager servicesManager,
        @Value("${cas-management.securityContext.serviceProperties.service}") final String defaultServiceUrl) {
    super(servicesManager);
    this.defaultService = new SimpleWebApplicationServiceImpl(defaultServiceUrl);
}
 
Example #16
Source File: LogoutManagerImplTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    final ServicesManager servicesManager = mock(ServicesManager.class);
    this.logoutManager = new LogoutManagerImpl(servicesManager, new SimpleHttpClient(), new SamlCompliantLogoutMessageCreator());
    this.tgt = mock(TicketGrantingTicket.class);
    this.services = new HashMap<String, Service>();
    this.simpleWebApplicationServiceImpl = new SimpleWebApplicationServiceImpl(URL);
    this.services.put(ID, this.simpleWebApplicationServiceImpl);
    when(this.tgt.getServices()).thenReturn(this.services);
    this.registeredService = new RegisteredServiceImpl();
    when(servicesManager.findServiceBy(this.simpleWebApplicationServiceImpl)).thenReturn(this.registeredService);
}
 
Example #17
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 #18
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 #19
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 #20
Source File: TicketGrantingTicketImplTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyIsRootFalse() {
    final TicketGrantingTicketImpl t1 = new TicketGrantingTicketImpl("test", null, null,
        TestUtils.getAuthentication(), new NeverExpiresExpirationPolicy());
    final TicketGrantingTicket t = new TicketGrantingTicketImpl("test",
            new SimpleWebApplicationServiceImpl("gantor"), t1,
        TestUtils.getAuthentication(), new NeverExpiresExpirationPolicy());

    assertFalse(t.isRoot());
}
 
Example #21
Source File: JBossCacheTicketRegistryTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyGetTicketsFromRegistryEqualToTicketsAdded() {
    final Collection<Ticket> tickets = new ArrayList<>();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", "test");

    for (int i = 0; i < TICKETS_IN_REGISTRY; i++) {
        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
                "TEST" + i, TestUtils.getAuthentication(),
                new NeverExpiresExpirationPolicy());
        final ServiceTicket st = ticketGrantingTicket.grantServiceTicket(
                "tests" + i, SimpleWebApplicationServiceImpl.createServiceFrom(request),
                new NeverExpiresExpirationPolicy(), false);
        tickets.add(ticketGrantingTicket);
        tickets.add(st);
        this.ticketRegistry.addTicket(ticketGrantingTicket);
        this.ticketRegistry.addTicket(st);
    }

    try {
        final Collection<Ticket> ticketRegistryTickets = this.ticketRegistry.getTickets();
        assertEquals(
                "The size of the registry is not the same as the collection.",
                ticketRegistryTickets.size(), tickets.size());

        for (final Ticket ticket : tickets) {
            if (!ticketRegistryTickets.contains(ticket)) {
                fail("Ticket was added to registry but was not found in retrieval of collection of all tickets.");
            }
        }
    } catch (final Exception e) {
        fail("Caught an exception. But no exception should have been thrown.");
    }
}
 
Example #22
Source File: ClientActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");

    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(ClientAction.THEME, MY_THEME);
    mockSession.setAttribute(ClientAction.LOCALE, MY_LOCALE);
    mockSession.setAttribute(ClientAction.METHOD, MY_METHOD);
    final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE);
    mockSession.setAttribute(ClientAction.SERVICE, service);
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final FacebookClient facebookClient = new MockFacebookClient();
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);

    final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class), mock(ExpirationPolicy.class));
    final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class);
    when(casImpl.createTicketGrantingTicket(any(Credential.class))).thenReturn(tgt);
    final ClientAction action = new ClientAction(casImpl, clients);
    final Event event = action.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockRequest.getAttribute(ClientAction.METHOD));
    assertEquals(MY_SERVICE, mockRequest.getAttribute(ClientAction.SERVICE));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
    assertEquals(service, flowScope.get(ClientAction.SERVICE));
    assertEquals(TGT_ID, flowScope.get(TGT_NAME));
    assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}
 
Example #23
Source File: ClientActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyStartAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(ClientAction.THEME, MY_THEME);
    mockRequest.setParameter(ClientAction.LOCALE, MY_LOCALE);
    mockRequest.setParameter(ClientAction.METHOD, MY_METHOD);

    final MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);
    mockRequestContext.getFlowScope().put(ClientAction.SERVICE, new SimpleWebApplicationServiceImpl(MY_SERVICE));

    final FacebookClient facebookClient = new FacebookClient(MY_KEY, MY_SECRET);
    final TwitterClient twitterClient = new TwitterClient(MY_KEY, MY_SECRET);
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient, twitterClient);
    final ClientAction action = new ClientAction(mock(CentralAuthenticationService.class), clients);

    final Event event = action.execute(mockRequestContext);
    assertEquals("error", event.getId());
    assertEquals(MY_THEME, mockSession.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockSession.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockSession.getAttribute(ClientAction.METHOD));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    assertTrue(((String) flowScope.get("FacebookClientUrl"))
            .startsWith("https://www.facebook.com/v2.2/dialog/oauth?client_id=my_key&redirect_uri=http%3A%2F%2Fcasserver%2Flogin%3F"
                    + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "%3DFacebookClient&state="));
    assertEquals(MY_LOGIN_URL + "?" + Clients.DEFAULT_CLIENT_NAME_PARAMETER
            + "=TwitterClient&needs_client_redirection=true", flowScope.get("TwitterClientUrl"));
}
 
Example #24
Source File: KryoTranscoder.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize and register classes with kryo.
 */
public void initialize() {
    // Register types we know about and do not require external configuration
    kryo.register(ArrayList.class);
    kryo.register(BasicCredentialMetaData.class);
    kryo.register(Class.class, new DefaultSerializers.ClassSerializer());
    kryo.register(Date.class, new DefaultSerializers.DateSerializer());
    kryo.register(HardTimeoutExpirationPolicy.class);
    kryo.register(HashMap.class);
    kryo.register(HandlerResult.class);
    kryo.register(ImmutableAuthentication.class);
    kryo.register(MultiTimeUseOrTimeoutExpirationPolicy.class);
    kryo.register(NeverExpiresExpirationPolicy.class);
    kryo.register(RememberMeDelegatingExpirationPolicy.class);
    kryo.register(ServiceTicketImpl.class);
    kryo.register(SimpleWebApplicationServiceImpl.class, new SimpleWebApplicationServiceSerializer());
    kryo.register(ThrottledUseAndTimeoutExpirationPolicy.class);
    kryo.register(TicketGrantingTicketExpirationPolicy.class);
    kryo.register(TicketGrantingTicketImpl.class);
    kryo.register(TimeoutExpirationPolicy.class);
    kryo.register(URL.class, new URLSerializer());

    // we add these ones for tests only
    kryo.register(RegisteredServiceImpl.class, new RegisteredServiceSerializer());
    kryo.register(RegexRegisteredService.class, new RegisteredServiceSerializer());

    // new serializers to manage Joda dates and immutable collections
    kryo.register(DateTime.class, new JodaDateTimeSerializer());
    // from the kryo-serializers library (https://github.com/magro/kryo-serializers)
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);

    // Register other types
    if (serializerMap != null) {
        for (final Map.Entry<Class<?>, Serializer> clazz : serializerMap.entrySet()) {
            kryo.register(clazz.getKey(), clazz.getValue());
        }
    }

    // don't reinit the registered classes after every write or read
    kryo.setAutoReset(false);
    // don't replace objects by references
    kryo.setReferences(false);
    // Catchall for any classes not explicitly registered
    kryo.setRegistrationRequired(false);
}
 
Example #25
Source File: ProxyController.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
private Service getTargetService(final HttpServletRequest request) {
    return SimpleWebApplicationServiceImpl.createServiceFrom(request);
}
 
Example #26
Source File: SimpleWebApplicationServiceSerializer.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
@Override
public void write(final Kryo kryo, final Output output, final SimpleWebApplicationServiceImpl service) {
    kryo.writeObject(output, service.getId());
}
 
Example #27
Source File: SimpleWebApplicationServiceSerializer.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
@Override
public SimpleWebApplicationServiceImpl read(final Kryo kryo, final Input input, final Class<SimpleWebApplicationServiceImpl> type) {
    return new SimpleWebApplicationServiceImpl(kryo.readObject(input, String.class));
}
 
Example #28
Source File: MultifactorAuthenticationTests.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
private static Service newService(final String id) {
    return new SimpleWebApplicationServiceImpl(id);
}
 
Example #29
Source File: SamlMetadataUIParserAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
    final String entityId = request.getParameter(this.entityIdParameterName);
    if (StringUtils.isBlank(entityId)) {
        logger.debug("No entity id found for parameter [{}]", this.entityIdParameterName);
        return success();
    }

    final WebApplicationService service = new SimpleWebApplicationServiceImpl(entityId);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        logger.debug("Entity id [{}] is not recognized/allowed by the CAS service registry", entityId);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE,
                "Entity " + entityId + " not recognized");
    }

    final EntityDescriptor entityDescriptor = this.metadataAdapter.getEntityDescriptorForEntityId(entityId);
    if (entityDescriptor == null) {
        logger.debug("Entity descriptor not found for [{}]", entityId);
        return success();
    }

    final SPSSODescriptor spssoDescriptor = getSPSSODescriptor(entityDescriptor);
    if (spssoDescriptor == null) {
        logger.debug("SP SSO descriptor not found for [{}]", entityId);
        return success();
    }

    final Extensions extensions = spssoDescriptor.getExtensions();
    final List<XMLObject> spExtensions = extensions.getUnknownXMLObjects(UIInfo.DEFAULT_ELEMENT_NAME);
    if (spExtensions.isEmpty()) {
        logger.debug("No extensions are found for [{}]", UIInfo.DEFAULT_ELEMENT_NAME.getNamespaceURI());
        return success();
    }

    final SimpleMetadataUIInfo mdui = new SimpleMetadataUIInfo(registeredService);

    for (final XMLObject obj : spExtensions) {
        if (obj instanceof UIInfo) {
            final UIInfo uiInfo = (UIInfo) obj;
            logger.debug("Found UI info for [{}] and added to flow context", entityId);
            mdui.setUIInfo(uiInfo);
        }
    }

    requestContext.getFlowScope().put(MDUI_FLOW_PARAMETER_NAME, mdui);
    return success();
}
 
Example #30
Source File: TestUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
public static Service getService(final String name) {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("service", name);
    return SimpleWebApplicationServiceImpl.createServiceFrom(request);
}