Example usage for org.springframework.security.core Authentication getCredentials

List of usage examples for org.springframework.security.core Authentication getCredentials

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getCredentials.

Prototype

Object getCredentials();

Source Link

Document

The credentials that prove the principal is correct.

Usage

From source file:sample.contact.ClientApplication.java

public void invokeContactService(Authentication authentication, int nrOfCalls) {
    StopWatch stopWatch = new StopWatch(nrOfCalls + " ContactService call(s)");
    Map<String, ContactService> contactServices = this.beanFactory.getBeansOfType(ContactService.class, true,
            true);//from w  w w .  ja v  a2s .  c  o  m

    SecurityContextHolder.getContext().setAuthentication(authentication);

    for (String beanName : contactServices.keySet()) {
        Object object = this.beanFactory.getBean("&" + beanName);

        try {
            System.out.println("Trying to find setUsername(String) method on: " + object.getClass().getName());

            Method method = object.getClass().getMethod("setUsername", new Class[] { String.class });
            System.out.println("Found; Trying to setUsername(String) to " + authentication.getPrincipal());
            method.invoke(object, authentication.getPrincipal());
        } catch (NoSuchMethodException ignored) {
            System.out.println("This client proxy factory does not have a setUsername(String) method");
        } catch (IllegalAccessException ignored) {
            ignored.printStackTrace();
        } catch (InvocationTargetException ignored) {
            ignored.printStackTrace();
        }

        try {
            System.out.println("Trying to find setPassword(String) method on: " + object.getClass().getName());

            Method method = object.getClass().getMethod("setPassword", new Class[] { String.class });
            method.invoke(object, authentication.getCredentials());
            System.out.println("Found; Trying to setPassword(String) to " + authentication.getCredentials());
        } catch (NoSuchMethodException ignored) {
            System.out.println("This client proxy factory does not have a setPassword(String) method");
        } catch (IllegalAccessException ignored) {
        } catch (InvocationTargetException ignored) {
        }

        ContactService remoteContactService = contactServices.get(beanName);
        System.out.println("Calling ContactService '" + beanName + "'");

        stopWatch.start(beanName);

        List<Contact> contacts = null;

        for (int i = 0; i < nrOfCalls; i++) {
            contacts = remoteContactService.getAll();
        }

        stopWatch.stop();

        if (contacts.size() != 0) {
            for (Contact contact : contacts) {
                System.out.println("Contact: " + contact);
            }
        } else {
            System.out.println("No contacts found which this user has permission to");
        }

        System.out.println();
        System.out.println(stopWatch.prettyPrint());
    }

    SecurityContextHolder.clearContext();
}

From source file:com.ai.bss.webui.security.AiBssAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//  w w w.j a  v a 2s  .c o m
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        //            commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        e.printStackTrace();
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

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   w w  w.j  av  a2 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:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(//w w w .j a  v a  2  s. co  m
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:com.googlecode.fascinator.portal.security.filter.FascinatorAuthenticationInterceptorFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    JsonSessionState jsonSessionState = (JsonSessionState) request.getSession()
            .getAttribute("sso:com.googlecode.fascinator.portal.JsonSessionState");
    if (jsonSessionState != null) {
        PreAuthenticatedAuthenticationToken token = null;
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            if (jsonSessionState.get("username") != null) {
                token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password");
                SpringUser user = new SpringUser();
                user.setUsername((String) jsonSessionState.get("username"));
                user.setSource((String) jsonSessionState.get("source"));
                token.setDetails(user);//from w  w  w.  jav  a2  s .c o  m
            } else {
                if (request.getParameter("apiKey") != null
                        && apiClients.get(request.getParameter("apiKey")) != null) {
                    String username = apiClients.get(request.getParameter("apiKey"));
                    token = new PreAuthenticatedAuthenticationToken(username, "password");
                    jsonSessionState.set("username", username);
                    jsonSessionState.set("source", "internal");
                    SpringUser user = new SpringUser();
                    user.setUsername(username);
                    user.setSource("internal");
                    token.setDetails(user);
                }
            }

        } else if (jsonSessionState.get("username") != null
                && !authentication.getName().equals(jsonSessionState.get("username"))) {
            token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password");
            SpringUser user = new SpringUser();
            user.setUsername((String) jsonSessionState.get("username"));
            user.setSource((String) jsonSessionState.get("source"));
            token.setDetails(user);
        } else if (jsonSessionState.get("username") == null) {
            // must have logged out
            SecurityContextHolder.getContext().setAuthentication(null);
        }

        if (token != null) {
            // User has been logged in so let's create their credentials and
            // authenticate them
            authentication = authManager.authenticate(token);

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
        // SSO doesn't use a normal Roles plugin so we need to get the
        // roles again here and create a new token
        SpringUser user = (SpringUser) authentication.getCredentials();
        if (!user.isSsoRolesSet()) {
            List<GrantedAuthority> userRoles = buildRoleList(user, jsonSessionState);
            user.setSsoRolesSet(true);
            authentication = new PreAuthenticatedAuthenticationToken(user.getUsername(), user, userRoles);
            SecurityContextHolder.getContext().setAuthentication(authentication);

        }

    }
    filterChain.doFilter(request, response);

}

From source file:nl.strohalm.cyclos.webservices.rest.RestAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    // Get / validate the principal / credentials
    String principal = authentication.getName();
    String credentials = (String) authentication.getCredentials();
    if (StringUtils.isEmpty(principal) || StringUtils.isEmpty(credentials)) {
        sendError("Empty username / password", INVALID_CREDENTIALS);
        throw new InvalidCredentialsException();
    }// w  w  w.  jav  a  2s.c  o  m
    // Get the request
    HttpServletRequest request = WebServiceContext.getRequest();
    if (request == null) {
        sendError("Couldn't resolve the current request", UNKNOWN_AUTHENTICATION_ERROR);
        throw new IllegalStateException("Couldn't resolve the current request");
    }

    final String remoteAddr = request.getRemoteAddr();

    // Load the channel
    Channel channel = channelService.loadByInternalName(Channel.REST);
    final PrincipalType principalType = channelService.resolvePrincipalType(Channel.REST,
            channel.getDefaultPrincipalType().getPrincipal().name());

    // Validate the user
    String usernameToVerify = principal;
    Member member = null;
    try {
        member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                Element.Relationships.GROUP);
        usernameToVerify = member.getUsername();
    } catch (final EntityNotFoundException e) {
        usernameToVerify = "";
    }
    // Verify username
    try {
        accessService.verifyLogin(null, usernameToVerify, remoteAddr);
    } catch (UserNotFoundException e) {
        sendError("Invalid username / password", INVALID_CREDENTIALS);
        throw new InvalidCredentialsException();
    }

    // Check if the channel is enabled for the specific member
    if (!accessService.isChannelEnabledForMember(channel, member)) {
        sendError("Channel disabled for the member", CHANNEL_DISABLED);
        throw new InvalidChannelException(member.getUsername(), channel.getInternalName());
    }

    // Check the credentials
    try {
        accessService.checkCredentials(channel, member.getMemberUser(), credentials, remoteAddr, null);
    } catch (BlockedCredentialsException e) {
        sendError("Credentials blocked", BLOCKED_CREDENTIALS);
        throw e;
    } catch (CredentialsException e) {
        sendError("Invalid username / password", INVALID_CREDENTIALS);
        throw e;
    }

    // Initialize the LoggedUser, so it is accessible from the services
    WebServiceContext.setRestMember(member);
    LoggedUser.init(member.getUser(), remoteAddr);

    // Authentication succeeded
    Collection<SimpleGrantedAuthority> authority = Collections
            .singleton(new SimpleGrantedAuthority("ROLE_REST"));
    return new UsernamePasswordAuthenticationToken(principal, credentials, authority);
}

From source file:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

/**
 * Do not try to validate JWT if user already authenticated via other provider
 * @return true, if JWT validation required
 *///from w  ww .  j  ava 2 s. c om
private boolean isAuthenticationRequired(String token) {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

    //authenticate if no auth
    if (existingAuth == null || !existingAuth.isAuthenticated()) {
        return true;
    }

    //revalidate if token was changed
    if (existingAuth instanceof JwtAuthentication
            && !StringUtils.equals(token, (String) existingAuth.getCredentials())) {
        return true;
    }

    //always try to authenticate in case of anonymous user
    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}

From source file:org.apache.atlas.web.security.AtlasADAuthenticationProvider.java

private Authentication getADBindAuthentication(Authentication authentication) {
    try {//from w  ww  .  j  a v  a 2 s .  c o m
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(adURL);
        ldapContextSource.setUserDn(adBindDN);
        ldapContextSource.setPassword(adBindPassword);
        ldapContextSource.setReferral(adReferral);
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        if (adUserSearchFilter == null || adUserSearchFilter.trim().isEmpty()) {
            adUserSearchFilter = "(sAMAccountName={0})";
        }
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adBase, adUserSearchFilter,
                ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        bindAuthenticator.afterPropertiesSet();

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(
                bindAuthenticator);

        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);
            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            LOG.error("AD Authentication Failed userName or userPassword is null or empty");
            return null;
        }
    } catch (Exception e) {
        LOG.error("AD Authentication Failed:", e);
        return null;
    }
}

From source file:org.apache.atlas.web.security.AtlasADAuthenticationProvider.java

private Authentication getADAuthentication(Authentication authentication) {
    try {//from   w w w . j  a v a  2s . c  om
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(
                adDomain, adURL);
        adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
        adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);

        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);
            authentication = adAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            LOG.error("AD Authentication Failed userName or userPassword is null or empty");
            return null;
        }
    } catch (Exception e) {
        LOG.error("AD Authentication Failed:", e);
        return null;
    }
}

From source file:org.apache.atlas.web.security.AtlasLdapAuthenticationProvider.java

private Authentication getLdapBindAuthentication(Authentication authentication) {
    try {/* ww  w. ja  v a2s.c  o  m*/
        if (isDebugEnabled) {
            LOG.debug("==> AtlasLdapAuthenticationProvider getLdapBindAuthentication");
        }
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        LdapContextSource ldapContextSource = getLdapContextSource();

        DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = getDefaultLdapAuthoritiesPopulator(
                ldapContextSource);

        if (ldapUserSearchFilter == null || ldapUserSearchFilter.trim().isEmpty()) {
            ldapUserSearchFilter = "(uid={0})";
        }

        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(ldapBase, ldapUserSearchFilter,
                ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = getBindAuthenticator(userSearch, ldapContextSource);

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(
                bindAuthenticator, defaultLdapAuthoritiesPopulator);

        if (userName != null && userPassword != null && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,
                    userPassword, grantedAuths);
            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if (groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            LOG.error(
                    "LDAP Authentication::userName or userPassword is null or empty for userName " + userName);
        }
    } catch (Exception e) {
        LOG.error(" getLdapBindAuthentication LDAP Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasLdapAuthenticationProvider getLdapBindAuthentication");
    }
    return authentication;
}