org.springframework.binding.message.MessageContext Java Examples

The following examples show how to use org.springframework.binding.message.MessageContext. 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: 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 #2
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 #3
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 #4
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 #5
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    request.addParameter("username", "test");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c, messageContext).getId());
}
 
Example #6
Source File: PersonSearchAction.java    From openregistry with Apache License 2.0 6 votes vote down vote up
public void setConfirmationMessage(final ServiceExecutionResult<Person> serviceExecutionResult, final ReconciliationResult reconciliationResult, final MessageContext context) {
    //if reconciliation result is EXACT or MAYBE then only a role was added, not a new person.
    //a force add, would result in no reconciliationResult.

    if (reconciliationResult != null){
        if (reconciliationResult.getReconciliationType() == ReconciliationResult.ReconciliationType.EXACT ||
                reconciliationResult.getReconciliationType() == ReconciliationResult.ReconciliationType.MAYBE) {
            context.addMessage(new MessageBuilder().info().code("roleAdded").build());
            return;
        }
    }

    final Person person = serviceExecutionResult.getTargetObject();
    final Identifier netId = person.getPrimaryIdentifiersByType().get(this.preferredPersonIdentifierType);

    if (person.getCurrentActivationKey() != null) {
        final MessageResolver message = new MessageBuilder().info().code("personAddedFinalConfirm").arg(netId.getValue()).arg(person.getCurrentActivationKey().asString()).build();
        context.addMessage(message);
    } else {
        context.addMessage(new MessageBuilder().info().code("personAddedFinalConfirm").arg(netId.getValue()).arg("TempKey").build());
    }
}
 
Example #7
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 #8
Source File: AuthenticationViaFormActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyRenewWithServiceAndDifferentCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

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

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

    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
}
 
Example #9
Source File: BuyHandler.java    From tutorial with MIT License 6 votes vote down vote up
/**
 * action-state 中的 evaluate 执行的方法需要返回值;并且 action-state 中根据这个返回值来决定下一步去那里
 * @param shoppingCart
 * @param error
 * @return
 */
public String createOrder(ShoppingCart shoppingCart, Order order, MessageContext error) {
    logger.trace("createOrder shoppingCart:{}, order: {}, eror: {}", shoppingCart, order, error);

    String returnValue = "success";

    if (shoppingCart.getCartItems() == null || shoppingCart.getCartItems().size() == 0) {
        error.addMessage(new MessageBuilder(). //
                error() //
                .defaultText("购物车是空的") //
                .build());

        returnValue = "fail";
    }

    // 还应检查购物车内物品是否已经下架等

    //创建订单
    order.setId("O99999");
    order.setPayDate(new Date());

    return returnValue;
}
 
Example #10
Source File: PersonSearchAction.java    From openregistry with Apache License 2.0 6 votes vote down vote up
public void setConfirmationMessage(final ServiceExecutionResult<Person> serviceExecutionResult, final ReconciliationResult reconciliationResult, final MessageContext context) {
    //if reconciliation result is EXACT or MAYBE then only a role was added, not a new person.
    //a force add, would result in no reconciliationResult.

    if (reconciliationResult != null){
        if (reconciliationResult.getReconciliationType() == ReconciliationResult.ReconciliationType.EXACT ||
                reconciliationResult.getReconciliationType() == ReconciliationResult.ReconciliationType.MAYBE) {
            context.addMessage(new MessageBuilder().info().code("roleAdded").build());
            return;
        }
    }

    final Person person = serviceExecutionResult.getTargetObject();
    final Identifier netId = person.getPrimaryIdentifiersByType().get(this.preferredPersonIdentifierType);

    if (person.getCurrentActivationKey() != null) {
        final MessageResolver message = new MessageBuilder().info().code("personAddedFinalConfirm").arg(netId.getValue()).arg(person.getCurrentActivationKey().asString()).build();
        context.addMessage(message);
    } else {
        context.addMessage(new MessageBuilder().info().code("personAddedFinalConfirm").arg(netId.getValue()).arg("TempKey").build());
    }
}
 
Example #11
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 #12
Source File: AuthenticationExceptionHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void handleUnknownExceptionByDefefault() {
    final AuthenticationExceptionHandler handler = new AuthenticationExceptionHandler();
    final MessageContext ctx = mock(MessageContext.class);
    
    final Map<String, Class<? extends Exception>> map = new HashMap<String, Class<? extends Exception>>();
    map.put("unknown", GeneralSecurityException.class);
    final String id = handler.handle(new AuthenticationException(map), ctx);
    assertEquals(id, "UNKNOWN");
}
 
Example #13
Source File: User.java    From enhanced-pet-clinic with Apache License 2.0 5 votes vote down vote up
public void validateCreateUser(ValidationContext context) {
	MessageContext messages = context.getMessageContext();
	if (!StringUtils.equals(uiPassword, verifyPassword)) {
		messages.addMessage(new MessageBuilder().error().source("password").source("verifyPassword")
				.defaultText("Passwords must be the same.").build());
	}
}
 
Example #14
Source File: CartController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public Event shipOrder(ShipForm ship, MessageContext messageContext) {
	if (ship == null) {
		// Code here for Error Messages
		return new EventFactorySupport().error(this);
	}
	return new EventFactorySupport().success(this);
}
 
Example #15
Source File: CartController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public Event registerPayment(PaymentForm payment, MessageContext messageContext) {
	if (payment == null) {
		// Code here for Error Messages
		return new EventFactorySupport().error(this);
	}
	return new EventFactorySupport().success(this);
}
 
Example #16
Source File: CartController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public Event registerOrder(OrderForm order, MessageContext messageContext) {
	if (order == null) {
		// Code here for Error Messages
		return new EventFactorySupport().error(this);
	}
	return new EventFactorySupport().success(this);
}
 
Example #17
Source File: CartController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public Event checkUser(LoginForm login, MessageContext messageContext) {
	if (loginService.retrieveAccount(login.getUsername()) == null) {
		MessageBuilder errorMessageBuilder1 = new MessageBuilder().error();
		errorMessageBuilder1.source("username");
		errorMessageBuilder1.code("login.username.error");
		messageContext.addMessage(errorMessageBuilder1.build());
		
		MessageBuilder errorMessageBuilder2 = new MessageBuilder().error();
		errorMessageBuilder2.source("password");
		errorMessageBuilder2.code("login.password.error");
		messageContext.addMessage(errorMessageBuilder2.build());
		return new EventFactorySupport().error(this);
	}
	return new EventFactorySupport().success(this);
}
 
Example #18
Source File: AuthenticationViaFormAction.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * Add warning messages to message context if needed.
 *
 * @param tgtId the tgt id
 * @param messageContext the message context
 * @return true if warnings were found and added, false otherwise.
 * @since 4.1.0
 */
protected boolean addWarningMessagesToMessageContextIfNeeded(final TicketGrantingTicket tgtId, final MessageContext messageContext) {
    boolean foundAndAddedWarnings = false;
    for (final Map.Entry<String, HandlerResult> entry : tgtId.getAuthentication().getSuccesses().entrySet()) {
        for (final MessageDescriptor message : entry.getValue().getWarnings()) {
            addWarningToContext(messageContext, message);
            foundAndAddedWarnings = true;
        }
    }
    return foundAndAddedWarnings;

}
 
Example #19
Source File: AbstractPersonServiceAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public final boolean convertAndReturnStatus(final ServiceExecutionResult<?> serviceExecutionResult, final MessageContext messageContext, final String successMessageCode) {
    this.converter.convertValidationErrors(serviceExecutionResult.getValidationErrors(), messageContext);

    if (serviceExecutionResult.succeeded() && successMessageCode != null) {
        messageContext.addMessage(new MessageBuilder().info().code(successMessageCode).build());
    }
    return serviceExecutionResult.succeeded();
}
 
Example #20
Source File: RoleAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public boolean isRoleNewForPerson(SorPerson sorPerson, Type affiliationType, MessageContext context) {
	//check if person already has the role to be added.
	logger.info("IsRoleNewForPerson: code:"+ affiliationType);
	final Person person = getPersonService().findPersonById(sorPerson.getPersonId());
	if (person.pickOutRole(affiliationType) != null){
		context.addMessage(new MessageBuilder().error().code("roleAlreadyExists").build());
		return false;
	}
	return true;
}
 
Example #21
Source File: PersonSearchAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public ServiceExecutionResult addSorPerson(final ReconciliationCriteria reconciliationCriteria, final MessageContext context) {
    reconciliationCriteria.getSorPerson().setSourceSor(AbstractPersonServiceAction.STATIC_SOR_NAME);
    final ServiceExecutionResult<Person> result = getPersonService().forceAddPerson(reconciliationCriteria);
    getSpringErrorValidationErrorConverter().convertValidationErrors(result.getValidationErrors(), context);

    return result;
}
 
Example #22
Source File: AbstractPersonServiceAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public final boolean convertAndReturnStatus(final ServiceExecutionResult<?> serviceExecutionResult, final MessageContext messageContext, final String successMessageCode) {
    this.converter.convertValidationErrors(serviceExecutionResult.getValidationErrors(), messageContext);

    if (serviceExecutionResult.succeeded() && successMessageCode != null) {
        messageContext.addMessage(new MessageBuilder().info().code(successMessageCode).build());
    }
    return serviceExecutionResult.succeeded();
}
 
Example #23
Source File: RoleAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public boolean isRoleNewForPerson(SorPerson sorPerson, Type affiliationType, MessageContext context) {
    //check if person already has the role to be added.
    logger.info("IsRoleNewForPerson: code:"+ affiliationType.getDescription());
    final Person person = getPersonService().findPersonById(sorPerson.getPersonId());
    if (person.pickOutRole(affiliationType) != null){
        context.addMessage(new MessageBuilder().error().code("roleAlreadyExists").build());
        return false;
    }
    return true;
}
 
Example #24
Source File: PersonSearchAction.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public ServiceExecutionResult addSorPerson(final ReconciliationCriteria reconciliationCriteria, final MessageContext context) {
    reconciliationCriteria.getSorPerson().setSourceSor(AbstractPersonServiceAction.STATIC_SOR_NAME);
    final ServiceExecutionResult<Person> result = getPersonService().forceAddPerson(reconciliationCriteria);
    getSpringErrorValidationErrorConverter().convertValidationErrors(result.getValidationErrors(), context);

    return result;
}
 
Example #25
Source File: AbstractMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * In the event of an MFA request, authenticate the credentials by default, and place
 * the authentication context back into the flow.
 * <p>Coming from the 'doAuthentication' and checking if the principal mfa source has been ranked or not
 * Or if coming straight from initial transition. In either case, if there is no mfa service already in the flow scope
 * try to get the principal attribute sourced mfa request and re-rank the existing mfa tx, so the mfa service is
 * always available in the flow scope for downstream subflows.
 * <p>If we get to this method, the mfa transaction is guaranteed to be in the flow scope.
 *
 * @param context request context
 * @param credentials the requesting credentials
 * @param messageContext the message bundle manager
 * @param id the identifier of the credential, based on implementation provided in the flow setup.
 *
 * @return the resulting event
 *
 * @throws Exception the exception
 */
protected final Event doMultiFactorAuthentication(final RequestContext context, final Credential credentials,
                                                  final MessageContext messageContext, final String id) throws Exception {

    Assert.notNull(id);
    Assert.notNull(credentials);

    try {
        final Authentication auth = this.authenticationManager.authenticate(credentials);
        if (MultiFactorRequestContextUtils.getMultifactorWebApplicationService(context) == null) {
            final List<MultiFactorAuthenticationRequestContext> mfaRequest =
                    getMfaRequestOrNull(auth, WebUtils.getService(context), context);
            //No principal attribute sourced mfa method request. Just get the highest ranked mfa service from existing ones
            if (mfaRequest == null) {
                MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context,
                        getHighestRankedMfaRequestFromMfaTransaction(context));
            } else {
                final MultiFactorAuthenticationSupportingWebApplicationService highestService =
                        addToMfaTransactionAndGetHighestRankedMfaRequest(mfaRequest, context);
                MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context, highestService);
                MultiFactorRequestContextUtils.setRequiredAuthenticationMethod(context, highestService.getAuthenticationMethod());
            }
        }

        final Event result = multiFactorAuthenticationSuccessful(auth, context, credentials, messageContext, id);
        MultiFactorRequestContextUtils.setAuthentication(context, auth);
        return result;
    } catch (final AuthenticationException e) {
        populateErrorsInstance(e.getMessage(), messageContext);
        MultiFactorRequestContextUtils.setAuthenticationExceptionInFlowScope(context, e);
        logger.error(e.getMessage(), e);
    }
    return getErrorEvent(context);
}
 
Example #26
Source File: AbstractMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if is valid login ticket.
 *
 * @param context the context
 * @param messageContext the message context
 *
 * @return true, if is valid login ticket
 */
protected final boolean isValidLoginTicket(final RequestContext context, final MessageContext messageContext) {
    final String authoritativeLoginTicket = WebUtils.getLoginTicketFromFlowScope(context);
    final String providedLoginTicket = WebUtils.getLoginTicketFromRequest(context);
    if (!authoritativeLoginTicket.equals(providedLoginTicket)) {
        logger.warn("Invalid login ticket {}", providedLoginTicket);
        final String code = "INVALID_TICKET";
        messageContext.addMessage(new MessageBuilder().error().code(code).arg(providedLoginTicket).defaultText(code).build());
        return false;
    }
    return true;
}
 
Example #27
Source File: AbstractMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Populate errors instance.
 *
 * @param code the error code
 * @param messageContext the message context
 */
protected final void populateErrorsInstance(final String code, final MessageContext messageContext) {
    try {
        messageContext.addMessage(new MessageBuilder().error().code(code).defaultText(code).build());
    }  catch (final Exception fe) {
        logger.error(fe.getMessage(), fe);
    }
}
 
Example #28
Source File: AbstractMultiFactorAuthenticationViaFormAction.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
protected final Event doExecute(final RequestContext ctx) throws Exception {
    final Credential credentials = WebUtils.getCredential(ctx);
    final MessageContext messageContext = ctx.getMessageContext();


    if (credentials != null) {
        final String id = credentials.getId();
        return submit(ctx, credentials, messageContext, id);
    }
    logger.warn("Credentials could not be determined, or no username was associated with the request.");
    return getErrorEvent(ctx);
}
 
Example #29
Source File: MultifactorLoginViewPrincipalAttributeGreeter.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
@Override
public String getPersonToGreet(final Principal p, final MessageContext messageContext) {

    String personId = p.getId();
    final Object attrValue = p.getAttributes().get(this.greetingAttributeName);

    if (attrValue == null) {
        LOGGER.warn("No attribute value could be found for [{}]", this.greetingAttributeName);
        return p.getId();
    }

    String greetingPersonId = attrValue.toString();
    if (attrValue instanceof Collection) {
        final Collection col =((Collection) attrValue);
        if (!col.isEmpty()) {
            greetingPersonId = col.iterator().next().toString();
            LOGGER.warn("Found multiple attribute values [{}] for [{}] to greet. Picked [{}]",
                    attrValue, this.greetingAttributeName,
                    greetingPersonId);
        }
    }

    if (!StringUtils.isBlank(greetingPersonId)) {
        personId = greetingPersonId;
    }

    final MessageResolver resolver = new MessageBuilder().source(CODE).info().code(CODE).arg(personId).build();
    messageContext.addMessage(resolver);

    final Message[] messages = messageContext.getMessagesBySource(CODE);
    if (messages == null || messages.length == 0) {
        LOGGER.warn("The greeting message for principal [{}] could not be resolved by the "
                + "code [{}] in any of the configured message resource bundles. Falling back to principal id [{}]",
                p, CODE, p.getId());
        return p.getId();
    }
    return messages[0].getText();
}
 
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;
}