List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials)
UsernamePasswordAuthenticationToken
, as the #isAuthenticated() will return false
. From source file:net.sourceforge.jukebox.model.ProfileTest.java
/** * Tests the validator with a valid password. *//*from w ww. j ava2s . c o m*/ @Test public final void testValidCurrentPassword() { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(Profile.ADMIN_USERNAME, "test1234"); SecurityContextHolder.getContext().setAuthentication(auth); Profile profile = createProfile("test1234", "newPassword", "newPassword"); Set<ConstraintViolation<Profile>> constraintViolations = validator.validate(profile); assertEquals(constraintViolations.size(), 0); SecurityContextHolder.getContext().setAuthentication(null); }
From source file:org.openwms.client.security.AuthenticationTokenProcessingFilter.java
/** * {@inheritDoc}/* w w w . j a v a 2 s . c o m*/ * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Expecting a http servlet request"); } HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader(AUTH_TOKEN); String userName = TokenUtils.getUserNameFromToken(authToken); if (userName != null) { // The returned UserDetails object has credentials encoded, we rely // on two AuthenticationProviders here to // come around this issue, one with PasswordEncoder and one without UserDetails userDetails = this.userService.loadUserByUsername(userName); if (TokenUtils.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext() .setAuthentication(this.authenticationManager.authenticate(authentication)); } } chain.doFilter(request, response); SecurityContextHolder.clearContext(); }
From source file:com.razorfish.security.AcceleratorAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();/*from w ww .j av a 2 s .co m*/ String usernameResult = username; UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; if (!usernameResult.isEmpty()) { final List<CustomerModel> result = getCustomerDao().findCustomerByMobileNumber(usernameResult); if (!result.isEmpty()) { usernameResult = result.iterator().next().getOriginalUid(); token = new UsernamePasswordAuthenticationToken(usernameResult, (String) authentication.getCredentials()); token.setDetails(authentication.getDetails()); } } if (getBruteForceAttackCounter().isAttack(usernameResult)) { try { final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(usernameResult)); userModel.setLoginDisabled(true); getModelService().save(userModel); bruteForceAttackCounter.resetUserCounter(userModel.getUid()); } catch (final UnknownIdentifierException e) { LOG.warn("Brute force attack attempt for non existing user name " + usernameResult); } finally { throw new BadCredentialsException( messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials")); } } checkCartForUser(usernameResult); return super.authenticate(token); }
From source file:org.createnet.raptor.auth.service.controller.AuthenticationController.java
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) @ApiOperation(value = "Login an user with provided credentials", notes = "", response = JwtResponse.class, nickname = "login") public ResponseEntity<?> login(@RequestBody JwtRequest authenticationRequest) throws AuthenticationException { try {// ww w. j a v a2 s . com final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.username, authenticationRequest.password)); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.username); final Token token = tokenService.createLoginToken((User) userDetails); // Return the token return ResponseEntity.ok(new JwtResponse((User) userDetails, token.getToken())); } catch (AuthenticationException ex) { logger.error("Authentication exception: {}", ex.getMessage()); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication failed"); } }
From source file:com.coinblesk.server.controller.UserController.java
@RequestMapping(value = "/login", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginDTO.getUsername().toLowerCase(Locale.ENGLISH), loginDTO.getPassword()); try {/*from w w w. ja v a 2s .c o m*/ Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.createToken(authentication); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(Collections.singletonMap("token", jwt)); } catch (AuthenticationException exception) { return new ResponseEntity<>( Collections.singletonMap("AuthenticationException", exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
From source file:com.evidence.service.UserServiceTest.java
@Test public void testPasswordEncoding() { ArrayList<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); list.add(new SimpleGrantedAuthority(Role.ROLE_USER.name())); list.add(new SimpleGrantedAuthority(Role.ROLE_ADMINISTRATOR.name())); User u = new User("admin@evidence.com", "password", list); String password = passwordEncoder.encodePassword("password", saltSource.getSalt(u)); com.tapas.evidence.entity.user.User user = userRepository.read(u.getUsername()); assertEquals(password, user.getPassword()); Authentication authentication = new UsernamePasswordAuthenticationToken("admin@evidence.com", "password"); try {//from w w w .j a va 2 s. c om authenticationManager.authenticate(authentication); } catch (BadCredentialsException e) { fail("Problem with authentication: user/password"); } }
From source file:com.ushahidi.swiftriver.core.api.controller.AccountsControllerTest.java
@Test public void getAuthenticatedUserAccount() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken("user1", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); this.mockMvc.perform(get("/v1/accounts/me").principal(authentication)).andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.id").value(3)).andExpect(jsonPath("$.account_path").value("user1")) .andExpect(jsonPath("$.active").value(true)).andExpect(jsonPath("$.private").value(false)) .andExpect(jsonPath("$.river_quota_remaining").value(20)) .andExpect(jsonPath("$.follower_count").value(2)).andExpect(jsonPath("$.following_count").value(1)) .andExpect(jsonPath("$.owner.name").value("User 1")) .andExpect(jsonPath("$.owner.email").value("user1@myswiftriver.com")) .andExpect(jsonPath("$.owner.username").value("user1")) .andExpect(jsonPath("$.owner.avatar") .value("https://secure.gravatar.com/avatar/373329f529512d8898e8a8aeea3a7675?s=80&d=mm&r=g")) .andExpect(jsonPath("$.rivers").exists()).andExpect(jsonPath("$.rivers[0].id").exists()) .andExpect(jsonPath("$.rivers[0].name").exists()) .andExpect(jsonPath("$.rivers[0].follower_count").exists()) .andExpect(jsonPath("$.rivers[0].public").exists()) .andExpect(jsonPath("$.rivers[0].active").exists()) .andExpect(jsonPath("$.rivers[0].drop_count").exists()) .andExpect(jsonPath("$.rivers[0].drop_quota").exists()) .andExpect(jsonPath("$.rivers[0].full").exists()) .andExpect(jsonPath("$.rivers[0].extension_count").exists()) .andExpect(jsonPath("$.buckets").exists()).andExpect(jsonPath("$.buckets[0].id").exists()) .andExpect(jsonPath("$.buckets[0].name").exists()) .andExpect(jsonPath("$.buckets[0].description").exists()) .andExpect(jsonPath("$.buckets[0].follower_count").exists()) .andExpect(jsonPath("$.buckets[0].public").exists()) .andExpect(jsonPath("$.buckets[0].drop_count").exists()).andExpect(jsonPath("$.forms").exists()); }
From source file:com.snv.guard.AuthenticationServiceTest.java
@Test public void should_clear_spring_security_context_when_logout() { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( credential.getLogin(), credential.getPassword()); this.authentication = authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(this.authentication); this.authenticationService.logout(); assertTrue(SecurityContextHolder.getContext().getAuthentication() == null); }
From source file:ru.org.linux.auth.LoginController.java
@RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST) @ResponseBody//ww w. ja va 2 s . c o m public LoginStatus loginAjax(@RequestParam("nick") final String username, @RequestParam("passwd") final String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username); token.setDetails(details); Authentication auth = authenticationManager.authenticate(token); UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails(); if (!userDetails.getUser().isActivated()) { return new LoginStatus(false, "User not activated"); } SecurityContextHolder.getContext().setAuthentication(auth); rememberMeServices.loginSuccess(request, response, auth); AuthUtil.updateLastLogin(auth, userDao); return new LoginStatus(auth.isAuthenticated(), auth.getName()); } catch (LockedException e) { return new LoginStatus(false, "User locked"); } catch (UsernameNotFoundException e) { return new LoginStatus(false, "Bad credentials"); } catch (BadCredentialsException e) { return new LoginStatus(false, e.getMessage()); } }
From source file:com.gm.wine.web.LoginvalidateAction.java
@Override public String execute() throws Exception { HttpServletRequest request = Struts2Utils.getRequest(); String loginName = request.getParameter("loginName"); String password = request.getParameter("password"); UserVO u = new UserVO(); try {/*from www .j a v a2 s . co m*/ User user = userManager.getUserByUsername(loginName); if (user != null) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginName, password); token.setDetails(new WebAuthenticationDetails(request)); Authentication authenticatedUser = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authenticatedUser); request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); u.setErrorCode(GlobalMessage.SUCCESS_CODE); u.setErrorMessage("?"); u.setId(user.getId()); u.setLoginName(user.getLoginName()); u.setName(user.getName()); } else { u.setErrorCode(GlobalMessage.ERROR_CODE); u.setErrorMessage("?"); } } catch (AuthenticationException e) { e.printStackTrace(); u.setErrorCode(GlobalMessage.ERROR_CODE); u.setErrorMessage("?"); } data = new Gson().toJson(u); return SUCCESS; }