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:com.devicehive.auth.rest.providers.BasicAuthenticationProvider.java

@SuppressWarnings("unchecked")
@Override//from   w  w w  .  j  a  v  a  2 s  .c  o m
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String key = (String) authentication.getPrincipal();
    String pass = (String) authentication.getCredentials();
    logger.debug("Basic authentication requested for username {}", key);

    UserVO user = null;
    try {
        user = userService.authenticate(key, pass);
    } catch (HiveException e) {
        logger.error("User auth failed", e);
    }
    if (user != null && user.getStatus() == UserStatus.ACTIVE) {
        String role = user.isAdmin() ? HiveRoles.ADMIN : HiveRoles.CLIENT;
        logger.info("User {} authenticated with role {}", key, role);

        HivePrincipal principal = new HivePrincipal(user);

        if (user.isAdmin()) {
            Set<String> allActions = AvailableActions.getAllActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            allActions.forEach(action -> allowedActions.add(HiveAction.fromString(action)));
            principal.setActions(allowedActions);
        } else {
            String[] actions = AvailableActions.getClientActions();
            Set<HiveAction> allowedActions = new HashSet<>();
            for (String action : actions)
                allowedActions.add(HiveAction.fromString(action));
            principal.setActions(allowedActions);
        }

        return new HiveAuthentication(principal, AuthorityUtils.createAuthorityList(role));

    }
    logger.warn("Basic auth for {} failed", key);
    throw new BadCredentialsException("Invalid credentials");
}

From source file:com.climate.oada.security.oauth.CustomUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {

    LOG.info("Going to process authentication: " + authentication);
    if (authentication != null && authentication.getPrincipal() != null
            && authentication.getCredentials() != null) {

        LOG.info("authentication principal: " + authentication.getPrincipal());
        LOG.info("authentication credentials: " + authentication.getCredentials());

        /*//w w w  .  j a v  a 2s  .  co  m
         * authentication.getPrincipal() <=> userName
         * authentication.getCredentials() <=> password
         */
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
        return auth;
    }
    throw new BadCredentialsException("Invalid User Credentials");
}

From source file:org.exoplatform.acceptance.security.CrowdAuthenticationProviderWrapper.java

/**
 * {@inheritDoc}//from   w  w  w.j  av a 2 s. c om
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication crowdAuthentication = crowdAuthenticationProvider.authenticate(authentication);
    return new UsernamePasswordAuthenticationToken(crowdAuthentication.getPrincipal(),
            crowdAuthentication.getCredentials(),
            grantedAuthoritiesMapper.mapAuthorities(crowdAuthentication.getAuthorities()));
}

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.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.set("username", username);
    parameters.set("password", password);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class);

    if (response.getStatusCode() == HttpStatus.OK) {
        String userFromUaa = (String) response.getBody().get("username");

        if (userFromUaa.equals(userFromUaa)) {
            logger.info("Successful authentication request for " + authentication.getName());
            return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES);
        }/*  w  ww . j a  v a  2  s. c  o m*/
    } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("Failed authentication request");
        throw new BadCredentialsException("Authentication failed");
    } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
        logger.info("Internal error from UAA. Please Check the UAA logs.");
    } else {
        logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA."
                + " Is a compatible version running?");
    }
    throw new RuntimeException("Could not authenticate with remote server");
}

From source file:net.firejack.platform.web.security.spring.AuthenticationManager.java

protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() == null || authentication.getCredentials() == null
            || authentication.getDetails() == null) {
        String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
        throw new BadCredentialsException(errorMessage);
    }//from  w  w w  .ja v a  2  s.c o m

    String userName = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();
    HttpSession session = ((AuthenticationToken) authentication).getSession();

    if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
        if (!getAuthenticators().isEmpty()) {
            AuthenticatorFactory authenticatorFactory = AuthenticatorFactory.getInstance();
            IAuthenticationSource authenticationSource = authenticatorFactory
                    .provideDefaultAuthenticationSource(userName, password);
            for (IAuthenticator authenticator : getAuthenticators()) {
                IAuthenticationDetails authenticationDetails = authenticator.authenticate(authenticationSource);
                if (authenticationDetails != null) {
                    return generateDefaultToken(authenticationDetails, session);
                }
            }
        }
    }

    String errorMessage = MessageResolver.messageFormatting("login.authentication.failure", null);
    throw new BadCredentialsException(errorMessage);
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFactory.java

public Authentication updateAuthenticationForNewProvider(Authentication existingAuthentication,
        String providerId) {//from w  ww  . jav  a 2  s.  c o m
    return createNewAuthentication(existingAuthentication.getName(),
            existingAuthentication.getCredentials() == null ? null
                    : existingAuthentication.getCredentials().toString(),
            addAuthority(existingAuthentication, userAuthoritiesService.getProviderAuthority(providerId)));
}

From source file:org.keycloak.adapters.springsecurity.authentication.DirectAccessGrantAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = resolveUsername(authentication.getPrincipal());
    String password = (String) authentication.getCredentials();
    RefreshableKeycloakSecurityContext context;
    KeycloakAuthenticationToken token;//from   w ww  .  j  a  v a2 s .  c  o m
    Collection<? extends GrantedAuthority> authorities;

    try {
        context = directAccessGrantService.login(username, password);
        authorities = KeycloakSpringAdapterUtils.createGrantedAuthorities(context, grantedAuthoritiesMapper);
        token = new KeycloakAuthenticationToken(
                KeycloakSpringAdapterUtils.createAccount(keycloakDeployment, context), authorities);
    } catch (VerificationException e) {
        throw new BadCredentialsException("Unable to validate token", e);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Error authenticating with Keycloak server", e);
    }

    return token;
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFactory.java

public Authentication updateAuthenticationForNewConnection(Authentication existingAuthentication,
        Connection<?> connection) {
    return createNewAuthentication(existingAuthentication.getName(),
            existingAuthentication.getCredentials() == null ? null
                    : existingAuthentication.getCredentials().toString(),
            addAuthority(existingAuthentication,
                    userAuthoritiesService.getProviderAuthority(connection.getKey())));
}

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilterTest.java

private AuthenticationManager mockAuthentication(String credentials) {
    AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
    Authentication resultAuthentication = mock(Authentication.class);
    when(resultAuthentication.getCredentials()).thenReturn(credentials);
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(resultAuthentication);
    return authenticationManager;
}