当前位置: 首页>>代码示例>>Java>>正文


Java UsernamePasswordAuthenticationToken类代码示例

本文整理汇总了Java中org.acegisecurity.providers.UsernamePasswordAuthenticationToken的典型用法代码示例。如果您正苦于以下问题:Java UsernamePasswordAuthenticationToken类的具体用法?Java UsernamePasswordAuthenticationToken怎么用?Java UsernamePasswordAuthenticationToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


UsernamePasswordAuthenticationToken类属于org.acegisecurity.providers包,在下文中一共展示了UsernamePasswordAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: additionalAuthenticationChecks

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:DIA-NZ,项目名称:webcurator,代码行数:25,代码来源:DebugDaoAuthenticationProvider.java

示例2: authenticate

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private RESTController.ErrorCode authenticate(String username, String password, Authentication previousAuth) {

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

        // Ensure password is given.
        if (password == null) {
            return RESTController.ErrorCode.MISSING_PARAMETER;
        }

        try {
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authResult = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(authResult);
//            LOG.info("Authentication succeeded for user " + username);
        } catch (AuthenticationException x) {
            LOG.info("Authentication failed for user " + username);
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        return null;
    }
 
开发者ID:FutureSonic,项目名称:FutureSonic-Server,代码行数:24,代码来源:RESTRequestParameterProcessingFilter.java

示例3: retrieveUser

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
    throws AuthenticationException {
    UserDetails loadedUser;

    try {
    	// Check if User is Authenticated. ?? TODO
    	
        loadedUser = this.getUserDetailsService().loadUserByUsername(username);
    } catch (DataAccessException repositoryProblem) {
        throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new AuthenticationServiceException(
            "UserDetailsService returned null, which is an interface contract violation");
    }

    return loadedUser;
}
 
开发者ID:NCIP,项目名称:cagrid-general,代码行数:20,代码来源:CSMAuthenticationProvider.java

示例4: invoke

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@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;
}
 
开发者ID:Vitaliy-Yakovchuk,项目名称:ramus,代码行数:13,代码来源:LoginExecutor.java

示例5: testPermissionWhenParameterized

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
/**
 * When the source project name is parameterized, cannot check at configure time whether
 * the project is accessible.  In this case, permission check is done when the build runs.
 * Only jobs accessible to all authenticated users are allowed.
 */
@LocalData
@Test
public void testPermissionWhenParameterized() throws Exception {
    FreeStyleProject p = createProject("test$JOB", null, "", "", false, false, false, true);
    ParameterDefinition paramDef = new StringParameterDefinition("JOB", "job1");
    ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef);
    p.addProperty(paramsDef);
    // Build step should succeed when this parameter expands to a job accessible
    // to authenticated users (even if triggered by anonymous, as in this case):
    SecurityContextHolder.clearContext();
    FreeStyleBuild b = p.scheduleBuild2(0, new UserCause(),
            new ParametersAction(new StringParameterValue("JOB", "Job2"))).get();
    assertFile(true, "foo2.txt", b);
    rule.assertBuildStatusSuccess(b);
    // Build step should fail for a job not accessible to all authenticated users,
    // even when accessible to the user starting the job, as in this case:
    SecurityContext old = ACL.impersonate(
            new UsernamePasswordAuthenticationToken("joe","joe"));
    try {
    b = p.scheduleBuild2(0, new UserCause(),
            new ParametersAction(new StringParameterValue("JOB", "Job"))).get();
    assertFile(false, "foo.txt", b);
        rule.assertBuildStatus(Result.FAILURE, b);
    } finally {
        SecurityContextHolder.setContext(old);
    }
}
 
开发者ID:jenkinsci,项目名称:run-selector-plugin,代码行数:33,代码来源:CopyArtifactTest.java

示例6: authenticate

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
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;
    }
 
开发者ID:sindremehus,项目名称:subsonic,代码行数:34,代码来源:RESTRequestParameterProcessingFilter.java

示例7: processPasswordChange

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:DIA-NZ,项目名称:webcurator,代码行数:43,代码来源:ResetPasswordController.java

示例8: supports

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public boolean supports(Class authentication) {
    if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) {
        return true;
    } else {
        return false;
    }
}
 
开发者ID:kuali,项目名称:rice,代码行数:8,代码来源:KualiTestAuthenticationProvider.java

示例9: authenticate

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private static void authenticate(String principal) {
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "pass");
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
开发者ID:jenkinsci,项目名称:external-workspace-manager-plugin,代码行数:5,代码来源:DiskPoolRestrictionTest.java

示例10: login

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public void login() throws AuthenticationException {       
	Authentication auth = new UsernamePasswordAuthenticationToken(
            _creds.getUsername(), _creds.getPassword());
	try {
		auth = _manager.authenticate(auth);
	} catch (AuthenticationException ae) {
		log.info("Login FAILED for user<" + _creds.getUsername());
		throw ae;
	}
		
	log.info("Login OK for user<" + _creds.getUsername() + ">");
     
    // Should not be store here but need it.....
    this.authentication  = auth;
    
    SecurityContextHolder.getContext().setAuthentication(auth);
    
    try {
    	List<String> roleNames = new ArrayList<String>();
    	
    	for (GrantedAuthority grantedAuth : getPrincipal().getAuthorities()) {
    		String name = grantedAuth.getAuthority();
    		
    		if (name != null) {
    			log.info("<" + _creds.getUsername() + "> granted role " + name);
    			if (!roleNames.contains(name)) {
    				roleNames.add(name);
    			}
    		}
    		
    	}
    	IAuthorizationService authService = (IAuthorizationService)getService(IAuthorizationService.class);
    	if (authService != null) {
    		rbacSession = authService.setupRBAC(this, roleNames);
    		log.info("<" + _creds.getUsername() + ">");
    		log.info(rbacSession.toString());
    		/*
    		System.out.println("<" + _creds.getUsername() + ">");
    		System.out.println(rbacSession.toString());
    		*/
    	}
    } catch (Throwable t) {
    		t.printStackTrace();
    }
}
 
开发者ID:luox12,项目名称:onecmdb,代码行数:46,代码来源:Session.java

示例11: onSuccessfulAuthentication

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
/** @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.");

      }
  }
 
开发者ID:DIA-NZ,项目名称:webcurator,代码行数:45,代码来源:WCTAuthenticationProcessingFilter.java

示例12: authenticate

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:kuali,项目名称:rice,代码行数:64,代码来源:KualiCasAuthenticationProvider.java

示例13: authenticateNow

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private UsernamePasswordAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
	return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_KUALI_USER")});
}
 
开发者ID:kuali,项目名称:rice,代码行数:4,代码来源:KualiTestAuthenticationProvider.java

示例14: createSecureContext

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private static void createSecureContext(final ApplicationContext ctx, final String username, final String password) {
    AuthenticationProvider provider = (AuthenticationProvider) ctx.getBean("authenticationProvider");
    Authentication auth = provider.authenticate(new UsernamePasswordAuthenticationToken(username, password));
    SecurityContextHolder.getContext().setAuthentication(auth);
}
 
开发者ID:NCIP,项目名称:cagrid-general,代码行数:6,代码来源:SDKAcegiMethodTest.java

示例15: retrieveUser

import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    return RedmineSecurityRealm.this.authenticate(username, authentication.getCredentials().toString());
}
 
开发者ID:yasu-s,项目名称:redmine-user-auth-plugin,代码行数:5,代码来源:RedmineSecurityRealm.java


注:本文中的org.acegisecurity.providers.UsernamePasswordAuthenticationToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。