@Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (response != null) { response.setHeader("X-Frame-Options", "DENY"); } if (request != null && modelAndView != null) { User user = userService.getUserFromSecurityContext(); if (user == null) { HttpSession session = request.getSession(); if (session != null) { SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT"); if (context != null) { if (context.getAuthentication() != null && context.getAuthentication().getPrincipal() != null && context.getAuthentication().getPrincipal() instanceof User) { user = userService.get(((User) context.getAuthentication().getPrincipal()).getId()); } } } } modelAndView.getModel().put("user", user); } }
@ModelAttribute @RequestMapping(method = RequestMethod.GET) protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception { // If not an administrator, make sure user is not trying to add or edit another user if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) { if (isAdd(request) || request.getParameter("id") != null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); log.warn( "User '" + request.getRemoteUser() + "' is trying to edit user with id '" + request.getParameter("id") + "'"); throw new AccessDeniedException("You do not have permission to modify other users."); } } if (!isFormSubmission(request)) { String userId = request.getParameter("id"); // if user logged in with remember me, display a warning that they can't change passwords log.debug("checking for remember me login..."); AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx.getAuthentication() != null) { Authentication auth = ctx.getAuthentication(); if (resolver.isRememberMe(auth)) { request.getSession().setAttribute("cookieLogin", "true"); // add warning message saveMessage(request, getText("userProfile.cookieLogin", request.getLocale())); } } User user; if (userId == null && !isAdd(request)) { user = getUserManager().getUserByUsername(request.getRemoteUser()); } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) { user = getUserManager().getUser(userId); } else { user = new User(); user.addRole(new Role(Constants.USER_ROLE)); } user.setConfirmPassword(user.getPassword()); return user; } else { // populate user object from database, so all fields don't need to be hidden fields in form return getUserManager().getUser(request.getParameter("id")); } }
/** * This method is designed to catch when user's login and record their name * * @param event the event to process * @see * javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeAdded(HttpSessionBindingEvent event) { if (event.getName().equals(EVENT_KEY) && !isAnonymous()) { SecurityContext securityContext = (SecurityContext) event.getValue(); if (securityContext.getAuthentication().getPrincipal() instanceof User) { User user = (User) securityContext.getAuthentication().getPrincipal(); addUsername(user); } } }
public static Authentication getCurrentAuthentication() { final SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext == null) { return null; } return securityContext.getAuthentication(); }
/** Get the login of the current user. */ public static String getCurrentLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); UserDetails springSecurityUser = (UserDetails) securityContext.getAuthentication().getPrincipal(); return springSecurityUser.getUsername(); }
/** * API to save a new UtilityAttribute Usage : /UtilityAttribute/create * * @param * @return name of jsp file to which control is to be returned */ @RequestMapping(value = "/utilityattribute/create/{uid}/{slno}", method = RequestMethod.POST) protected String createUtilityAttribute( @ModelAttribute("utilityarrtibute") UtilityAttributes utlyattribute, @PathVariable("uid") int utilityid, @PathVariable("slno") int slno) { int stat = 0; try { logger.info(" in utility create POST. utility= " + utlyattribute.getUtilityid()); int primarykey = mastersservice.insertUtilityAttr(utlyattribute); if (primarykey != -1) { stat = 1; } } catch (Exception e) { logger.info("Exception in create UtilityAttribute " + e.getMessage()); } // Redirect control to list page via main page String saveoper = "/API/utilityattribute/create/" + utilityid + "/-1?savestat=" + stat; SecurityContext sec = SecurityContextHolder.getContext(); AbstractAuthenticationToken auth = (AbstractAuthenticationToken) sec.getAuthentication(); @SuppressWarnings("unchecked") Map<String, Object> info = (Map<String, Object>) auth.getDetails(); info.put("saveoper", saveoper); auth.setDetails(info); return "redirect:/start.htm"; }
/** * API to update a UtilityAttribute Usage : /UtilityAttribute/update/{utilityid}/{slno} * * @param ID of attribute * @return name of jsp file to which control is to be returned */ @RequestMapping( value = "/utilityattribute/update/{utilityid}/{slno}", method = RequestMethod.POST) protected String updateUtilityAttribute( @PathVariable("utilityid") int utilityid, @PathVariable("slno") int slno, @ModelAttribute("utilityattribute") UtilityAttributes utilityattr) { logger.info( "*** in utilityattr update id=** " + slno + " :utilityattr=" + utilityattr.getUtilityid()); int stat = 0; try { utilityattr.setUtilityid(utilityid); utilityattr.setN_slno(slno); if (mastersservice.updateUtilityAttr(utilityattr)) { stat = 1; } } catch (Exception e) { logger.info("Exception in update utilityattr " + e.getMessage()); } // Redirect to list page via main page String saveoper = "/API/utilityattribute/create/" + utilityid + "/-1?savestat=" + stat; SecurityContext sec = SecurityContextHolder.getContext(); AbstractAuthenticationToken auth = (AbstractAuthenticationToken) sec.getAuthentication(); @SuppressWarnings("unchecked") Map<String, Object> info = (Map<String, Object>) auth.getDetails(); info.put("saveoper", saveoper); auth.setDetails(info); return "redirect:/start.htm"; }
public static UserAccount getPrincipal() { UserAccount result; SecurityContext context; Authentication authentication; Object principal; // If the asserts in this method fail, then you're // likely to have your Tomcat's working directory // corrupt. Please, clear your browser's cache, stop // Tomcat, update your Maven's project configuration, // clean your project, clean Tomcat's working directory, // republish your project, and start it over. context = SecurityContextHolder.getContext(); Assert.notNull(context); authentication = context.getAuthentication(); Assert.notNull(authentication); principal = authentication.getPrincipal(); Assert.isTrue(principal instanceof UserAccount); result = (UserAccount) principal; Assert.notNull(result); Assert.isTrue(result.getId() != 0); return result; }
private static EditorUserAuthentication getEditorUserAuthentication(HttpSession session) { SecurityContext secContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT"); EditorUserAuthentication authentication = null; if (secContext != null) authentication = (EditorUserAuthentication) secContext.getAuthentication(); return authentication; }
/** * Return the current user, or throws an exception, if the user is not authenticated yet. * * @return the current user */ public static CustomUserDetails getCurrentUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails) { return (CustomUserDetails) authentication.getPrincipal(); } throw new IllegalStateException("User not found!"); }
@Test(expected = BadCredentialsException.class) public void updateUser_throwsUnAuthorized() { when(userRepository.save(userA)).thenReturn(userA); when(securityContext.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(userB); communityServiceImpl.updateUser(userA); }
public User getCurrentUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); UserDetails springSecurityUser = (UserDetails) securityContext.getAuthentication().getPrincipal(); return userRepository.findUserByLogin(springSecurityUser.getUsername()); }
private Authentication getAuthentication() { if (authentication != null) { return authentication; } SecurityContext context = SecurityContextHolder.getContext(); return context.getAuthentication(); }
private boolean isAnonymous() { AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx != null) { Authentication auth = ctx.getAuthentication(); return resolver.isAnonymous(auth); } return true; }
/** * If the current user has a specific authority (security role). * * <p>The name of this method comes from the isUserInRole() method in the Servlet API */ public static boolean isUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority)); } return false; }
public static User getUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); MyUser myUser = (MyUser) authentication.getPrincipal(); User user = new User(); user.setId(myUser.getId()); user.setName(myUser.getName()); user.setUsername(myUser.getUsername()); return user; }
@Test(expected = ResourceAccessException.class) public void loadUserByUsername_throwsResourceAccessException() { when(userRepository.findOne(USER_A_NAME)).thenReturn(null); when(securityContext.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(null); communityServiceImpl.loadUserByUsername(USER_A_NAME); verify(securityContext, times(1)).getAuthentication(); verify(authentication, times(1)).getPrincipal(); }
/** * When user's logout, remove their name from the hashMap * * @param event the session binding event * @see * javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeRemoved(HttpSessionBindingEvent event) { if (event.getName().equals(EVENT_KEY) && !isAnonymous()) { SecurityContext securityContext = (SecurityContext) event.getValue(); Authentication auth = securityContext.getAuthentication(); if (auth != null && (auth.getPrincipal() instanceof User)) { User user = (User) auth.getPrincipal(); removeUsername(user); } } }
/* * (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain) */ @Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { try { final SecurityContext context = SecurityContextHolder.getContext(); String uid = null; if (context != null) { final Authentication authentication = context.getAuthentication(); if (authentication != null) { uid = context.getAuthentication().getName(); } } MDC.put(identifiert, uid == null ? NOT_KNOWN : uid); chain.doFilter(request, response); } finally { MDC.remove(identifiert); } }
/** * Return the current user, or throws an exception, if the user is not authenticated yet. * * @return the current user */ public static User getCurrentUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { if (authentication.getPrincipal() instanceof User) { return (User) authentication.getPrincipal(); } } throw new IllegalStateException("User not found!"); }
@Test public void loadUserByUsername_usesSecurityContext() { when(userRepository.findOne(USER_A_NAME)).thenReturn(null); when(securityContext.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(userA); UserDetails result = communityServiceImpl.loadUserByUsername(USER_A_NAME); verify(securityContext, times(1)).getAuthentication(); verify(authentication, times(1)).getPrincipal(); assertEquals(USER_A_NAME, result.getUsername()); }
@Test public void updateUser_setsAttributes() { when(userRepository.save(userA)).thenReturn(userA); when(passwordEncoder.encode(USER_A_PASSWORD)).thenReturn(USER_A_PASSWORD_ENCODED); when(securityContext.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(userA); User user = communityServiceImpl.updateUser(userA); assertEquals(USER_A_PASSWORD_ENCODED, user.getPassword()); verify(passwordEncoder, times(1)).encode(USER_A_PASSWORD); }
private Long getUserId() { Long userId = null; SecurityContext context = SecurityContextHolder.getContext(); if (context.getAuthentication() != null) { AppUser appUser = this.context.authenticatedUser(); userId = appUser.getId(); } else { userId = new Long(0); } return userId; }
/** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */ public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities = securityContext.getAuthentication().getAuthorities(); if (authorities != null) { for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)) { return false; } } } return true; }
@Test public void updateUser_usesDAO_001() { when(userRepository.save(userA)).thenReturn(userA); when(securityContext.getAuthentication()).thenReturn(authentication); when(authentication.getPrincipal()).thenReturn(userA); User user = communityServiceImpl.updateUser(userA); assertEquals(userA, user); verify(userRepository, times(1)).save(userA); verify(securityContext, times(1)).getAuthentication(); verify(authentication, times(1)).getPrincipal(); }
private void init() { SecurityContext context = SecurityContextHolder.getContext(); if (context instanceof SecurityContext) { Authentication authentication = context.getAuthentication(); if (authentication instanceof Authentication) { if (!authentication.getPrincipal().equals("anonymousUser")) { this.setMatriculaUser(((User) authentication.getPrincipal()).getUsername()); logger.info("Login: " + this.getMatriculaUser()); } } } }
@Override public void newRevision(Object revisionEntity) { logger.debug("Adding new revision to the database."); SecurityContext securityContext = SecurityContextHolder.getContext(); String currentUser = "******"; String currentIPAddress = getServerIPAddress(); if (securityContext.getAuthentication() != null) { logger.debug("Authentication information exists. Retrieving required information."); currentUser = ((User) securityContext.getAuthentication().getPrincipal()).getUsername(); WebAuthenticationDetails details = (WebAuthenticationDetails) securityContext.getAuthentication().getDetails(); currentIPAddress = details.getRemoteAddress(); } Revision revision = ((Revision) revisionEntity); revision.setIpAddress(currentIPAddress); revision.setRevisionDate(Calendar.getInstance().getTime()); revision.setUserName(currentUser); }
public static MyUser getMyUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); try { return (MyUser) authentication.getPrincipal(); } catch (Exception e) { MyUser myUser = new MyUser(); Role role = new Role(); role.setBasicType("all"); myUser.setRole(role); return myUser; } }
/** Get the login of the current user. */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }
@ModelAttribute("user") public User populateUser() { SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { return null; } Authentication auth = context.getAuthentication(); if (auth == null) { return null; } Object user = auth.getDetails(); return (user != null && user instanceof User) ? (User) user : null; }