@RequestMapping( value = {"/", "/welcome**"}, method = RequestMethod.GET) public ModelAndView defaultPage() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); ModelAndView model = new ModelAndView(); if (!(auth instanceof AnonymousAuthenticationToken)) { UserDetails userDetail = (UserDetails) auth.getPrincipal(); model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername())); model.addObject( "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername())); model.setViewName("homeLogged"); } else { model.setViewName("home"); } NextBeer nextestBeer = nextBeerDAO.getNextBeer(); Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 23); today.set(Calendar.MINUTE, 59); if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) { model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay()); } model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers()); return model; }
@Test public void testLoadUserByUsername() { UserDetails expectedUserDetails = new User( "EXISTING_USER", "PASSWORD", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); UserDetails userDetails = userDetailsServiceWrapper.loadUserByUsername("EXISTING_USER"); assertEquals(expectedUserDetails.getPassword(), userDetails.getPassword()); assertEquals(expectedUserDetails.getUsername(), userDetails.getUsername()); assertEquals(expectedUserDetails.isAccountNonExpired(), userDetails.isAccountNonExpired()); assertEquals(expectedUserDetails.isAccountNonLocked(), userDetails.isAccountNonLocked()); assertEquals( expectedUserDetails.isCredentialsNonExpired(), expectedUserDetails.isCredentialsNonExpired()); assertEquals(expectedUserDetails.isEnabled(), userDetails.isEnabled()); assertTrue( HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( expectedUserDetails.getAuthorities(), userDetails.getAuthorities())); try { userDetails = userDetailsServiceWrapper.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); fail("testLoadUserByUsername() - UsernameNotFoundException did not bubble up!"); } catch (UsernameNotFoundException e) { } }
public void removeUserFromCache(UserDetails user) { if (logger.isDebugEnabled()) { logger.debug("Cache remove: " + user.getUsername()); } this.removeUserFromCache(user.getUsername()); }
/** * This method will do authentication for the user. return true if successful else return false. * * @param user * @return */ protected final boolean doLogin(UserDetails user) { if (user != null && doValidate(user)) { user = userGroupService.getUserByUsername(user.getUsername()); MyFormProperties.getInstance().setUser(user); Authentication request = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()); Authentication result = authenticationManager.authenticate(request); SecurityContextHolder.getContext().setAuthentication(result); return true; } return false; }
protected UserDetails createUserDetails( String username, UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities) { String returnUsername = userFromUserQuery.getUsername(); if (!isUsernameBasedPrimaryKey()) { returnUsername = username; } System.out.println( "HERE2>>>LOGGING IN...**********username: "******" userFromUserQuery.getPassword(): " + userFromUserQuery.getPassword() + " (CustomUser)userFromUserQuery).getKtn(): " + ((CustomUser) userFromUserQuery).getKtn().toString()); return new CustomUser( ((CustomUser) userFromUserQuery).getKtn(), returnUsername, userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), true, true, true, combinedAuthorities); }
@RequestMapping(value = "account/current", method = RequestMethod.GET) @ResponseStatus(value = HttpStatus.OK) @ResponseBody public Account accounts(UserDetails userDetails) { LOG.info(userDetails.toString()); return userRepository.findByEmail(userDetails.getUsername()); }
// @Override public List<Capture> getAllCaptures() { UserDetails userDetails = JarvisContextHolder.getContext().getUserDetails(); if (userDetails == null) { ResponseBuilderImpl builder = new ResponseBuilderImpl(); builder.status(Response.Status.UNAUTHORIZED); Response response = builder.build(); throw new WebApplicationException(response); } List<Capture> result = Lists.newArrayList(); for (final Annotation annotation : annotatorDao.getAnnotationsByUsername(userDetails.getUsername())) { Capture capture = new Capture(); capture.setAnnotator_schema_version(annotation.getAnnotatorSchemaVersion()); capture.setCreated(new Date(annotation.getCreated())); capture.setId(annotation.getId()); capture.setOfflineId(annotation.getOfflineId()); capture.setQuote(annotation.getQuote()); capture.setRanges(annotation.getRanges()); capture.setResearchSession(annotation.getResearchSession()); capture.setText(annotation.getText()); capture.setUri(annotation.getUri()); result.add(capture); } return result; }
@RequestMapping( value = {"/welcome"}, method = RequestMethod.GET) public ModelAndView defaultPage(Locale locale, HttpServletRequest request) { logger.info("Welcome to welcome Page. The client locale is {}.", locale); Contact contact = new Contact(); // check if user is login Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth instanceof UsernamePasswordAuthenticationToken) { UserDetails userDetail = (UserDetails) auth.getPrincipal(); String username = userDetail.getUsername(); logger.info("username taken from SecurityContext " + username); User user = userService.getUserByUsername(username); if (user != null) { Utils.populateContact(user, contact); } logger.info("Contact object populated with username " + contact.getUsername()); } ModelAndView mav = new ModelAndView("userMain"); mav.addObject("countriesMap", Utils.getCountriesMap()); mav.addObject("command", contact); mav.addObject( DashboardSessionManagmentFilter.SESSION_AUTHENTICATION_PARAM_NAME, filter.generateSecurityToken(request, encoder)); return mav; }
@Override public void updateUser(UserDetails user) { inMemManager.updateUser(user); User userToUpdate = userRepository.findFirstByUsername(user.getUsername()); userToUpdate.setPassword(user.getPassword()); for (GrantedAuthority authority : user.getAuthorities()) { StringTokenizer stringTokenizer = new StringTokenizer(authority.getAuthority(), ":"); String rl = stringTokenizer.nextToken(); String pj = stringTokenizer.nextToken(); boolean found = false; for (Role role : userToUpdate.getRoles()) { if (role.getProject().equals(pj)) { role.setRole(Role.RoleEnum.valueOf(rl)); found = true; } } if (!found) { Role role = new Role(); role.setRole(Role.RoleEnum.valueOf(rl)); role.setProject(pj); userToUpdate.getRoles().add(role); } } userRepository.save(userToUpdate); }
/** Get the login of the current user. */ public static String getCurrentLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); UserDetails springSecurityUser = (UserDetails) securityContext.getAuthentication().getPrincipal(); return springSecurityUser.getUsername(); }
@RequestMapping( value = {"/pay_success_url"}, method = RequestMethod.POST) public void successURL( @RequestParam(value = "OutSum", required = true) String outSum, @RequestParam(value = "InvId", required = true) String invId, @RequestParam(value = "SignatureValue", required = true) String signatureValue, @RequestParam(value = "Culture", required = false) String culture) throws Exception { double _money = Double.parseDouble(outSum); long _id = Long.parseLong(invId); String md5String = md5SignatureValue(_money, _id, password2, ":Shp_item=" + shp_item); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); Users u = userService.getRepository().findUsersByLogin(userDetail.getUsername()); PaymentSystems ps = (PaymentSystems) paymentService.getRepository().findPaymentSystemsByUserId(u.getId()); if (md5String.equals(ps.getKey())) { u.setSummaryCash(u.getSummaryCash() + _money); userService.getRepository().save(u); } HttpGet method = new HttpGet(url.concat("?OK").concat(invId)); HttpClient client = new DefaultHttpClient(); client.execute(method); }
// @Override public Capture saveCapture(final String sessionId, final Capture capture) { UserDetails userDetails = JarvisContextHolder.getContext().getUserDetails(); if (userDetails == null) { ResponseBuilderImpl builder = new ResponseBuilderImpl(); builder.status(Response.Status.UNAUTHORIZED); Response response = builder.build(); throw new WebApplicationException(response); } Annotation annotation = new Annotation(); annotation.setAuthor(userDetails.getUsername()); annotation.setAnnotatorSchemaVersion(capture.getAnnotator_schema_version()); annotation.setCreated(new Date().getTime()); annotation.setOfflineId(capture.getOfflineId()); annotation.setQuote(capture.getQuote()); annotation.setRanges(capture.getRanges()); annotation.setResearchSession(capture.getResearchSession()); annotation.setText(capture.getText()); annotation.setUri(capture.getUri()); annotatorDao.insertAnnotation(annotation); capture.setId(annotation.getId()); capture.setCreated(new Date(annotation.getCreated())); return capture; }
@RequestMapping(value = "/group/create/invite", method = RequestMethod.POST) public String grpCrtInvite( @ModelAttribute("rootData") RootBean bean, Model model, Principal principal) throws Exception { initilize.exec(); // ログインアカウントのUserNameを取得 Authentication authentication = (Authentication) principal; UserDetails userDetails = (UserDetails) authentication.getPrincipal(); String userName = userDetails.getUsername(); /*グループを新規作成(MEMBERには、ログインアカウントのみをセット)し、 ログインアカウント以外のーザを取得*/ grpCrtInviteCommand.preProc(bean); grpCrtInviteCommand.exec(userName); this.bean = grpCrtInviteCommand.postProc(); // ログインアカウント以外のユーザを画面にセット model.addAttribute("rootData", bean); finalize.exec(bean, CommonConstants.VIEW_INVITE_MEMBER); return "groupInviteMember"; }
protected UserDetails createUserDetails( String username, UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities) { String returnUsername = userFromUserQuery.getUsername(); AuthenticatedUser authenticatedUser = (AuthenticatedUser) userFromUserQuery; if (!isUsernameBasedPrimaryKey()) { returnUsername = username; } return new AuthenticatedUser( returnUsername, authenticatedUser.getPassword(), authenticatedUser.getDept(), authenticatedUser.getSys_reserver3(), authenticatedUser.getUserRealName(), authenticatedUser.getJh(), authenticatedUser.getDeptzero(), authenticatedUser.getWorkdept(), authenticatedUser.getWorkdeptzero(), authenticatedUser.isEnabled(), true, true, true, combinedAuthorities); }
/** * Get all mail for the user (given to us by authentication), as a friendly HTML view. * * @param user User needing mail. * @return A list of mail. */ @GET @Produces(MediaType.TEXT_HTML) @Timed public MailboxView getMailAsHtml(@Auth UserDetails user) { return new MailboxView(grabNotifications(user.getUsername()), user); }
/** * Acknowledge the receipt of a message. * * @param user User acknowledging the message. * @param notificationId ID of the message. * @return Response OK if the message exists, otherwise 404. */ @POST @Timed public Response acknowledgeNotification( @Auth UserDetails user, @FormParam("msgId") String notificationId) { logger.info("Acknowledging message {} for {}.", notificationId, user.getUsername()); if (this.notificationMailbox.acknowledgeReceipt(user.getUsername(), notificationId)) { // OK - 200 return Response.ok().build(); } // NOT FOUND! return Response.status(404).build(); }
/** * Handles the creation of the final <tt>Authentication</tt> object which will be returned by the * provider. * * <p>The default implementation just creates a new OutOfBandAuthenticationToken from the * original, but with the UserDetails as the principal and including the authorities loaded by the * UserDetailsService. * * @param userDetails the loaded UserDetails object * @param auth the token passed to the authenticate method, containing * @return the token which will represent the authenticated user. */ protected Authentication createSuccessfulAuthentication( UserDetails rawUserDetails, OutOfBandAuthenticationToken auth) { String eMail = auth.getEmail(); if (eMail == null) { logger.warn("OutOfBand attributes did not include an e-mail address! "); throw new UsernameNotFoundException("email address not supplied in OutOfBand attributes"); } eMail = OutOfBandAuthenticationProvider.normalizeMailtoAddress(eMail); String mailtoDomain = OutOfBandAuthenticationProvider.getMailtoDomain(eMail); UserDetails userDetails = rawUserDetails; Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); authorities.addAll(userDetails.getAuthorities()); // add the AUTH_OUT_OF_BAND granted authority, authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OUT_OF_BAND.toString())); // attempt to look user up in registered users table... String username = null; UserDetails partialDetails = null; boolean noRights = false; try { partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail); // found the user in the table -- fold in authorizations and get uriUser. authorities.addAll(partialDetails.getAuthorities()); // users are blacklisted by registering them and giving them no rights. noRights = partialDetails.getAuthorities().isEmpty(); username = partialDetails.getUsername(); } catch (Exception e) { logger.warn( "OutOfBand attribute e-mail: " + eMail + " did not match any known e-mail addresses! " + e.getMessage()); throw new UsernameNotFoundException("account not recognized"); } AggregateUser trueUser = new AggregateUser( username, partialDetails.getPassword(), UUID.randomUUID().toString(), // junk... mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(), partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities); if (noRights || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) { logger.warn("OutOfBand attribute e-mail: " + eMail + " account is blocked! "); throw new UsernameNotFoundException("account is blocked"); } return new OutOfBandAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getEmail()); }
public User getCurrentUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); UserDetails springSecurityUser = (UserDetails) securityContext.getAuthentication().getPrincipal(); return userRepository.findUserByLogin(springSecurityUser.getUsername()); }
/** * {@inheritDoc}. * * @param arg0 the user name * @return S security user details. */ @Override public UserDetails loadUserByUsername(final String arg0) throws UsernameNotFoundException { for (final UserDetails details : RepositoryUserDetailsService.users) { if (details.getUsername().equals(arg0)) { return details; } } throw new UsernameNotFoundException("no user with this pseudo"); }
@Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { for (UserDetails detail : this.details) { if (detail.getUsername().equalsIgnoreCase(userName)) { return detail; } } return null; }
@Override public ItemDetails getItem(int itemNumber) throws RegistryException, LoginException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) webServiceContext.getUserPrincipal(); UserDetails user = userDetailsService.loadUserByUsername(token.getName()); terminalSession.getModule(Login.class).login(user.getUsername(), user.getPassword()); return terminalSession.getEntity(ItemDetails.class, itemNumber); }
/** Private copy constructor. */ private WikiUserDetailsImpl(UserDetails userDetails) { this.username = userDetails.getUsername(); this.password = userDetails.getPassword(); this.enabled = userDetails.isEnabled(); this.accountNonExpired = userDetails.isAccountNonExpired(); this.credentialsNonExpired = userDetails.isCredentialsNonExpired(); this.accountNonLocked = userDetails.isAccountNonLocked(); this.setAuthorities(userDetails.getAuthorities()); }
public static String getUserName() { String userName = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { UserDetails userDetail = (UserDetails) auth.getPrincipal(); userName = userDetail.getUsername(); } return userName; }
public static String userName() { UserDetails user = SecurityUtils.getUser(); if (user != null) { return user.getUsername(); } return null; }
@Override public void createUser(UserDetails userDetails) { if (!userExists(userDetails.getUsername())) { String password = userDetails.getPassword(); String hashedPassword = PasswordEncoderGenerator.generateHashedPassword(password); User user = (User) userDetails; user.setPassword(hashedPassword); mongoOperations.save((User) userDetails); } }
@RequestMapping(value = "/403", method = RequestMethod.GET) public String access(ModelMap model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { UserDetails userDetails = (UserDetails) authentication.getPrincipal(); model.addAttribute("username", userDetails.getUsername()); } return "403"; }
@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()); }
public static String createToken(UserDetails userDetails, String magicKey, long interval) { long expires = System.currentTimeMillis() + interval; StringBuilder tokenBuilder = new StringBuilder(); tokenBuilder.append(userDetails.getUsername()); tokenBuilder.append(":"); tokenBuilder.append(expires); tokenBuilder.append(":"); tokenBuilder.append(TokenUtils.computeSignature(userDetails, magicKey, expires)); return tokenBuilder.toString(); }
public String getCurrentUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication.getPrincipal() instanceof String) { // Usuario anónimo return null; } UserDetails u = (UserDetails) (authentication == null ? null : authentication.getPrincipal()); if (u != null) { return u.getUsername(); } return null; }
public static String createToken(UserDetails userDetails) { /* Expires in one hour */ long expires = System.currentTimeMillis() + 1000L * 60 * 60; StringBuilder tokenBuilder = new StringBuilder(); tokenBuilder.append(userDetails.getUsername()); tokenBuilder.append(":"); tokenBuilder.append(expires); tokenBuilder.append(":"); tokenBuilder.append(TokenUtils.computeSignature(userDetails, expires)); return tokenBuilder.toString(); }