Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getName

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getName

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getName.

Prototype

public String getName() 

Source Link

Usage

From source file:org.jasig.schedassist.web.security.CustomLDAPAuthenticationProvider.java

/**
 * Incorporates some of the /* w  w  w  . j ava 2 s.  c  om*/
 *  (non-Javadoc)
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);
        if (userData == null) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    }
}

From source file:org.geonode.security.GeoNodeAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication, HttpServletRequest request)
        throws AuthenticationException {
    this.client.setRequestUrl("http://" + request.getServerName() + "/");
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        String password = (String) token.getCredentials();

        // ignore this - let the other provider(s) handle things
        if (GeoServerUser.ROOT_USERNAME.equals(username)
                && GeoServerUser.DEFAULT_ADMIN_PASSWD.equals(username)) {
            return null;
        }//from www  . ja  va2  s.co  m

        try {
            if (username == "" && password == null) {
                return client.authenticateAnonymous();
            } else {
                // if an anonymous session cookie exists in the request but
                // the user is logging in via the admin or other form mechanism,
                // it's possible that the GeoNodeCookieProcessingFilter will
                // 'overwrite' the credentials... it will check for this
                Authentication auth = client.authenticateUserPwd(username, password);
                if (auth.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
                return auth;
            }
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (UsernamePasswordAuthenticationToken)", e);
        }
    } else if (authentication instanceof GeoNodeSessionAuthToken) {
        try {
            return client.authenticateCookie((String) authentication.getCredentials());
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (GeoNodeSessionAuthToken)", e);
        }
    } else if (authentication instanceof AnonymousGeoNodeAuthenticationToken) {
        try {
            return client.authenticateAnonymous();
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (AnonymousGeoNodeAuthenticationToken)", e);
        }
    } else {
        throw new IllegalArgumentException(
                "GeoNodeAuthenticationProvider accepts only UsernamePasswordAuthenticationToken and GeoNodeSessionAuthToken; received "
                        + authentication);
    }
}

From source file:org.apache.cxf.fediz.service.idp.STSUPAuthenticationProvider.java

private Authentication handleUsernamePassword(UsernamePasswordAuthenticationToken usernamePasswordToken,
        IdpSTSClient sts) {//  w  ww  .  j  av a 2  s . c  o m
    sts.getProperties().put(SecurityConstants.USERNAME, usernamePasswordToken.getName());
    sts.getProperties().put(SecurityConstants.PASSWORD, (String) usernamePasswordToken.getCredentials());

    try {

        // Line below may be uncommented for debugging    
        // setTimeout(sts.getClient(), 3600000L);

        SecurityToken token = sts.requestSecurityToken(this.appliesTo);

        List<GrantedAuthority> authorities = createAuthorities(token);

        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(
                usernamePasswordToken.getName(), usernamePasswordToken.getCredentials(), authorities);

        STSUserDetails details = new STSUserDetails(usernamePasswordToken.getName(),
                (String) usernamePasswordToken.getCredentials(), authorities, token);
        upat.setDetails(details);

        LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), usernamePasswordToken.getName());
        return upat;

    } catch (Exception ex) {
        LOG.info("Failed to authenticate user '" + usernamePasswordToken.getName() + "'", ex);
        return null;
    }

}

From source file:com.corporate.transport.authentication.FacebookAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) {

    System.out.println("FacebookAuthenticationProvider.authenticate()");

    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    String username = auth.getName();
    String password = (String) auth.getCredentials();

    //TEST      /*from w  w  w.ja v  a2  s . com*/
    try {
        System.out.println("GOING FOR VALIDATION");
        LDAPAuthentication ldap = new LDAPAuthentication();
        if (ldap.authenticate(username, password)) {
            List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();

            if (username != null && (username.equals("patel286@avaya.com"))) {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            } else {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
            }

            return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
        }

    } catch (Exception e) {

        if (e instanceof AuthenticationException) {
            throw new BadCredentialsException("Incorrect Email Id or Password - Jayesh");
        }
        //TODO [SM] Add logging for specific exception
        else if (e instanceof CommunicationException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else if (e instanceof NamingException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        }
    }

    //PRODUCTION      
    /*      try{
       System.out.println("GOING FOR VALIDATION");
       com.corporate.ldap.Authentication ldap = new com.corporate.ldap.Authentication();
       status = ldap.authenticate(username, password);
            
       System.out.println("GOING FOR VALIDATION STATUS:"+status);
       if(status==1){
    List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();
            
    if(username!=null && username.equals("jayesh.patel")){
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));   
    }else{
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
    }
            
    return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
            
       }else if(status==0){
    throw new BadCredentialsException("Incorrect Email Id or Password.");
            
       }else if(status==2){
    throw new LDAPConnectivityException("There is some error connecting with LDAP");
       }
            
    }catch (Exception e) {
       e.printStackTrace();
    }*/

    return null;

}

From source file:nc.noumea.mairie.appock.core.security.MockAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String s,
        final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
        throws AuthenticationException {

    try {/*from   w  w w  . j a v  a  2 s. c om*/
        AppUser appUser = appUserService.findByLogin(usernamePasswordAuthenticationToken.getName());
        if (appUser == null || !appUser.isActif()) {
            throw new BadCredentialsException("Connection  l'application APPOCK impossible");
        }
    } catch (NoResultException e) {
        throw new BadCredentialsException("Connection  l'application APPOCK impossible");
    }

    user = new UserDetails() {
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return appockAuthoritiesPopulator.getGrantedAuthorities(null,
                    usernamePasswordAuthenticationToken.getName());
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public String getUsername() {
            return usernamePasswordAuthenticationToken.getName();
        }

        @Override
        public boolean isAccountNonExpired() {
            return true;
        }

        @Override
        public boolean isAccountNonLocked() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }

        @Override
        public boolean isEnabled() {
            return true;
        }
    };

    return user;
}

From source file:com.tasktop.c2c.server.common.service.http.MultiUserClientHttpRequestFactory.java

protected void setCredentials(HttpClient httpClient, Authentication authentication) {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = token.getCredentials() == null ? "" : token.getCredentials().toString();

    // FIXME: review, should probably not be AuthScope.ANY
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    Object auth = httpClient.getParams().getParameter(PARAM_AUTH_KEY);
    if (auth == null || !auth.equals(credentials)) {
        clearAuthState(httpClient);//from  w w w  .j  a v a  2s  .co  m

        httpClient.getParams().setParameter(PARAM_AUTH_KEY, credentials);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }

    // this seems to be necessary for correct operation.
    // it seems that with keepalives a response to an auth challenge is issued
    // without first reading the whole response, making the 2nd request read the wrong
    // data for the HTTP status line.
    httpClient.getParams().setAuthenticationPreemptive(authenticationPreemptive);
    if (cookiePolicy != null) {
        httpClient.getParams().setCookiePolicy(cookiePolicy);
    }
}

From source file:org.verinice.rest.security.VeriniceAuthenticationProvider.java

private boolean checkPassword(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {

    String realm = environement.getProperty("veriniceserver.realm");
    String a1 = authentication.getName() + ":" + realm + ":" + authentication.getCredentials();
    String md5Hex = md5Hex(a1);/*from w  ww . j ava  2  s. c om*/
    return md5Hex.equals(userDetails.getPassword());
}

From source file:waffle.spring.WindowsAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    final UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    final IWindowsIdentity windowsIdentity = this.authProvider.logonUser(auth.getName(),
            auth.getCredentials().toString());
    WindowsAuthenticationProvider.LOGGER.debug("logged in user: {} ({})", windowsIdentity.getFqn(),
            windowsIdentity.getSidString());

    if (!this.allowGuestLogin && windowsIdentity.isGuest()) {
        WindowsAuthenticationProvider.LOGGER.warn("guest login disabled: {}", windowsIdentity.getFqn());
        throw new GuestLoginDisabledAuthenticationException(windowsIdentity.getFqn());
    }/*  w w w.  j  a v a2s.  c  o m*/

    final WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity, this.principalFormat,
            this.roleFormat);
    WindowsAuthenticationProvider.LOGGER.debug("roles: {}", windowsPrincipal.getRolesString());

    final WindowsAuthenticationToken token = new WindowsAuthenticationToken(windowsPrincipal,
            this.grantedAuthorityFactory, this.defaultGrantedAuthority);

    WindowsAuthenticationProvider.LOGGER.info("successfully logged in user: {}", windowsIdentity.getFqn());
    return token;
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

@Override
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();

    DirContext ctx = bindAsUser(username, password);

    try {//from www  . ja  va  2 s. c  om
        return searchForUser(ctx, username);

    } catch (NamingException e) {
        logger.error("Failed to locate directory entry for authenticated user: " + username, e);
        throw badCredentials(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}

From source file:opensnap.security.SecurityChannelInterceptor.java

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) message
            .getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER);
    String destination = (String) message.getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER);
    if ((destination == null) || isAllowed(destination, authentication.getName())) {
        return message;
    }//from  w  w  w  .j ava 2  s  .c  om
    throw new AccessDeniedException(
            "Message to destination " + destination + " not allowed for user " + authentication.getName());

}