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

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

Introduction

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

Prototype

public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
        Collection<? extends GrantedAuthority> authorities) 

Source Link

Document

This constructor should only be used by AuthenticationManager or AuthenticationProvider implementations that are satisfied with producing a trusted (i.e.

Usage

From source file:org.dspace.rest.authentication.DSpaceAuthenticationProvider.java

private Authentication createAuthenticationToken(final String password, final Context context,
        final List<SimpleGrantedAuthority> grantedAuthorities) {
    EPerson ePerson = context.getCurrentUser();
    if (ePerson != null && StringUtils.isNotBlank(ePerson.getEmail())) {
        return new UsernamePasswordAuthenticationToken(ePerson.getEmail(), password, grantedAuthorities);

    } else {/*from   w  w w  . j  av  a 2 s  .c om*/
        log.info(LogManager.getHeader(context, "failed_login",
                "No eperson with an non-blank e-mail address found"));
        throw new BadCredentialsException("Login failed");
    }
}

From source file:uk.org.rbc1b.roms.scheduled.ProjectAvailabilityEmailScheduledService.java

/**
 * Checks volunteers to whom confirmed dates can be sent by email.
 */// w w  w  .j  a  va  2  s. c  om
//@Scheduled(cron = "0 0/5 * * * ?")
@Scheduled(cron = "0 40 * * * ?")
public void checkConfirmationDates() {
    UserDetails system = userDetailsService.loadUserByUsername("System");
    Authentication authentication = new UsernamePasswordAuthenticationToken(system, system.getUsername(),
            system.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
    List<ProjectAvailability> projectAvailabilityList = projectAvailabilityDao.findUnconfirmedVolunteers();
    if (projectAvailabilityList.isEmpty()) {
        return;
    }
    for (ProjectAvailability projectAvailability : projectAvailabilityList) {
        try {
            Email email = projectAvailabilityEmailGenerator
                    .generateVolunteerAvailabilityConfirmationEmail(projectAvailability);
            if (email == null) {
                LOGGER.error("Cannot send email to RBC ID:" + projectAvailability.getPerson().getPersonId());

            } else {
                emailDao.save(email);
                projectAvailability.setConfirmationEmail(true);
                projectAvailabilityDao.update(projectAvailability);
            }
        } catch (IOException | TemplateException e) {
            LOGGER.error("Failed to send confirmation email:", e);
        }
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    final boolean debug = logger.isDebugEnabled();

    String userIdentifier = request.getHeader(SPI_HEADER);

    if (userIdentifier == null) {
        chain.doFilter(request, response);
        return;/*from ww  w.ja v a2  s.  co  m*/
    }

    try {
        SocialUser socialUser = getRegisteredUser(userIdentifier);
        if (socialUser == null) {
            response.setHeader(MUST_REGISTER_HEADER, request.getHeader(SPI_HEADER));
            chain.doFilter(request, response);
            return;
        }

        if (authenticationIsRequired(socialUser.getUserId())) {
            User registeredUser = communityService.findOne(socialUser.getUserId());

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    registeredUser, registeredUser.getPassword(), registeredUser.getAuthorities());
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);
            rememberMeServices.loginSuccess(request, response, authResult);
            onSuccessfulAuthentication(request, response, authResult);
        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        rememberMeServices.loginFail(request, response);

        onUnsuccessfulAuthentication(request, response, failed);

        if (ignoreFailure) {
            chain.doFilter(request, response);
        }
        return;
    }

    chain.doFilter(request, response);
}

From source file:org.carewebframework.security.spring.AbstractAuthenticationProvider.java

/**
 * Authentication Provider. Produces a trusted <code>UsernamePasswordAuthenticationToken</code>
 * if/*from   w  ww .  j a v  a  2s .co  m*/
 * 
 * @param authentication The authentication context.
 * @return authentication Authentication object if authentication succeeded. Null if not.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails();
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    String domain = null;

    if (log.isDebugEnabled()) {
        log.debug("User: " + username);
        log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress());
    }

    if (username != null) {
        String pcs[] = username.split("\\\\", 2);
        domain = pcs[0];
        username = pcs.length > 1 ? pcs[1] : null;
    }

    ISecurityDomain securityDomain = domain == null ? null
            : SecurityUtil.getSecurityService().getSecurityDomain(domain);

    if (username == null || password == null || securityDomain == null) {
        throw new BadCredentialsException("Missing security credentials.");
    }

    IUser user = authenticate(username, password, securityDomain, details);
    details.setDetail("user", user);
    List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
    List<String> list = getAuthorities(user);
    Set<String> authorities = list == null ? new HashSet<String>() : new HashSet<String>(list);

    for (String grantedAuthority : grantedAuthorities) {
        if (grantedAuthority.startsWith("-")) {
            authorities.remove(grantedAuthority.substring(1));
        } else {
            authorities.add(grantedAuthority);
        }
    }

    for (String authority : authorities) {
        if (!authority.isEmpty()) {
            userAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }

    User principal = new User(username, password, true, true, true, true, userAuthorities);

    authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
            principal.getAuthorities());
    ((UsernamePasswordAuthenticationToken) authentication).setDetails(details);
    return authentication;
}

From source file:oauth2.authentication.UserAuthenticationProvider.java

protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
        Collection<GrantedAuthority> authorities) {

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal,
            authentication.getCredentials(), authorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:net.seedboxer.web.security.AuthenticationAPIKeyFilter.java

private Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) {
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user,
            user.getPassword(), user.getAuthorities());

    authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

    return authRequest;
}

From source file:org.osiam.auth.login.ldap.OsiamLdapAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    Preconditions.checkArgument(authentication instanceof OsiamLdapAuthentication,
            "OsiamLdapAuthenticationProvider only supports OsiamLdapAuthentication.");

    final OsiamLdapAuthentication userToken = (OsiamLdapAuthentication) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (Strings.isNullOrEmpty(username)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Username");
    }// ww  w. j a  v a2  s.c o  m

    if (Strings.isNullOrEmpty(password)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Password");
    }

    User user = resourceServerConnector.getUserByUsername(username);
    checkIfInternalUserExists(user);

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails ldapUser = osiamLdapUserContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    user = synchronizeLdapData(userData, user);

    User authUser = new User.Builder(username).setId(user.getId()).build();

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authUser, null,
            grantedAuthorities);
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityContextLoader.java

/**
 * This method does all the heavy work in retrieving the context out of Redis. It inspects the servlet request
 * and tries to scrape the authentication token out of a header. If the header is missing or the token is not
 * found, an empty {@link SecurityContext} is returned, effectively telling Spring that the current request is
 * coming from an anonymous, unauthenticated actor.
 *
 * @param requestResponseHolder the request container
 * @return a security context/*from   w  ww .  jav  a2s. c o m*/
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    String tokenParam = coalesce(request.getHeader(SessionConstant.AUTH_TOKEN_HEADER),
            request.getParameter(SessionConstant.AUTH_TOKEN_PARAM));

    SecurityContext securityContext = new SecurityContextImpl();

    if (tokenParam == null || !redisService.exists(tokenParam)) {
        return securityContext;
    }

    String serializedAuthData = redisService.get(tokenParam);
    AuthenticationDTO dto;

    try {
        dto = new ObjectMapper().readValue(serializedAuthData, AuthenticationDTO.class);
    } catch (IOException e) {
        LOGGER.error("Error deserializing auth DTO", e);
        return securityContext;
    }

    Account account = accountDao.findByEmail(dto.getEmail());

    Collection<GrantedAuthority> gal = Collections.singletonList(new SimpleGrantedAuthority(dto.getRole()));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(account.getId(), null,
            gal);
    token.setDetails(dto.getCsrf());

    securityContext.setAuthentication(token);

    return securityContext;
}

From source file:org.xaloon.wicket.security.spring.external.ExternalAuthenticationProvider.java

private Authentication createExternalAuthenticationToken(Authentication authentication,
        AuthenticationToken initialToken) {
    User user = userDao.newUser();// ww w .  j av  a 2s .c om
    user.setUsername(authentication.getName());
    user.setExternal(true);
    externalParameterResolver.resolve(initialToken, user);

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(SecurityAuthorities.AUTHENTICATED_USER));

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    result.setDetails(user);
    return result;
}