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:cz.muni.pa165.carparkapp.configuration.MyAuthenticationProvider.java

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

    password = DigestUtils.shaHex(password);
    Employee user = null;/*from www  .jav a  2 s . c o m*/

    for (Employee e : dao.getAllEmployees()) {
        //System.out.println(e);
        if (e.getUserName().equals(username)) {
            user = e;
            break;
        }
    }

    if (user == null) {
        throw new BadCredentialsException("Username not found.");
    }

    if (!password.equals(user.getPassword())) {
        throw new BadCredentialsException("Wrong password.");
    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));

    return new UsernamePasswordAuthenticationToken(username, password, authorities);
}

From source file:ru.codemine.ccms.api.security.ApiAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse responce = (HttpServletResponse) resp;
    HttpServletRequest request = (HttpServletRequest) req;

    String authToken = request.getHeader("X-Auth-Token");
    String username = apiTokenUtils.getUsernameFromToken(authToken);

    if (username != null) {
        Employee employee = employeeService.getByUsername(username);
        if (apiTokenUtils.validateToken(authToken, employee)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    employee, null, employee.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }//from   w  w w.j  a  v  a2  s  .c  o m
    }

    chain.doFilter(req, resp);
}

From source file:com.sg.rest.security.components.WebTokenProcessingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String sToken = this.extractAuthTokenFromRequest(httpRequest);
    if (sToken != null) {

        long accountId = securityService.getAccountIdAndVerifyToken(sToken);
        GetAccountRolesOperation dto = new GetAccountRolesOperation(accountId);
        GetAccountRolesResponse rolesDto = handler.handle(dto);
        if (rolesDto.getStatus() == GetAccountRolesStatus.STATUS_ACCOUNT_NOT_FOUND) {
            throw new WebSecurityAccountNotFoundException(accountId);
        }//w  w w.j  av a  2 s  .  com

        SgRestUser userPrincipal = new SgRestUser(accountId);
        userPrincipal.setRoles(rolesDto.getData().getRoles());

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                userPrincipal, null, userPrincipal.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    chain.doFilter(request, response);
}

From source file:ph.fingra.statisticsweb.service.MemberServiceImpl.java

public void update(Member member) {
    if (!StringUtils.isEmpty(member.getPassword())) {
        member.setPassword(passwordEncoder.encode(member.getPassword()));
    }//w  w w . ja va 2s  .co m
    memberDao.update(member);
    UserDetails newPrincipal = new FingraphUser(get(member.getMemberid()));
    Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(newPrincipal,
            currentAuth.getCredentials(), newPrincipal.getAuthorities());
    newAuth.setDetails(currentAuth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

From source file:org.createnet.raptor.auth.service.services.BrokerMessageHandler.java

public void handle(Message<?> message) {

    System.out.println(message.getPayload());
    JsonNode json;//www.j a  v a2  s.c o m
    try {
        json = mapper.readTree(message.getPayload().toString());
    } catch (IOException ex) {
        throw new MessagingException("Cannot convert JSON payload: " + message.getPayload().toString());
    }

    switch (json.get("type").asText()) {
    case "object":

        User user = userService.getByUuid(json.get("userId").asText());
        UserDetails details = new RaptorUserDetailsService.RaptorUserDetails(user);
        final Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(),
                user.getPassword(), details.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        SyncRequest req = new SyncRequest();
        req.userId = user.getUuid();
        req.operation = json.get("op").asText();
        req.objectId = json.get("object").get("id").asText();
        req.created = json.get("object").get("createdAt").asLong();

        deviceService.sync(user, req);

        SecurityContextHolder.getContext().setAuthentication(null);
        break;
    case "data":
        StreamPayload data = mapper.convertValue(json, StreamPayload.class);
        break;
    case "action":
        ActionPayload action = mapper.convertValue(json, ActionPayload.class);
        break;
    case "user":
        // TODO: Add event notification in auth service
        break;
    }

}

From source file:com.github.cherimojava.orchidae.security.MongoAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    LOG.info(AUTH, "login attempt for user {}", authentication.getName());
    UserDetails details = userDetailsService.loadUserByUsername((String) authentication.getPrincipal());

    if (details == null
            || !pwEncoder.matches((String) authentication.getCredentials(), details.getPassword())) {
        LOG.info(AUTH, "failed to authenticate user {}", authentication.getName());
        throw new BadCredentialsException(ERROR_MSG);
    }//from  ww w .jav  a 2 s .  c  o m

    LOG.info(AUTH, "login attempt for user {}", authentication.getName());

    return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), details.getAuthorities());
}

From source file:com.lixiaocong.social.SignInUtil.java

@Override
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
    UserDetails user = userDetailsService.loadUserByUsername(localUserId);

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,
            user.getPassword(), user.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    return "/";
}

From source file:be.bittich.quote.security.AuthenticationTokenProcessingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);

    String authToken = extractAuthTokenFromRequest(httpRequest);

    String username = tokenService.getUsernameFromToken(authToken);

    if (username != null) {

        UserDetails userDetails = this.userService.loadUserByUsername(username);

        if (tokenService.validateToken(authToken, request.getRemoteAddr(), userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }//  w  w  w  . j  a  va 2s . co  m
    }

    chain.doFilter(request, response);
}

From source file:com.jevontech.wabl.security.AuthenticationTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    //log.debug("doFilter");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    String username = this.tokenUtils.getUsernameFromToken(authToken);

    log.debug("doFilter: this.tokenHeader=" + this.tokenHeader);

    log.debug("doFilter: authToken=" + authToken + " , username=" + username);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        log.debug("doFilter: userDetails=" + userDetails.toString());
        if (this.tokenUtils.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }/*from w  w  w  .  jav  a  2s  .c  om*/
    }

    chain.doFilter(request, response);
}

From source file:com.javaeeeee.components.JpaAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(),
            authentication.getCredentials().toString());
    if (optional.isPresent()) {
        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());

    } else {/*from w  w w.  j a  v a 2 s .co  m*/
        throw new AuthenticationCredentialsNotFoundException("Wrong credentials.");
    }
}