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.epam.trade.storefront.controllers.pages.AccountPageController.java

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

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }//from  w w  w .  java2  s. c o m

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // 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) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:com.bac.accountserviceapp.AccountServiceApp.java

@Override
public AccountServiceAuthentication login(AccountServiceAuthentication authentication) {
    //// w  w  w  .j a  v  a2  s .  co m
    //  Validate authentication content
    //
    Objects.requireNonNull(authentication, noAuthenticationMsg);
    Objects.requireNonNull(authentication.getApplicationName(), noApplicationName);
    Objects.requireNonNull(authentication.getAccountKey(), incompleteLogin);
    Objects.requireNonNull(authentication.getAccountPassword(), incompleteLogin);
    //
    //  Clear out any pre-set values
    //
    authentication.setAccountResource(null);
    authentication.setAccountRole(null);
    authentication.setAuthenticationOutcome(null);
    //
    //  
    //
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            authentication.getAccountKey(), authentication.getAccountPassword());
    Authentication loginToken = login(authenticationToken);
    authentication.setAccountPassword(null);
    //
    //  If the token is not authenticated then return
    //
    AccountServiceAuthenticationOutcome loginOutcome = (AccountServiceAuthenticationOutcome) loginToken
            .getDetails();
    if (loginOutcome != AUTHENTICATED) {
        authentication.setAuthenticationOutcome(loginOutcome);
        return authentication;
    }
    //
    //  Temporarily set outcome to no role and then verify that
    //
    authentication.setAuthenticationOutcome(NO_ROLE);
    final String expectedApplicationName = authentication.getApplicationName();
    if (loginToken.getAuthorities() != null) {

        for (GrantedAuthority authority : loginToken.getAuthorities()) {

            String authorityString = authority.getAuthority();
            matcher = pattern.matcher(authorityString);
            if (!matcher.matches() || matcher.groupCount() != AUTHORITY_PATTERN_COUNT) {
                continue;
            }
            String authorityApplicationName = matcher.group(AUTHORITY_PATTERN_APPLICATION_ITEM);
            String authorityRole = matcher.group(AUTHORITY_PATTERN_ROLE_ITEM);

            if (!expectedApplicationName.equals(authorityApplicationName)) {
                continue;
            }
            //
            //  Look up the AccountRole and add it to the outgoing authentication
            //
            AccountServiceRole accountRole;
            try {
                accountRole = AccountServiceRole.valueOf(authorityRole);
            } catch (IllegalArgumentException e) {
                logger.warn("Unable to find a valid Account Servie Role for '{}'", authorityRole);
                accountRole = null;
            }
            authentication.setAccountRole(accountRole);
            authentication.setAuthenticationOutcome(AUTHENTICATED);
            break;
        }
    }
    //
    //  If NO_ROLE is overidden then populate the outgoing authentication with the Account resource
    //
    if (authentication.getAuthenticationOutcome() == AUTHENTICATED) {

        Account account = strategy.getAccountForApplication(expectedApplicationName,
                authentication.getAccountKey());
        if (account == null) {
            authentication.setAuthenticationOutcome(NO_RESOURCE);
        } else {
            authentication.setAccountResource(account.getResourceName());
        }
    }
    //
    //  Complete so return
    //
    return authentication;
}

From source file:org.duracloud.account.security.vote.UserAccessDecisionVoterTest.java

private Authentication createAuthentication(Long userId, String username, Set<Role> roles) {
    Authentication auth = EasyMock.createMock("Authentication", Authentication.class);
    DuracloudUser user = new DuracloudUser();
    user.setId(userId);/* www.ja  va  2  s .  co  m*/
    user.setUsername(username);
    user.setPassword("password");
    user.setFirstName("firstName");
    user.setLastName("lastName");
    user.setEmail("email");
    user.setSecurityQuestion("question");
    user.setSecurityAnswer("answer");

    EasyMock.expect(auth.getPrincipal()).andReturn(user);

    Collection<GrantedAuthority> userRoles = new HashSet<GrantedAuthority>();
    for (Role role : roles) {
        userRoles.add(new SimpleGrantedAuthority(role.name()));
    }
    EasyMock.expect(auth.getAuthorities()).andReturn((Collection) userRoles);

    return auth;
}

From source file:com.traffitruck.web.HtmlController.java

@RequestMapping(value = "/resetPassword", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ModelAndView resetPassword(@RequestParam("password") String password,
        @RequestParam("confirm_password") String confirm_password) {
    if (password == null || !password.equals(confirm_password)) {
        throw new RuntimeException("Failed resetting the password");
    }/*from  w w w.ja va 2 s  . c  o m*/
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    LoadsUser user = dao.getUser(username);
    user.setPassword(password);
    dao.storeUser(user);

    String resetPasswordId = null;
    for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (grantedAuthority.getAuthority().startsWith("resetPassword-"))
            resetPasswordId = grantedAuthority.getAuthority().substring("resetPassword-".length());
        dao.deleteResetPassword(resetPasswordId, username);
    }
    return new ModelAndView("redirect:" + user.getRoles().get(0).getLandingUrl());
}

From source file:de.hska.ld.oidc.controller.OIDCController.java

private void enrichAuthoritiesWithStoredAuthorities(HttpServletRequest request, String sub, String issuer,
        OIDCUserinfoDto oidcUserinfoDto, String oidcToken, User user, Authentication auth) {
    DefaultUserInfo userInfo = new DefaultUserInfo();
    userInfo.setSub(oidcUserinfoDto.getSub());
    userInfo.setEmail(oidcUserinfoDto.getEmail());
    userInfo.setName(oidcUserinfoDto.getName());
    userInfo.setEmailVerified(true);/*from w  w  w .jav  a2  s.co  m*/
    userInfo.setFamilyName(oidcUserinfoDto.getFamilyName());
    userInfo.setGivenName(oidcUserinfoDto.getGivenName());
    userInfo.setPreferredUsername(oidcUserinfoDto.getPreferredUsername());
    userInfo.setUpdatedTime(oidcUserinfoDto.getUpdatedTime());
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1];
    authorities.forEach(authority -> {
        if (authority instanceof SubjectIssuerGrantedAuthority) {
            // extract the oidc authority information
            oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority;
        }
    });

    // create new authorities that includes the authorities stored in the database
    // as well as the oidc authority
    ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
    user.getRoleList().forEach(role -> {
        newAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    });
    if (oidcAuthority[0] == null) {
        newAuthorities.add(new SubjectIssuerGrantedAuthority(sub, issuer));
    } else {
        newAuthorities.add(oidcAuthority[0]);
    }
    OIDCAuthenticationToken token = new OIDCAuthenticationToken(sub, issuer, userInfo, newAuthorities, null,
            oidcToken, null);
    token.setDetails(new WebAuthenticationDetails(request));
    SecurityContextHolder.getContext().setAuthentication(token);
}

From source file:cec.easyshop.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn// w  ww. ja  v a 2s. c o m
public String updateEmail(final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);
    String returnAction = REDIRECT_TO_UPDATE_EMAIL_PAGE;

    if (!bindingResult.hasErrors() && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
        returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);

            // 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) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE);
        }
    }

    return returnAction;
}

From source file:com.nagarro.core.v2.controller.UsersController.java

private boolean containsRole(final Authentication auth, final String role) {
    for (final GrantedAuthority ga : auth.getAuthorities()) {
        if (ga.getAuthority().equals(role)) {
            return true;
        }/*w w  w  . j  a  v a 2s . c o m*/
    }
    return false;
}

From source file:de.whs.poodle.security.SpringSecurityConfig.java

@Bean
public SwitchUserFilter switchUserFilter() {
    SwitchUserFilter filter = new SwitchUserFilter();
    filter.setTargetUrl("/");
    filter.setSwitchUserUrl("/switchUser");
    filter.setExitUserUrl("/exitUser");
    filter.setSwitchFailureUrl("/?switchUserFailed=1");

    /*//  w  ww  .  j  a v  a  2s  .  c  o  m
     * Called when a user is switched and returns the UserDetails.
     */
    filter.setUserDetailsService(username -> {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        /* If no username is specified, we interpret this as "student mode"
        * (see <form> in instructor/navItems.html). */
        if (username.isEmpty()) {
            // get the logged in student
            Instructor instructor = instructorRepo.getByUsername(auth.getName());

            log.debug("{} switched to student mode", instructor.getUsername());

            // create the fake student and switch
            Student fakeStudent = studentRepo.createFakeStudent(instructor.getId());

            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_STUDENT"));
            authorities.add(new SimpleGrantedAuthority("ROLE_FAKE_STUDENT"));
            return new User(fakeStudent.getUsername(), "password", authorities);
        } else { // switch to specified user (admins only)
            boolean isAdmin = auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
            if (!isAdmin)
                throw new ForbiddenException();

            log.debug("User {} switching to {}", auth.getName(), username);
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();

            /*
             *   username is the user that we switched to. We have no information
             *   on whether he is a student or an instructor. Since he must be
             *   in the database, let's just check there.
             */
            if (studentRepo.studentExists(username))
                authorities.add(new SimpleGrantedAuthority("ROLE_STUDENT"));
            else if (instructorRepo.exists(username))
                authorities.add(new SimpleGrantedAuthority("ROLE_INSTRUCTOR"));
            else
                throw new UsernameNotFoundException("user doesn't exist.");

            return new User(username, "password", authorities);
        }
    });

    return filter;
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
@RequireHardLogIn//from  ww  w . ja  v  a2  s .co  m
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");
    }

    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingEmail(model);
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "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) {
            bindingResult.rejectValue("email", "profile.email.unique");
            returnAction = errorUpdatingEmail(model);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("email", "profile.currentPassword.invalid");
            returnAction = errorUpdatingEmail(model);
        }
    }

    return returnAction;
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(produces = "text/html")
public String list(@ModelAttribute("command") PosteCandidatureSearchCriteria searchCriteria,
        BindingResult bindResult, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size,
        @RequestParam(value = "sortFieldName", required = false) String sortFieldName,
        @RequestParam(value = "sortOrder", required = false) String sortOrder,
        @RequestParam(value = "zip", required = false, defaultValue = "off") Boolean zip,
        HttpServletResponse response, HttpServletRequest request, Model uiModel)
        throws IOException, SQLException {

    // uiModel.addAttribute("users", User.findUserEntries(firstResult,
    // sizeNo));//from w ww .j a va2 s  .c o m

    List<PosteCandidature> postecandidatures = null;

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    String emailAddress = auth.getName();
    User user = User.findUsersByEmailAddress(emailAddress, null, null).getSingleResult();

    boolean isAdmin = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN"));
    boolean isManager = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MANAGER"));
    boolean isSuperManager = isManager
            || auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_SUPER_MANAGER"));
    boolean isMembre = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"));
    boolean isCandidat = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT"));

    if (sortFieldName == null)
        sortFieldName = "o.poste.numEmploi,o.candidat.nom";
    if ("nom".equals(sortFieldName))
        sortFieldName = "candidat.nom";
    if ("email".equals(sortFieldName))
        sortFieldName = "candidat.emailAddress";
    if ("numCandidat".equals(sortFieldName))
        sortFieldName = "candidat.numCandidat";
    if ("managerReviewState".equals(sortFieldName))
        sortFieldName = "managerReview.reviewStatus";

    // pagination only for admin / manager users ...
    if (isAdmin || isManager) {

        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            long nbResultsTotal = PosteCandidature.countPosteCandidatures();
            uiModel.addAttribute("nbResultsTotal", nbResultsTotal);
            float nrOfPages = (float) nbResultsTotal / sizeNo;
            uiModel.addAttribute("maxPages",
                    (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
            postecandidatures = PosteCandidature.findPosteCandidatureEntries(firstResult, sizeNo, sortFieldName,
                    sortOrder);
        } else {
            postecandidatures = PosteCandidature.findAllPosteCandidatures(sortFieldName, sortOrder);
            uiModel.addAttribute("nbResultsTotal", postecandidatures.size());
        }

        uiModel.addAttribute("posteapourvoirs", PosteAPourvoir.findAllPosteAPourvoirNumEplois());
        uiModel.addAttribute("candidats", User.findAllCandidatsIds());
        uiModel.addAttribute("reviewStatusList", Arrays.asList(ReviewStatusTypes.values()));

        String mailAuditionnableEntete = AppliConfig.getCacheTexteEnteteMailCandidatAuditionnable();
        String mailAuditionnablePiedPage = AppliConfig.getCacheTextePiedpageMailCandidatAuditionnable();
        uiModel.addAttribute("mailAuditionnableEntete", mailAuditionnableEntete);
        uiModel.addAttribute("mailAuditionnablePiedPage", mailAuditionnablePiedPage);
    }

    else if (isCandidat) {

        if (!AppliConfig.getCacheCandidatCanSignup()) {

            postecandidatures = new ArrayList<PosteCandidature>(
                    PosteCandidature.findPosteCandidaturesByCandidat(user, null, null).getResultList());

            // restrictions si phase auditionnable
            Date currentTime = new Date();
            if (currentTime.compareTo(AppliConfig.getCacheDateEndCandidat()) > 0
                    && currentTime.compareTo(AppliConfig.getCacheDateEndCandidatActif()) > 0) {
                for (PosteCandidature postecandidature : PosteCandidature
                        .findPosteCandidaturesByCandidat(user, null, null).getResultList()) {
                    if (!postecandidature.getAuditionnable() || postecandidature.getPoste()
                            .getDateEndCandidatAuditionnable() != null
                            && currentTime.compareTo(
                                    postecandidature.getPoste().getDateEndCandidatAuditionnable()) > 0) {
                        postecandidatures.remove(postecandidature);
                    }
                }
            }

        } else {
            postecandidatures = new ArrayList<PosteCandidature>(PosteCandidature
                    .findPosteCandidaturesByCandidatAndByDateEndCandidatGreaterThanAndNoAuditionnableOrByDateEndCandidatAuditionnableGreaterThanAndAuditionnable(
                            user, new Date())
                    .getResultList());
        }

    }

    else if (isMembre) {
        Set<PosteAPourvoir> membresPostes = new HashSet<PosteAPourvoir>(user.getPostes());
        List<PosteAPourvoir> postes = searchCriteria.getPostes();
        if (postes != null && !postes.isEmpty()) {
            membresPostes.retainAll(postes);
            uiModel.addAttribute("finderview", true);
            uiModel.addAttribute("command", searchCriteria);
        }
        if (membresPostes.isEmpty()) {
            membresPostes = new HashSet<PosteAPourvoir>(user.getPostes());
        }
        postecandidatures = PosteCandidature.findPosteCandidaturesRecevableByPostes(membresPostes,
                searchCriteria.getAuditionnable(), sortFieldName, sortOrder).getResultList();
        if (zip) {
            String contentType = "application/zip";
            Calendar cal = Calendar.getInstance();
            Date currentTime = cal.getTime();
            SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String currentTimeFmt = dateFmt.format(currentTime);
            String baseName = "demat-" + currentTimeFmt + ".zip";
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + baseName + "\"");
            zipService.writeZip(postecandidatures, response.getOutputStream());
            logService.logActionFile(LogService.DOWNLOAD_ACTION, postecandidatures, request, currentTime);
            return null;
        }

        for (PosteCandidature pc : postecandidatures) {
            if (pc.getReporters() != null && pc.getReporters().contains(user)) {
                pc.setReporterTag(true);
            }
        }

        uiModel.addAttribute("nbResultsTotal", postecandidatures.size());
        List<PosteAPourvoir> membresPostes2Display = new ArrayList<PosteAPourvoir>(user.getPostes());

        Collections.sort(membresPostes2Display, new Comparator<PosteAPourvoir>() {
            @Override
            public int compare(PosteAPourvoir p1, PosteAPourvoir p2) {
                return p1.getNumEmploi().compareTo(p2.getNumEmploi());
            }
        });

        uiModel.addAttribute("membresPostes", membresPostes2Display);
    }

    uiModel.addAttribute("postecandidatures", postecandidatures);

    uiModel.addAttribute("zip", new Boolean(false));

    uiModel.addAttribute("texteMembreAideCandidatures", AppliConfig.getCacheTexteMembreAideCandidatures());
    uiModel.addAttribute("texteCandidatAideCandidatures", AppliConfig.getCacheTexteCandidatAideCandidatures());

    uiModel.addAttribute("legendColors", ManagerReviewLegendColor.getLegendColors());

    addDateTimeFormatPatterns(uiModel);
    return "postecandidatures/list";
}