org.acegisecurity.providers.UsernamePasswordAuthenticationToken Java Examples

The following examples show how to use org.acegisecurity.providers.UsernamePasswordAuthenticationToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DebugDaoAuthenticationProvider.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    Object salt = null;

    System.out.println("User pwd: "+userDetails.getPassword());
    System.out.println("Auth pwd raw: "+authentication.getCredentials().toString());
    
    if (getSaltSource() != null) {
        salt = getSaltSource().getSalt(userDetails);
    }
    
    System.out.println("Auth pwd: "+getPasswordEncoder().encodePassword(authentication.getCredentials().toString().trim(), salt));
    
    System.out.println("Salt: "+salt);
    System.out.println("Encoder: "+getPasswordEncoder());

    if (!getPasswordEncoder().isPasswordValid(userDetails.getPassword(),
            authentication.getCredentials().toString(), salt)) {
        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials",
                "Bad credentials"), userDetails);
    }
}
 
Example #2
Source File: LoginExecutor.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object invoke(RemoteInvocation invocation, Object arg1)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    Object object = super.invoke(invocation, arg1);
    UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(
            invocation.getArguments()[0].toString(), invocation
            .getArguments()[1].toString());
    Authentication auth = daoAuthenticationProvider.authenticate(userToken);
    SecurityContextHolder.getContext().setAuthentication(auth);
    return object;
}
 
Example #3
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof GitLabAuthenticationToken) {
                return authentication;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                try {
                    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
                    GitLabAuthenticationToken gitlab = new GitLabAuthenticationToken(token.getCredentials().toString(), getGitlabApiUri(), TokenType.PRIVATE_TOKEN);
                    SecurityContextHolder.getContext().setAuthentication(gitlab);
                    return gitlab;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            throw new BadCredentialsException("Unexpected authentication type: " + authentication);
        }
    }, new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            return GitLabSecurityRealm.this.loadUserByUsername(username);
        }
    });
}
 
Example #4
Source File: RESTRequestParameterProcessingFilter.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {

        // Previously authenticated and username not overridden?
        if (username == null && previousAuth != null) {
            return null;
        }

        if (salt != null && token != null) {
            User user = securityService.getUserByName(username);
            if (user == null) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
            String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
            if (!expectedToken.equals(token)) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }

            password = user.getPassword();
        }

        if (password != null) {
            try {
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                Authentication authResult = authenticationManager.authenticate(authRequest);
                SecurityContextHolder.getContext().setAuthentication(authResult);
                return null;
            } catch (AuthenticationException x) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
        }

        return RESTController.ErrorCode.MISSING_PARAMETER;
    }
 
Example #5
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
public HttpResponse doEscapeHatch(@QueryParameter("j_username") String username, @QueryParameter("j_password") String password) {
    randomWait(); // to slowdown brute forcing
    if(!isEscapeHatchEnabled()) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(this.escapeHatchUsername == null || this.escapeHatchSecret == null) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(escapeHatchUsername.equalsIgnoreCase(username) && escapeHatchSecret.getPlainText().equals(password)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
        if(isNotBlank(escapeHatchGroup)) {
            authorities.add(new GrantedAuthorityImpl(escapeHatchGroup));
        }
        String userName = "escape-hatch-admin";
        GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[authorities.size()]);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        		userName,
                "",
                grantedAuthorities
        );
        SecurityContextHolder.getContext().setAuthentication(token);
        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);
        return HttpRedirect.CONTEXT_ROOT;
    }
    return HttpResponses.redirectViaContextPath("loginError");
}
 
Example #6
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException {

        GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo);
        if(LOGGER.isLoggable(Level.FINEST)) {
		    StringBuilder grantedAuthoritiesAsString = new StringBuilder("(");
		    for(GrantedAuthority grantedAuthority : grantedAuthorities) {
		        grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
            }
            grantedAuthoritiesAsString.append(" )");
		    LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        User user = User.get(token.getName());
        // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object.
        user.addProperty(new OicUserProperty(userName, grantedAuthorities));

        if(emailFieldName!=null) {
	        String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName);
	        if (email != null) {
	            user.addProperty(new Mailer.UserProperty(email));
	        }
        }

        if(fullNameFieldName!=null) {
		    String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName);
		    if (fullName != null) {
		        user.setFullName(fullName);
		    }
        }

        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);

        return token;
    }
 
Example #7
Source File: ResetPasswordController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Process the change password command. 
 */
private ModelAndView processPasswordChange(HttpServletRequest aReq,HttpServletResponse aResp, ResetPasswordCommand aCmd, BindException aErrors) throws Exception {
    ModelAndView mav = new ModelAndView();
    if (aErrors.hasErrors()) {
        mav.addObject(Constants.GBL_CMD_DATA, aErrors.getTarget());
        mav.addObject(Constants.GBL_ERRORS, aErrors);
        mav.setViewName(Constants.VIEW_RESET_PWD);

        return mav;
    }

    try {
                    
        UsernamePasswordAuthenticationToken upat = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        
        User userAccount = (User) authDAO.getUserByName(upat.getName());
        
        String sysSalt = salt.getSystemWideSalt();
        String encodedPwd = encoder.encodePassword(aCmd.getNewPwd(),sysSalt);
        
        userAccount.setPassword(encodedPwd);
        //userAccount.setPwdFailedAttempts(0);
        userAccount.setForcePasswordChange(false);

        authDAO.saveOrUpdate(userAccount);
        
        upat.setDetails(userAccount);
        
        SecurityContextHolder.getContext().setAuthentication(upat);
        
        mav.addObject(Constants.MESSAGE_TEXT, "Your password has been changed.");
        mav.setViewName(Constants.VIEW_PASSWORD_RESET_SUCCESS);

        return mav;
    }
    catch (Exception e) {
        throw new Exception("Persistance Error occurred during password change", e);
    }
}
 
Example #8
Source File: KualiTestAuthenticationProvider.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public boolean supports(Class authentication) {
    if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) {
        return true;
    } else {
        return false;
    }
}
 
Example #9
Source File: WCTAuthenticationProcessingFilter.java    From webcurator with Apache License 2.0 4 votes vote down vote up
/** @see org.acegisecurity.ui.AbstractProcessingFilter#onSuccessfulAuthentication(HttpServletRequest,HttpServletResponse, Authentication) . */
  protected void onSuccessfulAuthentication(HttpServletRequest request,
          HttpServletResponse response, Authentication authResult)
          throws IOException {
      
      log.debug("calling onSuccessfulAuthentication for WCT");
      String userName = authResult.getName();
      
      User wctUser = authDAO.getUserByName(userName);
      
      if (wctUser != null) {
       log.debug("loaded WCT User object "+wctUser.getUsername()+" from database");
       UsernamePasswordAuthenticationToken auth =  (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
       auth.setDetails(wctUser);
       log.debug("pushing back upat into SecurityContext with populated WCT User");
       SecurityContextHolder.getContext().setAuthentication(auth);
      
       //audit successful login event
       auditor.audit(User.class.getName(), wctUser.getOid(), Auditor.ACTION_LOGIN_SUCCESS, "Successful Login for username: "+wctUser.getUsername());
	
       // Get the Spring Application Context.
	WebApplicationContext ctx = ApplicationContextFactory.getWebApplicationContext();

	// set or re-set the page size cookie..
	// ..first get the value of the page size cookie
	String currentPageSize = CookieUtils.getPageSize(request);
	// ..then refresh the page size cookie, to expire in a year
	CookieUtils.setPageSize(response, currentPageSize);

       // set login for duration
       String sessionId = request.getSession().getId();
       LogonDurationDAO logonDurationDAO = (LogonDurationDAO) ctx.getBean(Constants.BEAN_LOGON_DURATION_DAO);
      	logonDurationDAO.setLoggedIn(sessionId, new Date(), wctUser.getOid(), wctUser.getUsername(), wctUser.getNiceName());
      	
	// Check previous records of duration
      	logonDurationDAO.setProperLoggedoutForCurrentUser(wctUser.getOid(), sessionId);
      	
}  else {
          
          //audit successful login but unsucessful load of WCT User event
          auditor.audit(User.class.getName(), Auditor.ACTION_LOGIN_FAILURE_NO_USER, "Un-successful login for username: "+userName+" as user doesn't exist in the WCT System.");

      }
  }
 
Example #10
Source File: KualiCasAuthenticationProvider.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * This overridden method is copied from CAS verbatim.  For some reason 
 * {@link authenticateNow} would not override and the super method 
 * would get called until did this method was also overridden.
 * 
 * @see org.acegisecurity.providers.cas.CasAuthenticationProvider#authenticate(org.acegisecurity.Authentication)
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    StatelessTicketCache statelessTicketCache = this.getStatelessTicketCache();
    String key = this.getKey();
    if (!supports(authentication.getClass())) {
        return null;
    }

    if (authentication instanceof UsernamePasswordAuthenticationToken
        && (!CasProcessingFilter.CAS_STATEFUL_IDENTIFIER.equals(authentication.getPrincipal().toString())
        && !CasProcessingFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal().toString()))) {
        // UsernamePasswordAuthenticationToken not CAS related
        return null;
    }

    // If an existing CasAuthenticationToken, just check we created it
    if (authentication instanceof CasAuthenticationToken) {
        if (key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) {
            return authentication;
        } else {
            throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey",
                    "The presented CasAuthenticationToken does not contain the expected key"));
        }
    }

    // Ensure credentials are presented
    if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) {
        throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket",
                "Failed to provide a CAS service ticket to validate"));
    }

    boolean stateless = false;

    if (authentication instanceof UsernamePasswordAuthenticationToken
        && CasProcessingFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) {
        stateless = true;
    }

    CasAuthenticationToken result = null;

    if (stateless) {
        // Try to obtain from cache
        result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
    }

    if (result == null) {
        result = this.authenticateNow(authentication);
        result.setDetails(authentication.getDetails());
    }

    if (stateless) {
        // Add to cache
        statelessTicketCache.putTicketInCache(result);
    }

    return result;
}
 
Example #11
Source File: KualiTestAuthenticationProvider.java    From rice with Educational Community License v2.0 4 votes vote down vote up
private UsernamePasswordAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
	return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_KUALI_USER")});
}