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:br.com.joaops.smt.security.SmtAuthenticationProvider.java

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

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

    if (user == null) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }//from w w  w.  ja  v a 2s  . co m

    if (!user.getUsername().equals(username)) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (!passwordEncoder.matches(password, user.getPassword())) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (user.isEnabled() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",
                "AbstractUserDetailsAuthenticationProvider.disabled");
        throw new DisabledException(message);
    }

    if (user.isAccountNonLocked() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "AbstractUserDetailsAuthenticationProvider.locked");
        throw new LockedException(message);
    }

    if (user.isAccountNonExpired() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",
                "AbstractUserDetailsAuthenticationProvider.expired");
        throw new AccountExpiredException(message);
    }

    if (user.isCredentialsNonExpired() == false) {
        String message = this.messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired");
        throw new CredentialsExpiredException(message);
    }

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

From source file:com.mec.Services.JWTService.java

public Authentication getAuthentication(HttpServletRequest request) {
    //System.out.println("TokenAuthenticationService getAuth");
    String token = request.getHeader(HEADER_STRING);
    if (token != null) {
        try {/*from   ww w . j a va  2s.  c o  m*/
            DecodedJWT jwt = verifier.verify(token.replace(TOKEN_PREFIX, "").trim());
            try {
                return jwt.getSubject() != null ? new UsernamePasswordAuthenticationToken(jwt.getSubject(), "",
                        userDAO.getUserRoles(Integer.valueOf(jwt.getSubject().split(";")[0]))) : null;
            } catch (UsernameNotFoundException e) {
                System.out.println("TokenAuth Username not found - null");
                throw new UsernameNotFoundException("Username not found");
            }
        } catch (JWTVerificationException exception) {
            System.out.println("JWTVerificationException " + exception.toString());
            throw new JWTVerificationException(exception.toString());
        }
    }
    return null;
}

From source file:com.lixiaocong.controller.SignController.java

@RequestMapping(value = "/singup", method = RequestMethod.POST)
public ModelAndView post(@Valid UserSignUpForm user, BindingResult result, WebRequest request)
        throws ControllerParamException {
    if (result.hasErrors())
        throw new ControllerParamException();

    try {/*from   ww  w  .  j a va2  s. c  o  m*/
        User localUser = userService.create(user.getUsername(), encoder.encode(user.getPassword()));
        providerSignInUtils.doPostSignUp(user.getUsername(), request);

        UserDetails userDetails = userDetailsService.loadUserByUsername(localUser.getUsername());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return new ModelAndView("/");
    } catch (Exception e) {
        ModelAndView ret = new ModelAndView("sign/signup");
        ret.addObject("message", ",???");
        return ret;
    }
}

From source file:org.cloudfoundry.identity.uaa.login.ChangePasswordControllerTest.java

private void setupSecurityContext() {
    Authentication authentication = new UsernamePasswordAuthenticationToken("bob", "secret",
            Arrays.asList(UaaAuthority.UAA_USER));

    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:net.gplatform.sudoor.server.security.model.auth.SSAuth.java

/**
 * WARNING: Normally this is used by non-web interface. For web interface,
 * pls use Spring Security config to auto authenticate Here there is no
 * authenticate/*w  ww.  j av  a  2s  .c o m*/
 * 
 * @param username
 * @param password
 */
public void signin(String username, String password) {
    logger.debug("signin:" + username);

    Authentication request = new UsernamePasswordAuthenticationToken(username, password, null);
    SecurityContextHolder.getContext().setAuthentication(request);
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilter.java

/**
 * Copy the original authentication, but use the restricted set of authorities. Keep special token
 * classes, like Anonymous, RememberMe, etc. .
 *//*w  ww. j  av  a  2s  . c om*/
private AbstractAuthenticationToken copy(final Authentication authentication,
        final Set<GrantedAuthority> restricted) {
    final AbstractAuthenticationToken replacement;
    if (authentication instanceof AnonymousAuthenticationToken) {
        replacement = new AnonymousAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof RememberMeAuthenticationToken) {
        replacement = new RememberMeAuthenticationToken("dummy-key", authentication.getPrincipal(), restricted);
    } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        replacement = new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    } else {
        replacement = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), restricted);
    }
    return replacement;
}

From source file:com.hack23.cia.service.impl.action.application.LoginService.java

@Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" })
@Override/*from w w  w. j  a v  a  2 s.  c om*/
public LoginResponse processService(final LoginRequest serviceRequest) {

    final CreateApplicationEventRequest eventRequest = new CreateApplicationEventRequest();
    eventRequest.setEventGroup(ApplicationEventGroup.USER);
    eventRequest.setApplicationOperation(ApplicationOperationType.AUTHENTICATION);
    eventRequest.setActionName(LoginRequest.class.getSimpleName());
    eventRequest.setSessionId(serviceRequest.getSessionId());
    eventRequest.setElementId(serviceRequest.getEmail());

    final UserAccount userExist = userDAO.findFirstByProperty(UserAccount_.email, serviceRequest.getEmail());

    LoginResponse response;
    if (userExist != null && verifyOtp(serviceRequest, userExist) && passwordEncoder.matches(
            userExist.getUserId() + ".uuid" + serviceRequest.getUserpassword(), userExist.getUserpassword())) {

        final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();

        if (UserRole.ADMIN == userExist.getUserRole()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else if (UserRole.USER == userExist.getUserRole()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        eventRequest.setUserId(userExist.getUserId());

        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(userExist, userExist.getUserpassword(), authorities));

        userExist.setNumberOfVisits(userExist.getNumberOfVisits() + 1);
        userDAO.persist(userExist);
        response = new LoginResponse(ServiceResult.SUCCESS);

    } else {
        response = new LoginResponse(ServiceResult.FAILURE);
    }
    eventRequest.setApplicationMessage(response.getResult().toString());

    createApplicationEventService.processService(eventRequest);
    LOGGER.info("Event: {}", eventRequest);

    return response;
}

From source file:alpha.portal.webapp.controller.SignupController.java

/**
 * On submit.//from w  w w .  jav a2s  .c  o m
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.log.isDebugEnabled()) {
        this.log.debug("entering 'onSubmit' method...");
    }
    final Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(this.roleManager.getRole(Constants.USER_ROLE));

    try {
        this.getUserManager().saveUser(user);
    } catch (final AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor
        // userManagerSecurity
        this.log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (final UserExistsException e) {
        errors.rejectValue("username", "errors.existing.user",
                new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        return "signup";
    }

    this.saveMessage(request, this.getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (this.log.isDebugEnabled()) {
        this.log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    this.message.setSubject(this.getText("signup.email.subject", locale));

    try {
        this.sendUserMessage(user, this.getText("signup.email.message", locale),
                RequestUtil.getAppURL(request));
    } catch (final MailException me) {
        this.saveError(request, me.getMostSpecificCause().getMessage());
    }

    return this.getSuccessView();
}