List of usage examples for org.springframework.security.core Authentication getAuthorities
Collection<? extends GrantedAuthority> getAuthorities();
AuthenticationManager
to indicate the authorities that the principal has been granted. From source file:de.terrestris.shogun.security.ShogunAuthProcessingFilter.java
/** * On successful authentication by an Authentication Manager of Spring Security * we intercept with this method and change the respone to include the ROLES of * the logged in user./*from ww w .j a v a2 s . co m*/ * This way we can react on the ROLES and redirect accordingly within the requesting login form (here login.js) * * @see WebContent/client/login.js */ @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { SecurityContextHolder.getContext().setAuthentication(authResult); SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler(); this.setAuthenticationSuccessHandler(srh); srh.setRedirectStrategy(new RedirectStrategy() { @Override public void sendRedirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException { //do nothing, no redirect } }); super.successfulAuthentication(request, response, authResult); // build a comma separated string of the ROLES String authorityText = StringUtils.join(authResult.getAuthorities(), ","); // write the servlet return object HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response); Writer out = responseWrapper.getWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(out); jsonGenerator.writeStartObject(); jsonGenerator.writeBooleanField("success", true); jsonGenerator.writeStringField("name", authResult.getName()); jsonGenerator.writeStringField("role", authorityText); jsonGenerator.writeEndObject(); jsonGenerator.close(); }
From source file:org.geonode.security.GeoNodeDataAccessManager.java
/** * @see org.geoserver.security.DataAccessManager#canAccess(org.springframework.security.Authentication, * org.geoserver.catalog.ResourceInfo, org.geoserver.security.AccessMode) *//* www . ja v a 2 s. c om*/ public boolean canAccess(Authentication user, ResourceInfo resource, AccessMode mode) { if (!authenticationEnabled) { return true; } /** * A null user should only come from an internal GeoServer process (such as a GWC seed * thread). * <p> * Care must be taken in setting up the security filter chain so that no request can get * here with a null user. At least an anonymous authentication token must be set. * </p> */ if (user == null) { //throw new NullPointerException("user is null"); return true; } if (LOG.isLoggable(Level.FINE)) { LOG.fine("GeoNodeDataAccessManager::canAccess: Checking permissions for " + user.getName() + " with authorities " + user.getAuthorities() + " accessing " + resource); } if (user.getAuthorities().contains(GeoServerRole.ADMIN_ROLE)) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("GeoNodeDataAccessManager::canAccess: user " + user.getName() + " is admin"); } return true; } return securityClientProvider.getSecurityClient().authorize(user, resource, mode); }
From source file:com.epam.cme.storefront.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"); }/* ww w . j a va 2s . co m*/ 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.traffitruck.web.HtmlController.java
private void updateModelWithRoles(Map<String, Object> model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); boolean isLoadsOwner = false; boolean isTruckOwner = false; for (GrantedAuthority auth : authentication.getAuthorities()) { if (Role.LOAD_OWNER.toString().equals(auth.getAuthority())) { isLoadsOwner = true;//w w w .j a va 2s . co m } if (Role.TRUCK_OWNER.toString().equals(auth.getAuthority())) { isTruckOwner = true; } } model.put("isLoadsOwner", isLoadsOwner); model.put("isTruckOwner", isTruckOwner); }
From source file:org.energyos.espi.datacustodian.web.filter.ResourceValidationFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { System.out.println("ResourceValidationFilter: start of pooFilter"); Boolean invalid = true;/*from ww w . j ava2s . c o m*/ Boolean hasBearer = false; Boolean hasValidOAuthAccessToken = false; Boolean resourceRequest = false; Authorization authorizationFromToken = null; Subscription subscription = null; String resourceUri = null; String authorizationUri = null; Set<String> roles = null; // Get the URI for later tests HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String uri = request.getRequestURI(); String service = request.getMethod(); // See if any authentication has happened Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); } else { System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } System.out.printf("ResourceValidationFilter: role = %s, HttpRequest Method: %s, uri: %s\n", roles, service, uri); // Only process resource API request if ((uri.indexOf("/espi/1_1/resource/") != -1)) { resourceRequest = true; } // ///////////////////////////////////////////////////////////////////// // find the access token if present and validate we have a good one // ///////////////////////////////////////////////////////////////////// String token = request.getHeader("authorization"); if (token != null) { if (token.contains("Bearer")) { // has Authorization header with Bearer type hasBearer = true; token = token.replace("Bearer ", ""); // ensure length is >12 characters (48 bits in hex at least) if (token.length() >= 12) { // lookup the authorization -- we must have one to // correspond to an access token try { authorizationFromToken = authorizationService.findByAccessToken(token); hasValidOAuthAccessToken = true; resourceUri = authorizationFromToken.getResourceURI(); authorizationUri = authorizationFromToken.getAuthorizationURI(); subscription = authorizationFromToken.getSubscription(); } catch (Exception e) { System.out.printf("ResourceValidationFilter: doFilter - No Authorization Found - %s\n", e.toString()); throw new AccessDeniedException(String.format("No Authorization Found")); } } } } // ///////////////////////////////////////////////////////////////////// // If this is a resource request ensure it has a Bearer token // ///////////////////////////////////////////////////////////////////// if ((hasBearer == false) & !(resourceRequest == true)) { // no Bearer token and it passed the OAuth filter - so it must be // good2go not RESTAPI request // make sure the role is not an ANONYMOUS request for /manage ... if (!((roles.contains("ROLE_ANONYMOUS")) & (uri.indexOf("/management") != -1))) { invalid = false; } } // ///////////////////////////////////////////////////////////////////// // if this is RESTful request, process based on ROLE // ///////////////////////////////////////////////////////////////////// else if (hasValidOAuthAccessToken == true) { // if it has a valid access token // then we know it is REST request // Dispatch on authentication type // first, escape out of this if it is the special // "manage?command=foo" form int i = uri.indexOf("/management"); if (i > 0) { if (roles.contains("ROLE_DC_ADMIN")) { invalid = false; } else { System.out.printf("ResourceValidationFilter: doFilter - not valid for this token %s\n", uri); throw new AccessDeniedException(String.format("Access Not Authorized")); } } else { // lets check the uri i = uri.indexOf("espi/1_1/resource/"); if (i > 0) { // lets shorten it by stripping off up to resource uri = uri.substring(uri.indexOf("/resource/")); } else { // cant be a resource System.out.printf("ResourceValidationFilter: doFilter - Uri not well formed %s\n", uri); throw new AccessDeniedException(String.format("Access Not Authorized")); } } // strip off uri up to /resource/ since that is how we go here resourceUri = resourceUri.substring(resourceUri.indexOf("/resource/")); authorizationUri = authorizationUri.substring(authorizationUri.indexOf("/resource/")); // ///////////////////////////////////////////////////////////////////// // ROLE_USER // // GET /resource/LocalTimeParameters // GET /resource/LocalTimeParameters/{localTimeParametersId} // GET /resource/ReadingType // GET /resource/ReadingType/{readingTypeId} // GET /resource/Batch/Subscription/{subscriptionId} // GET // /resource/Batch/Subscription/{subscriptionId}/UsagePoint/{usagePointId} // GET /resource/Subscription/{subscriptionId}/UsagePoint // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId} // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerQualitySummary // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerQualitySummary/{electricPowerQualitySummaryId} // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerUsageSumary // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerUsageSumary/{electricPowerUsageSummaryId} // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId} // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId}/IntervalBlock // GET // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId}/IntervalBlock/{intervalBlockId} // // ///////////////////////////////////////////////////////////////////// if (invalid && roles.contains("ROLE_USER")) { // break uri into tokens String[] tokens = uri.split("/"); // only GET for this ROLE permitted if (!service.equals("GET")) { System.out.printf( "ResourceValidationFilter: doFilter - ROLE_USER attempted a RESTful %s Request -- Only GET Request are allowed\n", service); throw new AccessDeniedException(String.format("Access Not Authorized")); } // look for the root forms of LocalTimeParameters and // ReadingType if (invalid && ((uri.contains("resource/LocalTimeParameters")) || (uri.contains("resource/ReadingType")))) { invalid = false; } // must be either /resource/Batch/Subscription/{subscriptionId} if (invalid && uri.contains("/resource/Batch/Subscription")) { if (uri.startsWith(resourceUri)) { invalid = false; } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } // or /resource/Batch/Subscription/{subscriptionId}/** if (invalid && uri.contains("/resource/Subscription")) { if (authorizationFromToken.getSubscription().getId() .compareTo(Long.parseLong(tokens[3], 10)) == 0) { invalid = false; } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } } else if (invalid && roles.contains("ROLE_DC_ADMIN")) { // ///////////////////////////////////////////////////////////////////// // ROLE_DC_ADMIN // Access to all services and APIs // ///////////////////////////////////////////////////////////////////// // invalid = false; } else if (invalid && roles.contains("ROLE_TP_ADMIN")) { // ///////////////////////////////////////////////////////////////////// // ROLE_TP_ADMIN // // GET /resource/Authorization // GET /resource/Authorization/{authorizationId} // PUT /resource/Authorization/{authorizationId} // DELETE /resource/Authorization/{authorizationId} // GET /resource/Batch/Bulk/{bulkId} // GET /resource/ReadServiceStatus // GETALL // sftp://services.greenbuttondata.org/DataCustodian/espi/1_1/resource/Batch/Bulk/{bulkId} // ///////////////////////////////////////////////////////////////////// // the Bulk Authorizations if (invalid && uri.contains("/resource/Batch/Bulk")) { invalid = false; } // Authorizations GET/PUT/DELETE on individual, GET on // collection if (invalid && (uri.contains("/resource/Authorization"))) { // this is retrieving the authorization related to the token // the TP has access to AuthorizationIds he is tp for // which is authorization looked by access token, or, // any authorization that points to same // applicationInformationId if (service.equals("GET") || service.equals("PUT") || service.equals("DELETE")) { if (authorizationUri.equals(uri)) { invalid = false; } else { // get authorizationID if present String[] tokens = uri.split("/"); Long authorizationId = -1l; if (tokens.length > 3) { authorizationId = Long.parseLong(tokens[3], 10); } // check if its a collection if (authorizationId != -1l) { // it is specific ID, see if it authorization // for this third party Authorization requestedAuthorization = authorizationService .findById(authorizationId); if ((requestedAuthorization.getApplicationInformation().getId()) .equals(authorizationFromToken.getApplicationInformation().getId())) { invalid = false; } else { // not authorized for this resource System.out .printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } else { // this is collection request and controller // will limit to valid authorizations if (service.equals("GET")) { invalid = false; } else { // not authorized for this resource System.out .printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } } } } if (invalid && uri.contains("/resource/ReadServiceStatus")) { if (service.equals("GET")) { invalid = false; } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } // sftp // TODO: } else if (invalid && roles.contains("ROLE_UL_ADMIN")) { // ///////////////////////////////////////////////////////////////////// // ROLE_UL_ADMIN // // GET // /resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint // POST // /resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint // GET /resource/Authorization/{authorizationId} // // ///////////////////////////////////////////////////////////////////// // he can get his own AuthorizationUri // check if it is this authorization request if (uri.contains("/resource/Authorization")) { if (authorizationUri.equals(uri)) { invalid = false; } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } if (invalid && uri.contains("/resource/Batch/RetailCustomer")) { invalid = false; } if (invalid && uri.contains("/resource/ReadServiceStatus")) { if (service.equals("GET")) { invalid = false; } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } } else if (invalid && roles.contains("ROLE_TP_REGISTRATION")) { // ///////////////////////////////////////////////////////////////////// // ROLE_TP_REGISTRATION // // GET // /resource/ApplicationInformation/{applicationInformationId} // PUT // /resource/ApplicationInformation/{applicationInformationId} // DELETE // /resource/ApplicationInformation/{applicationInformationId} // ///////////////////////////////////////////////////////////////////// if (service.equals("GET") || service.equals("PUT") || service.equals("DELETE")) { if (uri.contains("/resource/ApplicationInformation")) { String[] tokens = uri.split("/"); if (tokens.length > 3) { Long applicationInformationIdFromUri = Long.parseLong(tokens[3], 10); Long applicationInformationId = authorizationFromToken.getApplicationInformation() .getId(); // only gets access to his if (applicationInformationIdFromUri.equals(applicationInformationId)) { invalid = false; } } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } else { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } } } System.out.printf("ResourceValidationFilter: normal exit doFilter: invalid=%s\n", invalid); if (invalid) { // not authorized for this resource System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n"); throw new AccessDeniedException(String.format("Access Not Authorized")); } // TODO -- Verify contents of query parameters are properly formatted chain.doFilter(req, res); }
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = { "/menu", "/" }) ModelAndView menu() {//from w w w.ja va 2 s . co m Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Map<String, Object> model = new HashMap<>(); boolean isLoadsOwner = false; boolean isTruckOwner = false; for (GrantedAuthority auth : authentication.getAuthorities()) { if (Role.LOAD_OWNER.toString().equals(auth.getAuthority())) { isLoadsOwner = true; } if (Role.TRUCK_OWNER.toString().equals(auth.getAuthority())) { isTruckOwner = true; } } String username = authentication.getName(); if (isLoadsOwner && !isTruckOwner) { return new ModelAndView("redirect:/myLoads", model); } List<Truck> trucks = dao.getTrucksForUserAndRegistration(username, TruckRegistrationStatus.APPROVED); if (trucks != null && trucks.size() > 0) { return new ModelAndView("redirect:/findTrucksForLoad", model); } else { return new ModelAndView("redirect:/myTrucks", model); } }
From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java
/** * Return a new authentication with the the real use name. *//*from w w w . j a v a 2 s . co m*/ private Authentication newAuthentication(final String userName, final String userpassword, final Authentication authentication, final HttpResponse httpResponse) { final List<String> cookies = Arrays.stream(httpResponse.getAllHeaders()) .filter(header -> "set-cookie".equals(header.getName())).map(Header::getValue) .collect(Collectors.toList()); // Get the optional real user name if provided final String realUserName = Optional.ofNullable(httpResponse.getFirstHeader("X-Real-User")) .map(Header::getValue).orElse(userName); if (realUserName.equals(userName)) { log.info("Success authentication of {}[{}]", realUserName, userpassword.length(), realUserName); } else { log.info("Success authentication of {}[{}] using login {}", realUserName, userpassword.length(), userName); } // Return the authentication token return new CookieUsernamePasswordAuthenticationToken(realUserName, authentication.getCredentials(), authentication.getAuthorities(), cookies); }
From source file:com.acc.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) @RequireHardLogIn/*from w w w . ja v a2 s . com*/ 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_PROFILE_PAGE; if (!bindingResult.hasErrors() && !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", 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.epam.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) @RequireHardLogIn/*from www.j a v a 2 s . c o m*/ 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"); } 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.ctc.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) @RequireHardLogIn/*from w w w. ja va 2 s .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_CURRENT_PASSWORD_INVALID); returnAction = setErrorMessagesAndCMSPage(model, UPDATE_EMAIL_CMS_PAGE); } } return returnAction; }