Example usage for org.springframework.security.core.userdetails UsernameNotFoundException getMessage

List of usage examples for org.springframework.security.core.userdetails UsernameNotFoundException getMessage

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails UsernameNotFoundException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.musicrecital.webapp.pages.PasswordHint.java

Object onActivate(EventContext ctx) {
    // ensure that the username has been set
    if (ctx == null || ctx.getCount() == 0) {
        logger.warn("Username not specified, notifying user that it's a required field.");
        alertManager.alert(Duration.TRANSIENT, Severity.ERROR,
                messages.format("errors.required", messages.get("user.username")));

        return Login.class;
    }// w ww .  j  a  v  a2 s .c om

    // Expect username is the first item in the context
    int userIdx = 0;
    this.username = ctx.get(String.class, userIdx).trim();
    logger.debug("Processing Password Hint for username: " + username);

    // look up the user's information
    try {
        User user = userManager.getUserByUsername(username);

        StringBuilder msg = new StringBuilder();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        String subject = '[' + messages.get("webapp.name") + "] " + messages.get("user.passwordHint");

        emailService.send(user, subject, msg.toString(), RequestUtil.getAppURL(request), true);

        alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                messages.format("login.passwordHint.sent", username, user.getEmail()));
    } catch (UsernameNotFoundException e) {
        logger.warn(e.getMessage());
        // If exception is expected do not rethrow
        alertManager.error(messages.format("login.passwordHint.error", username));

    } catch (MailException me) {
        alertManager.error(me.getCause().getLocalizedMessage());
    }

    return Login.class;
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.PasswordHintController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

    String username = request.getParameter("username");
    MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }/*from   w w  w.  j  a  v  a 2  s  .  c  o m*/

    log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        User user = userManager.getUserByUsername(username);

        StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        message.setTo(user.getEmail());
        String subject = '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint");
        message.setSubject(subject);
        message.setText(msg.toString());
        mailEngine.send(message);

        saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (UsernameNotFoundException e) {
        log.warn(e.getMessage());
        saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (MailException me) {
        log.warn(me.getMessage());
        saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:it.f2informatica.webapp.security.DatabaseUserDetailService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<AuthenticationModel> user = authenticationService.processLogin(username);
    if (user.isPresent()) {
        AuthenticationModel foundUser = user.get();
        logger.info("Authenticating with username: '" + foundUser.getUsername() + "', with role: '"
                + foundUser.getAuthorization() + "'");
        return createUserDetails(foundUser);
    }/*from ww  w.j a  v  a2s . c  o  m*/

    UsernameNotFoundException userNotFoundException = new UsernameNotFoundException(
            "Bad Credentials!!! User has not been found. Wrong Username[" + username + "]");
    logger.info(userNotFoundException.getMessage());

    throw userNotFoundException;
}

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

/**
 * Handle request./* w  w  w.j a  v  a2 s.  c o m*/
 * 
 * @param request
 *            the request
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(final HttpServletRequest request) throws Exception {
    this.log.debug("entering 'handleRequest' method...");

    final String username = request.getParameter("username");
    final MessageSourceAccessor text = new MessageSourceAccessor(this.messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        this.log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }

    this.log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        final User user = this.userManager.getUserByUsername(username);

        final StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        this.message.setTo(user.getEmail());
        final String subject = '[' + text.getMessage("webapp.name") + "] "
                + text.getMessage("user.passwordHint");
        this.message.setSubject(subject);
        this.message.setText(msg.toString());
        this.mailEngine.send(this.message);

        this.saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (final UsernameNotFoundException e) {
        this.log.warn(e.getMessage());
        this.saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (final MailException me) {
        this.log.warn(me.getMessage());
        this.saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:com.devnexus.ting.core.service.impl.SimpleConnectionSignUp.java

@Override
public String execute(Connection<?> connection) {
    final UserProfile profile = connection.fetchUserProfile();

    User user;//from  ww w.j a v  a 2  s .c  o m
    boolean isUpdate;

    try {
        user = (User) this.userService.loadUserByUsername(connection.getKey().toString());
        isUpdate = true;
    } catch (UsernameNotFoundException e) {
        user = new User();
        isUpdate = false;
    }

    user.setFirstName(profile.getFirstName());
    user.setEmail(profile.getEmail());
    user.setLastName(profile.getLastName());
    user.setUsername(connection.getKey().toString());
    user.setPassword(null);
    user.getUserAuthorities().add(new UserAuthority(user, AuthorityType.APP_USER));

    if (isUpdate) {
        this.userService.updateUser(user);
    } else {
        final User createdUser;
        try {
            createdUser = this.userService.addUser(user);
        } catch (DuplicateUserException e) {
            LOGGER.error("User {} already exists. Exception: {}", user.getUsername(), e.getMessage());
            return null;
        }
        LOGGER.info("User {} with Id {} created.", createdUser.getUsername(), user.getId());
    }
    return user.getUserId();
}

From source file:com.devnexus.ting.web.controller.AndroidLoginController.java

/**
 * This will verify tokens sent from an Authenticated Android device that
 * the user is who the user says it is./*from   w ww  .java  2  s .c  o m*/
 * <p/>
 * Additionally it will create an account if one does not exist.
 */
@RequestMapping(value = "/s/loginAndroid", method = RequestMethod.POST)
@ResponseBody
public String login(HttpServletRequest request, HttpServletResponse response) {

    try {

        AndroidAuthentication auth = GSON.fromJson(request.getReader(), AndroidAuthentication.class);
        String accessToken = auth.idToken;

        GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(),
                new JacksonFactory()).setAudience(Arrays.asList(CLIENT_ID))
                        // If you retrieved the token on Android using the
                        // Play Services 8.3 API or newer, set
                        // the issuer to "https://accounts.google.com".
                        // Otherwise, set the issuer to
                        // "accounts.google.com". If you need to verify
                        // tokens from multiple sources, build
                        // a GoogleIdTokenVerifier for each issuer and try
                        // them both.
                        .setIssuer("https://accounts.google.com").build();

        GoogleIdToken idToken = verifier.verify(accessToken);
        Payload payload = idToken.getPayload();

        User user;
        try {
            user = (User) userService.loadUserByUsername("google:" + payload.getSubject());
        } catch (UsernameNotFoundException e) {
            user = new User();
            user.setEmail(payload.getEmail());
            user.setUsername("google:" + payload.getSubject());
            user.setUserAuthorities(new HashSet<UserAuthority>(1));
            user.getUserAuthorities().add(new UserAuthority(user, AuthorityType.APP_USER));
            user.setFirstName((String) payload.get("given_name"));
            user.setLastName((String) payload.get("family_name"));
            byte[] password = new byte[16];
            new SecureRandom().nextBytes(password);
            user.setPassword(Arrays.toString(password));

            try {
                userService.addUser(user);
            } catch (DuplicateUserException ex) {
                Logger.getLogger(AndroidLoginController.class.getName()).log(Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            }

            user = (User) userService.loadUserByUsername(user.getUsername());

        }

        MobileSignIn signIn = new MobileSignIn();
        signIn.setToken(new BigInteger(512, new SecureRandom()).toString(32));
        signIn.setUser(user);
        user.getMobileTokens().add(signIn);

        userService.updateUser(user);

        return "{\"token\":\"" + signIn.getToken() + "\"}";

    } catch (IOException | GeneralSecurityException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e);

        throw new RuntimeException(e);
    }

}

From source file:org.apache.atlas.web.security.FileAuthenticationTest.java

@Test
public void testInValidUsernameLogin() {

    when(authentication.getName()).thenReturn("wrongUserName");
    when(authentication.getCredentials()).thenReturn("wrongpassword");
    try {// w ww .j ava 2s  . c o  m
        Authentication auth = authProvider.authenticate(authentication);
        LOG.debug(" {}", auth);
    } catch (UsernameNotFoundException uExp) {
        Assert.assertTrue(uExp.getMessage().contains("Username not found."));
    }
}

From source file:org.apache.atlas.web.security.FileAuthenticationTest.java

@Test
public void testLoginWhenRolePasswordNotSet() {

    when(authentication.getName()).thenReturn("user"); // for this user password details are set blank
    when(authentication.getCredentials()).thenReturn("P@ssword");
    try {// w w  w. ja va2 s .  co  m
        Authentication auth = authProvider.authenticate(authentication);
        LOG.debug(" {}", auth);
    } catch (UsernameNotFoundException uExp) {
        Assert.assertTrue(uExp.getMessage().startsWith("Username not found"));
    }
}

From source file:org.apache.nifi.web.security.authorization.NiFiAuthorizationService.java

/**
 * Loads the user details for the specified dn.
 *
 * Synchronizing because we want each request to be authorized atomically since each may contain any number of DNs. We wanted an access decision made for each individual request as a whole
 * (without other request potentially impacting it).
 *
 * @param request request/*www .  ja va  2s.  c o m*/
 * @return user details
 * @throws UsernameNotFoundException ex
 * @throws org.springframework.dao.DataAccessException ex
 */
@Override
public synchronized UserDetails loadUserDetails(NiFiAuthortizationRequestToken request)
        throws UsernameNotFoundException, DataAccessException {
    NiFiUserDetails userDetails = null;
    final List<String> chain = new ArrayList<>(request.getChain());

    // ensure valid input
    if (chain.isEmpty()) {
        logger.warn("Malformed proxy chain: " + StringUtils.join(request.getChain()));
        throw new UntrustedProxyException("Malformed proxy chain.");
    }

    NiFiUser proxy = null;

    // process each part of the proxy chain
    for (final ListIterator<String> chainIter = request.getChain().listIterator(chain.size()); chainIter
            .hasPrevious();) {
        final String dn = chainIter.previous();

        // if there is another dn after this one, this dn is a proxy for the request
        if (chainIter.hasPrevious()) {
            try {
                // get the user details for the proxy
                final NiFiUserDetails proxyDetails = getNiFiUserDetails(dn);
                final NiFiUser user = proxyDetails.getNiFiUser();

                // verify the proxy has the appropriate role
                if (!user.getAuthorities().contains(Authority.ROLE_PROXY)) {
                    logger.warn(String.format("Proxy '%s' must have '%s' authority. Current authorities: %s",
                            dn, Authority.ROLE_PROXY.toString(),
                            StringUtils.join(user.getAuthorities(), ", ")));
                    throw new UntrustedProxyException(
                            String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn,
                                    Authority.ROLE_PROXY.toString()));
                }

                // if we've already encountered a proxy, update the chain
                if (proxy != null) {
                    user.setChain(proxy);
                }

                // record this user as the proxy for the next user in the chain
                proxy = user;
            } catch (UsernameNotFoundException unfe) {
                // if this proxy is a new user, conditionally create a new account automatically
                if (properties.getSupportNewAccountRequests()) {
                    try {
                        logger.warn(
                                String.format("Automatic account request generated for unknown proxy: %s", dn));

                        // attempt to create a new user account for the proxying client
                        userService.createPendingUserAccount(dn,
                                "Automatic account request generated for unknown proxy.");
                    } catch (AdministrationException ae) {
                        throw new AuthenticationServiceException(String.format(
                                "Unable to create an account request for '%s': %s", dn, ae.getMessage()), ae);
                    } catch (IllegalArgumentException iae) {
                        // check then modified... account didn't exist when getting the user details but did when
                        // attempting to auto create the user account request
                        final String message = String.format("Account request was already submitted for '%s'",
                                dn);
                        logger.warn(message);
                        throw new AccountStatusException(message) {
                        };
                    }
                }

                logger.warn(String.format("Untrusted proxy '%s' must be authorized with '%s' authority: %s", dn,
                        Authority.ROLE_PROXY.toString(), unfe.getMessage()));
                throw new UntrustedProxyException(
                        String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn,
                                Authority.ROLE_PROXY.toString()));
            } catch (AuthenticationException ae) {
                logger.warn(String.format("Untrusted proxy '%s' must be authorized with '%s' authority: %s", dn,
                        Authority.ROLE_PROXY.toString(), ae.getMessage()));
                throw new UntrustedProxyException(
                        String.format("Untrusted proxy '%s' must be authorized with '%s'.", dn,
                                Authority.ROLE_PROXY.toString()));
            }
        } else {
            userDetails = getNiFiUserDetails(dn);

            // if we've already encountered a proxy, update the chain
            if (proxy != null) {
                final NiFiUser user = userDetails.getNiFiUser();
                user.setChain(proxy);
            }
        }
    }

    return userDetails;
}

From source file:org.artifactory.security.SecurityServiceImpl.java

@Override
public String resetPassword(String userName, String remoteAddress, String resetPageUrl) {
    UserInfo userInfo = null;//from w w  w  .j av  a  2  s  .co  m
    try {
        userInfo = findUser(userName);
    } catch (UsernameNotFoundException e) {
        //Alert in the log when trying to reset a password of an unknown user
        log.warn("An attempt has been made to reset a password of unknown user: {}", userName);
    }

    //If the user is found, and has an email address
    if (userInfo != null && !StringUtils.isEmpty(userInfo.getEmail())) {

        //If the user hasn't got sufficient permissions
        if (!userInfo.isUpdatableProfile()) {
            throw new RuntimeException("The specified user is not permitted to reset his password.");
        }

        //Get client IP, then generate and send a password reset key
        try {
            generatePasswordResetKey(userName, remoteAddress, resetPageUrl);
        } catch (EmailException ex) {
            String message = ex.getMessage() + " Please contact your administrator.";
            throw new RuntimeException(message);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    return "We have sent you via email a link for resetting your password. Please check your inbox.";
}