Java Code Examples for org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#getContextIdentifier()

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext#getContextIdentifier() . 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: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostAuthenticationHandlers() throws Exception {

    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class);
    HttpServletResponse response = PowerMockito.mock(HttpServletResponse.class);
    AuthenticationContext context = prepareContextForPostAuthnTests();
    authenticationRequestHandler.handle(request, response, context);
    assertNull(context.getParameter(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED));
    String pastrCookie = context.getParameter(FrameworkConstants.PASTR_COOKIE).toString();
    cookies[0] = new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(),
            pastrCookie);
    when(request.getCookies()).thenReturn(cookies);
    when(FrameworkUtils.getCookie(any(HttpServletRequest.class), anyString())).thenReturn
            (cookies[0]);
    authenticationRequestHandler.handle(request, response, context);
    assertTrue(Boolean.parseBoolean(context.getProperty(
            FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED).toString()));
}
 
Example 2
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = PostAuthenticationFailedException.class)
public void testPostAuthenticationHandlerFailures() throws Exception {

    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class);
    HttpServletResponse response = PowerMockito.mock(HttpServletResponse.class);
    AuthenticationContext context = prepareContextForPostAuthnTests();
    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(new DefaultStepBasedSequenceHandler());
    authenticationRequestHandler.handle(request, response, context);
    assertNull(context.getParameter(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED));
    String pastrCookie = context.getParameter(FrameworkConstants.PASTR_COOKIE).toString();
    cookies[0] = new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(), pastrCookie);
    when(request.getCookies()).thenReturn(cookies);
    when(FrameworkUtils.getCookie(any(HttpServletRequest.class), anyString())).thenReturn
            (new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(),
                    "someGibberishValue"));
    authenticationRequestHandler.handle(request, response, context);
    assertTrue(Boolean.parseBoolean(context.getProperty(
            FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED).toString()));
}
 
Example 3
Source File: SAMLSSOAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void sendPostRequest(HttpServletRequest request, HttpServletResponse response,
                             boolean isLogout, boolean isPassive,
                             String loginPage, AuthenticationContext context) throws SAMLSSOException {

    SAML2SSOManager saml2SSOManager = getSAML2SSOManagerInstance();
    saml2SSOManager.init(context.getTenantDomain(), context.getAuthenticatorProperties(),
            context.getExternalIdP().getIdentityProvider());

    if (!(saml2SSOManager instanceof DefaultSAML2SSOManager)) {
        throw new SAMLSSOException("HTTP-POST is not supported");
    }

    String encodedRequest = ((DefaultSAML2SSOManager) saml2SSOManager).buildPostRequest(
            request, isLogout, isPassive, loginPage, context);
    String relayState = context.getContextIdentifier();

    Map<String, String> reqParamMap = getAdditionalRequestParams(request, context);
    String postPageInputs = buildPostPageInputs(encodedRequest, relayState, reqParamMap);
    printPostPage(response, loginPage, postPageInputs);
}
 
Example 4
Source File: PostAuthenticationMgtService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void validatePASTRCookie(AuthenticationContext context, HttpServletRequest request)
        throws PostAuthenticationFailedException {

    Object pstrCookieObj = context.getParameter(FrameworkConstants.PASTR_COOKIE);
    if (pstrCookieObj != null) {
        String storedPastrCookieValue = (String) pstrCookieObj;
        Cookie pastrCookie = FrameworkUtils
                .getCookie(request, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()));
        if (pastrCookie != null && StringUtils.equals(storedPastrCookieValue, pastrCookie.getValue())) {
            if (log.isDebugEnabled()) {
                log.debug("pastr cookie validated successfully for sequence : " + context.getContextIdentifier());
            }
            return;
        } else {
            throw new PostAuthenticationFailedException(
                    "Invalid Request: Your authentication flow is ended or " + "invalid. Please initiate again.",
                    "Post authentication sequence tracking" + " cookie not found in request with context id : "
                            + context.getContextIdentifier());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(
                    "No stored pastr cookie found in authentication context for : " + context.getContextIdentifier()
                            + " . Hence returning without validating");
        }
    }
}
 
Example 5
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
  * Returns the redirection URL with the appended SAML2
  * Request message
  *
  * @param request SAML 2 request
  * @return redirectionUrl
  */
 @Override
 public String buildRequest(HttpServletRequest request, boolean isLogout, boolean isPassive,
                            String loginPage, AuthenticationContext context)
         throws SAMLSSOException {

     doBootstrap();
     String contextIdentifier = context.getContextIdentifier();
     RequestAbstractType requestMessage;

     if (request.getParameter(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ) == null) {
         String queryParam = context.getQueryParams();
         if (queryParam != null) {
             String[] params = queryParam.split("&");
             for (String param : params) {
                 String[] values = param.split("=");
                 if (values.length == 2 && SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ.equals(values[0])) {
                         request.setAttribute(SSOConstants.HTTP_POST_PARAM_SAML2_AUTH_REQ, values[1]);
                         break;
                     }
             }
         }
     }

     if (!isLogout) {
         requestMessage = buildAuthnRequest(request, isPassive, loginPage, context);
     } else {
         String username = (String) request.getSession().getAttribute(SSOConstants.LOGOUT_USERNAME);
         String sessionIndex = (String) request.getSession().getAttribute(SSOConstants.LOGOUT_SESSION_INDEX);
         String nameQualifier = (String) request.getSession().getAttribute(SSOConstants.NAME_QUALIFIER);
         String spNameQualifier = (String) request.getSession().getAttribute(SSOConstants.SP_NAME_QUALIFIER);

         requestMessage = buildLogoutRequest(username, sessionIndex, loginPage, nameQualifier, spNameQualifier);
     }
     String idpUrl = null;
     boolean isSignAuth2SAMLUsingSuperTenant = false;

     String encodedRequestMessage = encodeRequestMessage(requestMessage);
     StringBuilder httpQueryString = new StringBuilder("SAMLRequest=" + encodedRequestMessage);

     try {
         httpQueryString.append("&RelayState=" + URLEncoder.encode(contextIdentifier, "UTF-8").trim());
     } catch (UnsupportedEncodingException e) {
         throw new SAMLSSOException("Error occurred while url encoding RelayState", e);
     }

     if (SSOUtils.isAuthnRequestSigned(properties)) {
String signatureAlgoProp = properties
                 .get(IdentityApplicationConstants.Authenticator.SAML2SSO.SIGNATURE_ALGORITHM);
         if (StringUtils.isEmpty(signatureAlgoProp)) {
             signatureAlgoProp = IdentityApplicationConstants.XML.SignatureAlgorithm.RSA_SHA1;
         }
         String signatureAlgo = IdentityApplicationManagementUtil.getXMLSignatureAlgorithms()
                 .get(signatureAlgoProp);

         Map<String, String> parameterMap = FileBasedConfigurationBuilder.getInstance()
                 .getAuthenticatorBean(SSOConstants.AUTHENTICATOR_NAME).getParameterMap();
         if (parameterMap.size() > 0) {
             isSignAuth2SAMLUsingSuperTenant = Boolean.parseBoolean(parameterMap.
                     get(SIGN_AUTH2_SAML_USING_SUPER_TENANT));
         }
         if (isSignAuth2SAMLUsingSuperTenant) {
	SSOUtils.addSignatureToHTTPQueryString(httpQueryString, signatureAlgo,
                 new X509CredentialImpl(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, null));
         } else {
             SSOUtils.addSignatureToHTTPQueryString(httpQueryString, signatureAlgo,
                 new X509CredentialImpl(context.getTenantDomain(), null));
         }
     }	
     if (loginPage.indexOf("?") > -1) {
         idpUrl = loginPage.concat("&").concat(httpQueryString.toString());
     } else {
         idpUrl = loginPage.concat("?").concat(httpQueryString.toString());
     }
     return idpUrl;
 }