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.mule.modules.basicauthsecurity.strategy.JDBCSecurityProvider.java

public void validate(String auth, List<String> acceptedRoles) throws UnauthorizedException {
    List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    for (String role : acceptedRoles) {
        list.add(new SimpleGrantedAuthority(role));
    }//from w  w w .jav  a 2s.  c o  m
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(getUser(auth),
            getPass(auth), list);
    Authentication authResult = providerManager.authenticate(authRequest);

    Boolean containsKey = false;
    for (GrantedAuthority grantedAuthority : authResult.getAuthorities()) {
        if (authRequest.getAuthorities().contains(grantedAuthority)) {
            containsKey = true;
        }
    }

    if (!containsKey) {
        throw new UnauthorizedException("result");
    }
    if (!authResult.isAuthenticated()) {
        throw new UnauthorizedException("result");
    }
}

From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }/*from   w  w  w.  j  a v a  2  s.c  o  m*/
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername((String) token.getPrincipal());
        UsernamePasswordAuthenticationToken newToken = new UsernamePasswordAuthenticationToken(
                token.getPrincipal(), token.getCredentials(), userDetails.getAuthorities());
        newToken.setDetails(token.getDetails());
        return newToken;
    }
    return null;
}

From source file:org.meruvian.yama.webapi.config.oauth.UserTokenConverter.java

public Authentication extractAuthentication(Map<String, ?> map) {
    if (map.containsKey(USERNAME) && map.containsKey(USER_ID)) {
        DefaultUserDetails details = new DefaultUserDetails((String) map.get(USERNAME), "N/A",
                getAuthorities(map));/*from   ww  w  . ja v a 2s . c  om*/
        details.setId((String) map.get(USER_ID));

        User user = new User();
        user.setId(details.getId());
        user.setUsername(details.getUsername());
        details.setUser(user);

        return new UsernamePasswordAuthenticationToken(details, details.getPassword(),
                details.getAuthorities());
    }

    return null;
}

From source file:sample.mvc.SignupController.java

@RequestMapping(method = RequestMethod.POST)
public String signup(@Valid User user, BindingResult result, RedirectAttributes redirect) {
    if (result.hasErrors()) {
        return "user/signup";
    }//w  ww.  j  a v  a2 s.  c  om
    user = userRepository.save(user);
    redirect.addFlashAttribute("globalMessage", "Successfully signed up");

    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getEmail(),
            user.getPassword(), authorities);
    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), authorities);
    SecurityContextHolder.getContext().setAuthentication(auth);
    return "redirect:/";
}

From source file:com.amediamanager.controller.UserController.java

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid NewUser newUser, BindingResult result, RedirectAttributes attr, ModelMap model) {

    try {/*from w  w  w  .j  a  v  a 2s.c  o  m*/
        if (result.hasErrors()) {
            model.addAttribute("templateName", "welcome");
            return "base";
        }

        userService.save(newUser);
        User user = userService.find(newUser.getEmail());

        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

        // Authenticate the user
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getEmail(),
                null, grantedAuths);

        // Save user in session
        auth.setDetails(user);

        SecurityContextHolder.getContext().setAuthentication(auth);
    } catch (UserExistsException e) {
        attr.addFlashAttribute("error", "That user already exists.");
        LOG.info("User already exists.", e);
    }

    return "redirect:/welcome";
}

From source file:com.example.oauth1.loginconsumer.OAuthAuthenticationProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    String username = restTemplate.getForObject(userInfoUrl, String.class);
    List<GrantedAuthority> authorities = Arrays
            .<GrantedAuthority>asList(new SimpleGrantedAuthority("ROLE_USER"));
    return new UsernamePasswordAuthenticationToken(username, null, authorities);
}

From source file:nz.net.orcon.kanban.security.JcrAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authIn) throws AuthenticationException {

    String username = authIn.getName();
    String password = authIn.getCredentials().toString();

    logger.info("Authenticated Request - user: " + username);

    ObjectContentManager ocm = null;//from ww  w.  ja  v  a2 s.c o m

    try {
        ocm = ocmFactory.getOcm();

        User user = (User) ocm.getObject(User.class, String.format(URI.USER_URI, username));
        if (user != null && user.checkPassword(password)) {
            logger.info("Authenticated User: " + username);
            List<GrantedAuthority> grantedAuths = this.securityTool.getRoles(username);
            Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
            return auth;
        } else {
            logger.warn("Authentication Failure: " + username);
        }
    } catch (Exception e) {
        logger.error("Authentication Exception: " + username, e);
    } finally {
        if (ocm != null) {
            ocm.logout();
        }
    }

    return null;
}

From source file:org.openmrs.contrib.metadatarepository.service.impl.UserSecurityAdviceTest.java

@Before
public void setUp() throws Exception {
    // store initial security context for later restoration
    initialSecurityContext = SecurityContextHolder.getContext();

    SecurityContext context = new SecurityContextImpl();
    User user = new User("user");
    user.setId(1L);//from   w  w  w  . j a  v a 2s  .c  o m
    user.setPassword("password");
    user.addRole(new Role(Constants.USER_ROLE));

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
}

From source file:de.thm.arsnova.services.QuestionServiceTest.java

private void setAuthenticated(final boolean isAuthenticated, final String username) {
    if (isAuthenticated) {
        final List<GrantedAuthority> ga = new ArrayList<GrantedAuthority>();
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,
                "secret", ga);
        SecurityContextHolder.getContext().setAuthentication(token);
        userService.setUserAuthenticated(isAuthenticated, username);
    } else {/*w w w . j a v  a2s  .  co  m*/
        userService.setUserAuthenticated(isAuthenticated);
    }
}

From source file:org.jtalks.jcommune.service.nontransactional.SecurityServiceImpl.java

/**
 * {@inheritDoc}/*from  ww  w.j a  v  a 2  s  . c  o m*/
 */
@Override
public void authenticateUser(User user) {
    securityContextFacade.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities()));
}