Example usage for org.springframework.security.core Authentication getAuthorities

List of usage examples for org.springframework.security.core Authentication getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getAuthorities.

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

From source file:com.castlemock.war.config.SecurityInterceptor.java

/**
 * The method will check if the logged in user is still valid.
 * @param request The incoming request.//from   w ww  .  j av  a2  s  .  com
 * @param response The outgoing response
 * @param handler The handler contains information about the method and controller that will process the incoming request
 * @return Returns true if the logged in users information is still valid. Returns false if the user is not valid
 * @throws IOException Upon unable to send a redirect as a response
 * @throws ServletException Upon unable to logout the user
 */
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws IOException, ServletException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return true;
    }

    final String loggedInUsername = authentication.getName();
    if (ANONYMOUS_USER.equals(loggedInUsername)) {
        return true;
    }

    final ReadUserByUsernameInput readUserByUsernameInput = new ReadUserByUsernameInput(loggedInUsername);
    final ReadUserByUsernameOutput readUserByUsernameOutput = serviceProcessor.process(readUserByUsernameInput);
    final UserDto loggedInUser = readUserByUsernameOutput.getUser();
    if (loggedInUser == null) {
        LOGGER.info("The following logged in user is not valid anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else if (!Status.ACTIVE.equals(loggedInUser.getStatus())) {
        LOGGER.info("The following logged in user is not active anymore: " + loggedInUsername);
        request.logout();
        response.sendRedirect(request.getContextPath());
        return false;
    } else {
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            Role role = Role.valueOf(grantedAuthority.getAuthority());
            if (!loggedInUser.getRole().equals(role)) {
                LOGGER.info("The following logged in user's authorities has been updated: " + loggedInUsername);
                final UserDetails userDetails = userDetailSecurityService.loadUserByUsername(loggedInUsername);
                final Authentication newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
                        userDetails.getPassword(), userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(newAuthentication);
            }
        }
        return true;
    }
}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
public String updateEmail(@Valid final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }//from w w w. jav a 2  s .com

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
        returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail().toLowerCase(), updateEmailForm.getPassword());

            //temporary solution to set oryginal UID - with new version of commerceservices it will not be necessary
            final CustomerData customerData = customerFacade.getCurrentCustomer();
            customerData.setDisplayUid(updateEmailForm.getEmail());
            customerFacade.updateProfile(customerData);
            //end of temporary solution

            redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.confirmationUpdated"));

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            redirectAttributes.addFlashAttribute(GlobalMessages.INFO_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.emailNotChanged"));
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("email", "profile.currentPassword.invalid");
            GlobalMessages.addErrorMessage(model, "form.global.error");
            storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
            returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
        }
    }

    return returnAction;
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_InvalidPassword() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_InvalidPassword");

    try {// w w w . j a  v  a  2s  . c  o m
        createUserAccount();
        final String invalidUserPassword = UUID.randomUUID().toString();
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                invalidUserPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, BAD_CREDENTIALS);
        //
        //  Get the Authentication Principal: It should represent the user name
        //
        authenticatePrincipal(resultAuthentication, userEmail.getClass());
        assertEquals(userEmail, resultAuthentication.getPrincipal());
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_InactiveUser() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_InactiveUser");

    try {//w  w w .  j a va 2s. c o  m
        createUserAccount();
        //
        //  Set the User to Inactive
        //
        user.setEnabled(false);
        resultUser = accessor.updateUser(user);
        assertThat(resultUser, is(notNullValue()));
        assertEquals(userId, resultUser.getId());
        assertEquals(false, resultUser.isEnabled());
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, DISABLED_PRINCIPAL);
        //
        //  Get the Authentication Principal: It should represent the user name
        //
        authenticatePrincipal(resultAuthentication, userEmail.getClass());
        assertEquals(userEmail, resultAuthentication.getPrincipal());
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_InvalidUserName() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_InvalidUserName");

    try {//  www. j av a 2s .c  o m
        createUserAccount();
        final String invalidUserEmail = UUID.randomUUID().toString();
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                invalidUserEmail, userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, UNKNOWN_PRINCIPAL);
        //
        //  Get the Authentication Principal: It should represent the invalid user name
        //
        authenticatePrincipal(resultAuthentication, invalidUserEmail.getClass());
        assertEquals(invalidUserEmail, resultAuthentication.getPrincipal());
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_NoUserAccount() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_NoUserAccount");

    try {// w  w  w .j ava 2 s  .co m
        createUserAccount();
        //
        //  Delete the user account. This will not affect the clean up process
        //
        accountUser = accessor.getAccountUser(accountUser);
        accessor.deleteAccountUser(accountUser);
        resultAccountUser = accessor.getAccountUser(accountUser);
        assertThat(resultAccountUser, is(nullValue()));
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, AUTHENTICATED);
        //
        //  Get the Authentication Principal: It should represent the UserDetails
        //
        authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class);
        authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail);
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_InactiveAccountUser() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_InactiveAccountUser");

    try {/* ww  w  . j ava  2s . co  m*/
        createUserAccount();
        //
        //  Set the Account User to Inactive
        //
        accountUser.setEnabled(false);
        resultAccountUser = accessor.updateAccountUser(accountUser);
        assertThat(resultAccountUser, is(notNullValue()));
        assertEquals(false, resultAccountUser.isEnabled());
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, AUTHENTICATED);
        //
        //  Get the Authentication Principal: It should represent the UserDetails
        //
        authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class);
        authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail);
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication_InactiveApplication() throws NoSuchAlgorithmException {

    logger.info("testAuthentication_InactiveApplication");

    try {//w  w w .  j ava2 s .c  o  m
        createUserAccount();
        //
        //  Set the Application to Inactive
        //
        application.setEnabled(false);
        resultApplication = accessor.updateApplication(application);
        assertThat(resultApplication, is(notNullValue()));
        assertEquals(applicationId, resultApplication.getId());
        assertEquals(false, resultApplication.isEnabled());
        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, AUTHENTICATED);
        //
        //  Get the Authentication Principal: It should represent the UserDetails
        //
        authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class);
        authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail);
        //
        //  Ensure that no Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 0;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppSpringAuthenticationTest.java

@Test
public void testAuthentication() throws NoSuchAlgorithmException {

    logger.info("testAuthentication");

    try {//w  w  w .  jav  a  2s  .  c  o  m
        createUserAccount();
        //
        //  Apply any user account manipulation here
        //

        //
        //  Authenticate
        //
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEmail,
                userPassword);
        Authentication resultAuthentication = instance.login(authentication);
        assertNotNull(resultAuthentication);
        //
        //  Check the outcome
        //
        authenticateOutcome(resultAuthentication, AUTHENTICATED);
        //
        //  Get the Authentication Principal: It should represent the UserDetails
        //
        authenticatePrincipal(resultAuthentication, AccountServiceUserDetails.class);
        authenticateUserDetails((UserDetails) resultAuthentication.getPrincipal(), userEmail);
        //
        //  Ensure that the Authority has been granted
        //
        Collection<? extends GrantedAuthority> authorities = resultAuthentication.getAuthorities();
        assertNotNull(authorities);
        int expAuthoritySize = 1;
        int resultAuthoritySize = authorities.size();
        assertEquals(expAuthoritySize, resultAuthoritySize);
        final String expAuthority = applicationName + AUTHORITY_SEPARATOR + accessLevelRole.name();
        List<String> authoritiesList = getAuthorityList(authorities);
        assertNotNull(authoritiesList);
        assertTrue(authoritiesList.contains(expAuthority));

    } catch (InvalidKeySpecException ex) {
        logger.error("Password encryption error");
    } finally {
        // Clean up
        logger.info("testAuthentication: Delete");
        deleteUserAccount();
    }
}