List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities)
AuthenticationManager
or AuthenticationProvider
implementations that are satisfied with producing a trusted (i.e. From source file:ltistarter.BaseApplicationTest.java
/** * Makes a new session which contains authentication roles, * this allows us to test requests with varying types of security * * @param username the username to set for the session * @param roles all the roles to grant for this session * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session)) *//*from ww w .j a va 2s . c o m*/ public MockHttpSession makeAuthSession(String username, String... roles) { if (StringUtils.isEmpty(username)) { username = "azeckoski"; } MockHttpSession session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); Collection<GrantedAuthority> authorities = new HashSet<>(); if (roles != null && roles.length > 0) { for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } } //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities, "key", "signature", "HMAC-SHA-1", "signaturebase", "token"); Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities); SecurityContextHolder.getContext().setAuthentication(authToken); return session; }
From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java
@Test public void testAddUserAsAdmin() throws Exception { SecurityContext securityContext = new SecurityContextImpl(); User user = new User("admin"); user.setId(2L);/*from w ww . j a va 2 s.co m*/ user.setPassword("password"); user.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); securityContext.setAuthentication(token); SecurityContextHolder.setContext(securityContext); UserManager userManager = makeInterceptedTarget(); final User adminUser = new User("admin"); adminUser.setId(2L); context.checking(new Expectations() { { one(userDao).saveUser(with(same(adminUser))); } }); userManager.saveUser(adminUser); }
From source file:com.sun.identity.provider.springsecurity.OpenSSOAuthenticationProvider.java
/** * authenticate the access request.//from www. j a v a 2s . c o m * * Note by this point the user has already been granted an sso token * (i.e. they have already authenticated because they were redirected * to opensso). * * If the user has any group membership we turn those into * GrantedAuthortities (roles in Spring terminolgy). * @see OpenSSOSimpleAuthoritiesPopulator * * Note that a failure to retrieve OpenSSO roles does not result in * an non revcoverable exception (but we should revist this decision). In theory * we can continue with authentication only. The user will have no * GrantedAuthorities. * * @param authentication * @return authentication token - possibly withe ROLE_* authorities. * * @throws org.springframework.security.core.AuthenticationException */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { OpenSSOSimpleAuthoritiesPopulator populator = new OpenSSOSimpleAuthoritiesPopulator(); if (debug.messageEnabled()) debug.message("Authentication: " + authentication); UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String principal = (String) token.getPrincipal(); // hack alert // We pass in the SSOToken as the credential (.e.g the password) // this is probably confusing - and we should refactor to use a // proper OpenSSOAuthenitcationToken. SSOToken ssoToken = (SSOToken) token.getCredentials(); try { Collection<? extends GrantedAuthority> ga = populator.getGrantedAuthorities(ssoToken); UserDetails u = new User(principal, "secret", true, true, true, true, ga); authentication = new UsernamePasswordAuthenticationToken(u, "secret", ga); } catch (Exception ex) { //throw new AuthenticationServiceException("Exception trying to get AMIdentity", ex); // Note: We eat the exception // The authentication can still succeed - but there will be no // granted authorities (i.e. no roles granted). // This is arguably the right thing to do here debug.error("Exception Trying to get AMIdentity", ex); } return authentication; }
From source file:org.xaloon.wicket.security.spring.external.ExternalAuthenticationProvider.java
private Authentication createDefaultAuthenticationToken(Authentication authentication, UserDetails loadedUser) { UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(loadedUser, authentication.getCredentials(), loadedUser.getAuthorities()); result.setDetails(userDao.getUserByUsername(loadedUser.getUsername())); return result; }
From source file:org.musicrecital.webapp.services.impl.SpringSecurityContext.java
public void login(User user) { if (user == null) { throw new IllegalArgumentException("User cannot be null"); }//from ww w .j av a2s .c o m UsernamePasswordAuthenticationToken loggedIn = new UsernamePasswordAuthenticationToken(user, user.getConfirmPassword(), user.getAuthorities()); loggedIn.setDetails(user); SecurityContextHolder.getContext().setAuthentication(loggedIn); }
From source file:com.eazytec.webapp.filter.CustomAuthenticationProvider.java
License:asdf
public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = String.valueOf(authentication.getPrincipal()).toLowerCase(); String password = String.valueOf(authentication.getCredentials()); logger.debug("Checking authentication for user {}" + username); logger.debug("userResponse: {}" + captchaCaptureFilter.getCaptcha_response()); if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { throw new BadCredentialsException("No Username and/or Password Provided."); }/*from w ww . j a va2 s . c o m*/ licensePreCheck(); Boolean isCaptchaNeeded = Boolean .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.captcha.needed")); Boolean adEnabled = Boolean .valueOf(PropertyReader.getInstance().getPropertyFromFile("Boolean", "system.ad.enabled")); // if(!adEnabled){ if (isCaptchaNeeded && StringUtils.isBlank(captchaCaptureFilter.getCaptcha_response())) { throw new BadCredentialsException("Captcha Response is Empty"); } if (isCaptchaNeeded) { // else { // Send HTTP request to validate user's Captcha boolean captchaPassed = SimpleImageCaptchaServlet.validateCaptcha( captchaCaptureFilter.getCaptcha_challenge(), captchaCaptureFilter.getCaptcha_response()); // Check if valid if (captchaPassed) { logger.debug("Captcha is valid!"); resetCaptchaFields(); } else { logger.debug("Captcha is invalid!"); resetCaptchaFields(); throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.captcha.mismatch")); } } User user = null; if (!adEnabled) { user = userService.getUserById(username); } if (user == null && adEnabled) { throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch")); } if (user == null || !user.isEnabled() && !adEnabled) { throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch")); } if (passwordEncoder.isPasswordValid(user.getPassword(), password, saltSource.getSalt(user))) { Set<GrantedAuthority> authorityList = (Set<GrantedAuthority>) user.getAuthorities(); return new UsernamePasswordAuthenticationToken(user, password, authorityList); } else { if (adEnabled) { throw new BadCredentialsException(I18nUtil.getMessageProperty("errors.password.mismatch")); } else { throw new BPMAccountStatusException(I18nUtil.getMessageProperty("errors.password.mismatch")); } } }
From source file:com.organization.projectname.config.AuthenticationTokenFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authToken = request.getHeader(this.tokenHeader); // authToken.startsWith("Bearer ") // String authToken = header.substring(7); String username = jwtTokenUtil.getUsernameFromToken(authToken); String ip = SecurityUtil.getClientIP(request); log.info("checking authentication for user " + username + " and IP " + ip); IPWhitelist iPWhitelist = iPWhitelistRepository.findByIpAddr(ip); System.out.println(iPWhitelist); if (iPWhitelist != null && username != null && SecurityContextHolder.getContext().getAuthentication() == null) { // It is not compelling necessary to load the use details from the database. You could also store the information // in the token and read it from it. It's up to you ;) UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); // For simple validation it is completely sufficient to just check the token integrity. You don't have to call // the database compellingly. Again it's up to you ;) if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); log.info("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); }// w ww . j ava 2s .c o m } chain.doFilter(request, response); }
From source file:org.openengsb.opencit.ui.web.LoginPageTest.java
private void mockAuthentication() { AuthenticationManager authManager = mock(AuthenticationManager.class); final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() { @Override//from w ww . j ava 2s .co m public Authentication answer(InvocationOnMock invocation) { Authentication auth = (Authentication) invocation.getArguments()[0]; if (auth.getCredentials().equals("password")) { return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities); } throw new BadCredentialsException("wrong password"); } }); contextMock.putBean("authenticationManager", authManager); }
From source file:com.amediamanager.service.UserServiceImpl.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); User user = find(username);// w ww . j a va 2 s . c o m if (null == user || (!BCrypt.checkpw(password, user.getPassword()))) { throw new BadCredentialsException("Invalid username or password"); } List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); // Create new auth token auth = new UsernamePasswordAuthenticationToken(username, null, grantedAuths); auth.setDetails(user); return auth; }
From source file:binky.reportrunner.service.impl.AuthenticationServiceImpl.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.info("authenticate service invoked"); if (StringUtils.isBlank((String) authentication.getPrincipal()) || StringUtils.isBlank((String) authentication.getCredentials())) { logger.debug("userName blank is " + StringUtils.isBlank((String) authentication.getPrincipal() + " password blank is " + StringUtils.isBlank((String) authentication.getCredentials()))); throw new BadCredentialsException("Invalid username/password"); }/*from ww w . j a v a 2 s . c o m*/ String userName = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); RunnerUser user = userDao.get(userName); EncryptionUtil enc = new EncryptionUtil(); List<GrantedAuthority> authorities = new LinkedList<GrantedAuthority>(); try { if (user != null && user.getPassword().equals(enc.hashString(password))) { if (user.getIsAdmin()) { logger.info("admin login for user: " + userName); authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN")); } else { logger.info("user login for user: " + userName); } authorities.add(new GrantedAuthorityImpl("ROLE_USER")); } else { logger.warn("login fail for user: " + userName); throw new BadCredentialsException("Invalid username/password"); } } catch (Exception e) { logger.fatal(e.getMessage(), e); throw new AuthenticationServiceException(e.getMessage(), e); } return new UsernamePasswordAuthenticationToken(userName, authentication.getCredentials(), authorities); }