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.meruvian.yama.web.DefaultCredentialsService.java

@Override
public void registerAuthentication(String userId, HttpServletRequest request) {
    User user = userRepository.findById(userId);
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());

    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null,
            userDetails.getAuthorities());
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);

    HttpSession session = request.getSession(true);
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}

From source file:fr.univrouen.poste.web.ProfilChoiceController.java

@RequestMapping
public String profilChoice(@RequestParam(required = false) String profil) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities());

    if (profil != null) {
        logger.info(auth.getName() + " a slectionn le profil " + profil);
        if ("membre".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_CANDIDAT"));
        }/* ww w  . j  a v  a 2 s  .  c o  m*/
        if ("candidat".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_MEMBRE"));
        }
        auth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    if (auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT"))
            && auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"))) {
        return "profilChoice";
    } else {
        return "index";
    }
}

From source file:com.himanshu.poc.springbootsec.security.AuthenticationProviderImpl.java

@Override
public Authentication authenticate(Authentication arg0) throws AuthenticationException {
    logger.info(" User name is : " + arg0.getName());
    if (arg0.getName() == null || arg0.getName().isEmpty()) {
        //Token Based Authentication required
        logger.info("Since username is null or empty, hence token based authentication will be required");
        String tokenStr = (String) arg0.getCredentials();
        String userName = tokenKeeperService.queryUserByToken(tokenStr);

        UserDO user = userDao.getUserByUserName(userName);
        logger.info("Auth success");
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getPrincipal(),
                user.getCredentials(), user.getAuthorities());
        return token;

    } else {//from  w w w  .j  a  v  a2s.  com
        //Normal Authentication
        logger.info(
                "Since username is NOT null, hence username/password based authentication will be required");
        UserDO user = userDao.getUserByUserName(arg0.getName());

        if (user != null && user.getCredentials().equals(arg0.getCredentials())) {
            logger.info("Auth success");
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                    user.getPrincipal(), user.getCredentials(), user.getAuthorities());
            return token;
        }
    }

    logger.error("Auth failed");
    return null;
}

From source file:com.launchkey.example.springmvc.LaunchKeyAuthenticationProvider.java

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

    try {//  ww w .j a  v  a2s.c  o m
        this.authManager.login(username);
        Boolean authorized = null;
        while (authorized == null) {
            Thread.sleep(100L);
            authorized = this.authManager.isAuthorized();
        }
        if (authorized == null) {
            throw new InsufficientAuthenticationException(
                    "The authentication request was not responded to in sufficient time");
        } else if (!authorized) {
            throw new InsufficientAuthenticationException("The authentication request was denied");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Sleep error");
    } catch (AuthManager.AuthException e) {
        if (e.getCause() instanceof LaunchKeyException) {
            throw new BadCredentialsException("Authentication failure", e.getCause());
        }
    }

    return new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(),
            new ArrayList<GrantedAuthority>());
}

From source file:dubbo.spring.javaconfig.CurrentUserFilter.java

@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    String currentUserId = RpcContext.getContext().getAttachment("currentUserId");
    if (StringUtilsPlus.isNotEmpty(currentUserId)) {
        BackendUser user = backendUserRepo.findOne(Long.parseLong(currentUserId));
        LoginUserInfo currentUser = new LoginUserInfo();
        currentUser.setId(Long.parseLong(currentUserId));
        Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, StringUtilsPlus.EMPTY,
                new ArrayList<SimpleGrantedAuthority>());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }/*from  w  w  w  . ja  v a 2 s  . c o m*/
    return invoker.invoke(invocation);
}

From source file:com.seyren.core.security.mongo.MongoAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    User user = userStore.getUser(authentication.getName());
    if (user == null) {
        throw new AuthenticationCredentialsNotFoundException("User does not exist");
    }/* w  w  w  .  java  2s. c  o m*/
    String password = authentication.getCredentials().toString();
    if (passwordEncoder.matches(password, user.getPassword())) {
        return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                user.getAuthorities());
    } else {
        throw new BadCredentialsException("Bad Credentials");
    }
}

From source file:com.exp.tracker.services.impl.GroupServiceImplTests.java

@Test
public void groupServiceTests() {
    userDetailService = ctx.getBean(JdbcDaoImpl.class);
    UserDetails userDetails = userDetailService.loadUserByUsername("Admin");
    Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authToken);
    rCtx = new MockRequestContext();
    MockExternalContext ec = new MockExternalContext();
    ec.setCurrentUser("Admin");
    ((MockRequestContext) rCtx).setExternalContext(ec);

    // This test runs with two groups already setup in the embedded test db

    // get all groups
    Collection<GroupBean> groups = groupService.getGroups();
    Assert.assertNotNull("Expected a non null group list", groups);
    Assert.assertTrue("Expected exactly two groups", groups.size() == 2);

    // Add a group
    GroupBean gb = new GroupBean();
    gb.setActive(true);/* w  ww .  java 2  s .co  m*/
    gb.setGroupDescription("Test Description");
    gb.setGroupName("Test group name");
    gb.setUsers(null);
    GroupBean retGb = groupService.addGroup(gb);
    Assert.assertNotNull("Failed to create group", retGb);
    groups = groupService.getGroups();
    Assert.assertTrue("Expected exactly three groups", groups.size() == 3);
    //
    validationService.checkGroupCreationResult(retGb, rCtx);
    Message[] msgs = rCtx.getMessageContext().getAllMessages();
    Assert.assertTrue("Expected one message", msgs.length == 1);
    Message msg = msgs[0];
    Assert.assertTrue("Expected a success message", "Your group was created succesfuly.".equals(msg.getText()));
    // clear this message
    rCtx.getMessageContext().clearMessages();
    // now try adding group again with same name
    retGb = groupService.addGroup(gb);
    Assert.assertNull("Should have failed to create group", retGb);
    validationService.checkGroupCreationResult(retGb, rCtx);
    msgs = rCtx.getMessageContext().getAllMessages();
    Assert.assertTrue("Expected one message", msgs.length == 1);
    msg = msgs[0];
    Assert.assertTrue("Expected a failure message", "Failed to create group.".equals(msg.getText()));
}

From source file:com.seajas.search.utilities.spring.security.service.ExtendedAuthenticationProvider.java

/**
 * Override the authenticate method to provide our own extended UserDetails based logic.
 * /*from   w w  w  .j a va2  s.com*/
 * @param authentication
 * @throws AuthenticationException
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (StringUtils.isEmpty((String) authentication.getPrincipal())
            || StringUtils.isEmpty((String) authentication.getCredentials()))
        throw new BadCredentialsException("The given username / password are invalid");

    UserDetails userDetails = extendedUserDetailsService.getUserDetails((String) authentication.getPrincipal(),
            (String) authentication.getCredentials());

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

From source file:com.hp.autonomy.frontend.configuration.authentication.SingleUserAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final com.hp.autonomy.frontend.configuration.authentication.Authentication<?> configAuthentication = configService
            .getConfig().getAuthentication();

    if (!(configAuthentication instanceof SingleUserAuthentication)
            || LoginTypes.DEFAULT.equalsIgnoreCase(configAuthentication.getMethod())) {
        return null;
    }// w w  w . j  ava 2  s .  c om

    final SingleUserAuthentication singleUserAuthentication = (SingleUserAuthentication) configAuthentication;
    final BCryptUsernameAndPassword singleUser = singleUserAuthentication.getSingleUser();

    final String username = singleUser.getUsername();
    final String hashedPassword = singleUser.getHashedPassword();
    final String providedPassword = authentication.getCredentials().toString();

    if (authentication.getName().equals(username) && BCrypt.checkpw(providedPassword, hashedPassword)) {
        return new UsernamePasswordAuthenticationToken(username, providedPassword,
                Arrays.asList(new SimpleGrantedAuthority(roleAdmin)));
    } else {
        throw new BadCredentialsException("Bad credentials");
    }
}

From source file:com.ram.topup.api.ws.security.filter.AuthenticationTokenProcessingFilter.java

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

    if (!(request instanceof HttpServletRequest)) {
        throw new RuntimeException("Expecting a HTTP request");
    }/*  www  .j a  v a  2 s. c om*/

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader("X-Auth-Token");

    String userName = TokenUtils.getUserNameFromToken(authToken);

    if (userName != null) {
        UserDetails userDetails = this.userService.loadUserByUsername(userName);
        if (TokenUtils.validateToken(authToken, userDetails.getUsername(), userDetails.getPassword())) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}