org.jasig.cas.web.support.WebUtils Java Examples

The following examples show how to use org.jasig.cas.web.support.WebUtils. 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: TerminatingMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the ticket granting ticket.
 *
 * @param authentication the authentication
 * @param context        the context
 * @param credentials    the credentials
 * @param messageContext the message context
 * @param id             the id
 * @return the event
 * @throws Exception the exception
 */
private Event createTicketGrantingTicket(final Authentication authentication, final RequestContext context,
                                         final Credential credentials, final MessageContext messageContext,
                                         final String id) throws Exception {

    final MultiFactorCredentials mfa = MultiFactorRequestContextUtils.getMfaCredentials(context);

    mfa.addAuthenticationToChain(authentication);
    mfa.getChainedCredentials().put(id, credentials);

    MultiFactorRequestContextUtils.setMfaCredentials(context, mfa);

    final TicketGrantingTicket tgt = this.cas.createTicketGrantingTicket(mfa);
    WebUtils.putTicketGrantingTicketInScopes(context, tgt);
    final FlowSession session = context.getFlowExecutionContext().getActiveSession();
    logger.debug("Located active webflow session {}", session.getDefinition().getId());
    session.getParent().getScope().put("ticketGrantingTicketId", tgt.getId());
    return getSuccessEvent(context);

}
 
Example #2
Source File: TicketGrantingTicketCheckAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Determines whether the TGT in the flow request context is valid.
 *
 * @param requestContext Flow request context.
 *
 * @throws Exception in case ticket cannot be retrieved from the service layer
 * @return {@link #NOT_EXISTS}, {@link #INVALID}, or {@link #VALID}.
 */
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final String tgtId = WebUtils.getTicketGrantingTicketId(requestContext);
    if (!StringUtils.hasText(tgtId)) {
        return new Event(this, NOT_EXISTS);
    }

    String eventId = INVALID;
    try {
        final Ticket ticket = this.centralAuthenticationService.getTicket(tgtId, Ticket.class);
        if (ticket != null && !ticket.isExpired()) {
            eventId = VALID;
        }
    } catch (final TicketException e) {
        logger.trace("Could not retrieve ticket id {} from registry.", e);
    }
    return new Event(this,  eventId);
}
 
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: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example #5
Source File: GenerateServiceTicketActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceTicketFromCookie() throws Exception {
    MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    context.getFlowScope().put("ticketGrantingTicketId", this.ticketGrantingTicket);
    MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.setCookies(new Cookie[] {new Cookie("TGT",
            this.ticketGrantingTicket)});

    this.action.execute(context);

    assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
 
Example #6
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 #7
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example #8
Source File: TerminateSessionAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Terminates the CAS SSO session by destroying the TGT (if any) and removing cookies related to the SSO session.
 *
 * @param context Request context.
 *
 * @return "success"
 */
public Event terminate(final RequestContext context) {
    // in login's webflow : we can get the value from context as it has already been stored
    String tgtId = WebUtils.getTicketGrantingTicketId(context);
    // for logout, we need to get the cookie's value
    if (tgtId == null) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
    }
    if (tgtId != null) {
        WebUtils.putLogoutRequests(context, this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId));
    }
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    this.ticketGrantingTicketCookieGenerator.removeCookie(response);
    this.warnCookieGenerator.removeCookie(response);
    return this.eventFactorySupport.success(this);
}
 
Example #9
Source File: GenerateServiceTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyTicketGrantingTicketNoTgt() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    
    final MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("bleh");
    WebUtils.putTicketGrantingTicketInScopes(context, tgt);

    assertEquals("error", this.action.execute(context).getId());
}
 
Example #10
Source File: GenerateServiceTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyTicketGrantingTicketNotTgtButGateway() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    final MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.addParameter("gateway", "true");
    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("bleh");
    WebUtils.putTicketGrantingTicketInScopes(context, tgt);


    assertEquals("gateway", this.action.execute(context).getId());
}
 
Example #11
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySuccessfulAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("username", "test");
    request.addParameter("password", "test");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
}
 
Example #12
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySuccessfulAuthenticationWithNoServiceAndWarn()
    throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");

    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, response));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
    assertNotNull(WebUtils.getTicketGrantingTicketId(context));
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}
 
Example #13
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySuccessfulAuthenticationWithServiceAndWarn()
    throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");
    request.addParameter("service", "test");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request,  response));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}
 
Example #14
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRenewWithServiceAndSameCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");

    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test");
    request.addParameter("password", "test");

    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    context.getFlowScope().put("service", TestUtils.getService());

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("warn", this.action.submit(context, c, messageContext).getId());
}
 
Example #15
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();

    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));

    assertEquals("success", this.action.execute(this.context).getId());
    request.setCookies(response.getCookies());
    assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
 
Example #16
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySsoSessionCookieOnRenewAsParameter() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(CasProtocolConstants.PARAMETER_RENEW, "true");

    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.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(0, response.getCookies().length);
}
 
Example #17
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 #18
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 #19
Source File: SendTicketGrantingTicketAction.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {

    final MultiFactorCredentials mfa = MultiFactorRequestContextUtils.getMfaCredentials(context);

    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String ticketGrantingTicketValueFromCookie = (String) context.getFlowScope().get("ticketGrantingTicketId");

    if (ticketGrantingTicketId == null) {
        return success();
    }

    this.ticketGrantingTicketCookieGenerator.addCookie(WebUtils.getHttpServletRequest(context), WebUtils
            .getHttpServletResponse(context), ticketGrantingTicketId);

    if ((mfa == null || this.destroyPreviousSSOSession)
            && ticketGrantingTicketValueFromCookie != null
            && !ticketGrantingTicketId.equals(ticketGrantingTicketValueFromCookie)) {
        logger.debug("Destroying the previous SSO session mapped to [{}] because, this is not an MFA request,"
                + " or configuration dictated destroying the SSO session.", ticketGrantingTicketValueFromCookie);
        this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketValueFromCookie);
    }

    return success();
}
 
Example #20
Source File: SpnegoCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Sets the response header based on the retrieved tocken.
 *
 * @param context the context
 * @param credential the credential
 */
private void setResponseHeader(final RequestContext context,
        final Credential credential) {
    if (credential == null) {
        return;
    }

    final HttpServletResponse response = WebUtils
            .getHttpServletResponse(context);
    final SpnegoCredential spnegoCredentials = (SpnegoCredential) credential;
    final byte[] nextToken = spnegoCredentials.getNextToken();
    if (nextToken != null) {
        logger.debug("Obtained output token: {}", new String(nextToken, Charset.defaultCharset()));
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE, (this.ntlm
                ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE)
                + ' ' + CompressionUtils.encodeBase64(nextToken));
    } else {
        logger.debug("Unable to obtain the output token required.");
    }

    if (spnegoCredentials.getPrincipal() == null && send401OnAuthenticationFailure) {
        logger.debug("Setting HTTP Status to 401");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #21
Source File: SpnegoCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
private void setResponseHeader(final RequestContext context,
        final Credential credential) {
    if (credential == null) {
        return;
    }

    final HttpServletResponse response = WebUtils
            .getHttpServletResponse(context);
    final SpnegoCredential spnegoCredentials = (SpnegoCredential) credential;
    final byte[] nextToken = spnegoCredentials.getNextToken();
    if (nextToken != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Obtained output token: " + new String(nextToken));
        }
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE, (this.ntlm
                ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE)
                + " " + Base64.encode(nextToken));
    } else {
        logger.debug("Unable to obtain the output token required.");
    }

    if (spnegoCredentials.getPrincipal() == null && send401OnAuthenticationFailure) {
        logger.debug("Setting HTTP Status to 401");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example #22
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 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 Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("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.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #23
Source File: OpenIdSingleSignOnAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String userName = this.extractor
            .extractLocalUsernameFromUri(context.getRequestParameters()
                    .get("openid.identity"));
    final Service service = WebUtils.getService(context);

    context.getExternalContext().getSessionMap().put("openIdLocalId", userName);

    // clear the service because otherwise we can fake the username
    if (service instanceof OpenIdService && userName == null) {
        context.getFlowScope().remove("service");
    }

    if (ticketGrantingTicketId == null || userName == null) {
        return null;
    }

    return new OpenIdCredential(
            ticketGrantingTicketId, userName);
}
 
Example #24
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(new SimplePrincipal(
                principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example #25
Source File: GenerateServiceTicketAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final Service service = WebUtils.getService(context);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);

    try {
        final String serviceTicketId = this.centralAuthenticationService
            .grantServiceTicket(ticketGrantingTicket,
                service);
        WebUtils.putServiceTicketInRequestScope(context,
            serviceTicketId);
        return success();
    } catch (final TicketException e) {
        if (isGatewayPresent(context)) {
            return result("gateway");
        }
    }

    return error();
}
 
Example #26
Source File: TerminateWebSessionListener.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionEnded(final RequestContext context, final FlowSession session, final String outcome,
                         final AttributeMap output) {

    if ( session.isRoot() ) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        // get session but don't create it if it doesn't already exist
        final HttpSession webSession = request.getSession(false);

        if (webSession != null) {
            LOGGER.debug("Terminate web session {} in {} seconds", webSession.getId(), this.timeToDieInSeconds);
            // set the web session to die in timeToDieInSeconds
            webSession.setMaxInactiveInterval(this.timeToDieInSeconds);
        }
    }
}
 
Example #27
Source File: SendTicketGrantingTicketAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String ticketGrantingTicketValueFromCookie = (String) context.getFlowScope().get("ticketGrantingTicketId");

    if (ticketGrantingTicketId == null) {
        return success();
    }

    this.ticketGrantingTicketCookieGenerator.addCookie(WebUtils.getHttpServletRequest(context), WebUtils
        .getHttpServletResponse(context), ticketGrantingTicketId);

    if (ticketGrantingTicketValueFromCookie != null && !ticketGrantingTicketId.equals(ticketGrantingTicketValueFromCookie)) {
        this.centralAuthenticationService
            .destroyTicketGrantingTicket(ticketGrantingTicketValueFromCookie);
    }

    return success();
}
 
Example #28
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");

    final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
 
Example #29
Source File: AuthenticationViaFormAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private void putWarnCookieIfRequestParameterPresent(final RequestContext context) {
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    if (StringUtils.hasText(context.getExternalContext().getRequestParameterMap().get("warn"))) {
        this.warnCookieGenerator.addCookie(response, "true");
    } else {
        this.warnCookieGenerator.removeCookie(response);
    }
}
 
Example #30
Source File: InitiatingMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
protected final Event doAuthentication(final RequestContext context, final Credential credentials,
                                       final MessageContext messageContext, final String id) throws Exception {


    final String tgt = WebUtils.getTicketGrantingTicketId(context);
    if (!StringUtils.isBlank(tgt)) {
        logger.debug("Attempting to remove the pre-existing TGT from the context [{}]", tgt);
        this.cas.destroyTicketGrantingTicket(tgt);
        MultiFactorRequestContextUtils.setTicketGrantingTicketId(context, null);
    }

    final Event primaryAuthnEvent = this.wrapperAuthenticationAction.submit(context, credentials, messageContext);
    if (!success().getId().equals(primaryAuthnEvent.getId())) {
        logger.debug("Returning event id [{}]", primaryAuthnEvent);
        return primaryAuthnEvent;
    }

    MultiFactorRequestContextUtils.setTicketGrantingTicketId(context, WebUtils.getTicketGrantingTicketId(context));

    final List<MultiFactorAuthenticationRequestContext> mfaRequests =
            getMfaRequestOrNull(this.authenticationSupport.getAuthenticationFrom(WebUtils.getTicketGrantingTicketId(context)),
                    WebUtils.getService(context), context);

    if (mfaRequests != null) {
        MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context,
                addToMfaTransactionAndGetHighestRankedMfaRequest(mfaRequests, context));
        return doMultiFactorAuthentication(context, credentials, messageContext, id);
    }
    return primaryAuthnEvent;
}