Example usage for org.springframework.security.core AuthenticationException getMessage

List of usage examples for org.springframework.security.core AuthenticationException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:ro.allevo.fintpws.security.ApiAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.addHeader("Access-Control-Allow-Origin", "null");
    response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println(//from  w w  w  . ja  va2 s.co  m
            "Here : HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
}

From source file:de.thm.arsnova.controller.LoginController.java

@RequestMapping(value = { "/auth/login", "/doLogin" }, method = { RequestMethod.POST, RequestMethod.GET })
public void doLogin(@RequestParam("type") final String type,
        @RequestParam(value = "user", required = false) String username,
        @RequestParam(required = false) final String password,
        @RequestParam(value = "role", required = false) final UserSessionService.Role role,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    String addr = request.getRemoteAddr();
    if (userService.isBannedFromLogin(addr)) {
        response.sendError(429, "Too Many Requests");

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

    userSessionService.setRole(role);

    if ("arsnova".equals(type)) {
        Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication auth = daoProvider.authenticate(authRequest);
            if (auth.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(auth);
                request.getSession(true).setAttribute(
                        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                        SecurityContextHolder.getContext());

                return;
            }
        } catch (AuthenticationException e) {
            LOGGER.info("Authentication failed: {}", e.getMessage());
        }

        userService.increaseFailedLoginCount(addr);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else if ("ldap".equals(type)) {
        if (!"".equals(username) && !"".equals(password)) {
            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                    username, password, true, true, true, true, this.getAuthorities());

            Authentication token = new UsernamePasswordAuthenticationToken(user, password, getAuthorities());
            try {
                Authentication auth = ldapAuthenticationProvider.authenticate(token);
                if (auth.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(token);
                    request.getSession(true).setAttribute(
                            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                            SecurityContextHolder.getContext());

                    return;
                }
                LOGGER.info("LDAPLOGIN: {}", auth.isAuthenticated());
            } catch (AuthenticationException e) {
                LOGGER.info("No LDAP login: {}", e);
            }

            userService.increaseFailedLoginCount(addr);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    } else if ("guest".equals(type)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
        if (username == null || !username.startsWith("Guest") || username.length() != MAX_USERNAME_LENGTH) {
            username = "Guest"
                    + Sha512DigestUtils.shaHex(request.getSession().getId()).substring(0, MAX_GUESTHASH_LENGTH);
        }
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                username, "", true, true, true, true, authorities);
        Authentication token = new UsernamePasswordAuthenticationToken(user, null, authorities);

        SecurityContextHolder.getContext().setAuthentication(token);
        request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
    }
}

From source file:org.shredzone.cilla.admin.login.LoginBean.java

/**
 * Tries to login the user with the given credentials.
 *
 * @return name of the admin index page if the login was successful, {@code null} if
 *         the login was not successful.
 *//*from w  ww  .  ja va 2  s  .  c o m*/
public String login() {
    try {
        remoteLoginService.login(getUserName(), getPassword());
    } catch (AuthenticationException ex) {
        log.error("Authentication failed, user: '" + getUserName() + "', password: '********'", ex);

        FacesContext ctx = FacesContext.getCurrentInstance();
        Locale loc = ctx.getViewRoot().getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(), loc);
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle.getString("login.failed"),
                ex.getMessage());
        ctx.addMessage(null, message);

        return null;
    }

    return "/admin/index.xhtml";
}

From source file:com.stormpath.spring.config.StormpathAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    log.debug("Pre-authenticated entry point called. Rejecting access");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    String bearerRealm = String.format("Bearer realm=\"%s\"", applicationName);
    response.addHeader("WWW-Authenticate", bearerRealm);
    if (isJsonPreferred(request, response)) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        om.writeValue(response.getOutputStream(),
                new Error(ErrorConstants.ERR_ACCESS_DENIED, authException.getMessage()));
    } else {/*from   w  w w.j  a  va  2 s .co m*/
        sendRedirect(request, response);
    }
}

From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.addHeader("WWW-Authenticate", String.format("%s realm=\"%s\"", typeName, realmName));
    String accept = request.getHeader("Accept");
    boolean json = false;
    if (StringUtils.hasText(accept)) {
        for (MediaType mediaType : MediaType.parseMediaTypes(accept)) {
            if (mediaType.includes(MediaType.APPLICATION_JSON)) {
                json = true;//from w ww  .  jav  a  2 s  .c om
                break;
            }
        }
    }
    if (json) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().append(String.format("{\"error\":\"%s\"}", authException.getMessage()));
    } else {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
    }
}

From source file:com.nec.harvest.controller.LoginController.java

/**
 * The REST handle login event for the given username and password
 * //from  w  ww.  j ava  2  s  .  c  o  m
 * @param request
 *            A HttpServletRequest
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/login**")
public String login(@RequestParam(value = "error", required = false) boolean error,
        @SessionAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) AuthenticationException authException,
        final HttpServletRequest request, final Model model) {
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering the loggin page...");
    }

    // Get close confirm message when user click CLOSE application button on the login page
    model.addAttribute(Constants.CFM_CLOSE_APPLICATION_MESSAGE, getCloseAppMsg());

    // 
    if (error && authException != null) {
        logger.warn(authException.getMessage());

        Message message;

        // ??????????
        if (authException instanceof BadCredentialsException) {
            message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
        } else {
            Throwable throwable = authException.getCause();
            if (throwable instanceof HarvestAuthenticationException) {
                message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
            } else if (throwable instanceof OrganizationNotFoundException) {
                message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M02);
            } else if (authException instanceof AuthenticationServiceException) { // NOTE: This case is authentication method not supported: GET
                logger.warn(authException.getMessage());

                // This exception will be throw when end-user type directly or try to access
                // by URL: .../j_spring_security_check
                message = MessageHelper.get(MsgConstants.AF001_ENT_CHK_M01);
            } else {
                message = getSystemError();
                if (logger.isDebugEnabled()) {
                    logger.debug(authException.getMessage(), authException.getCause());
                }

                // 
                logger.error(authException.getMessage(), authException.getCause());
            }
        }

        // 
        model.addAttribute(ERROR, true);
        model.addAttribute(ERROR_MESSAGE, message);

        // Clear authentication exception from the SESSION
        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, null);
    }

    return getViewName();
}

From source file:de.itsvs.cwtrpc.security.SimpleRpcAuthenticationFailureHandler.java

protected Exception createRemoteException(HttpServletRequest request, AuthenticationException exception,
        Class<? extends Exception> remoteExceptionClass) {
    final Constructor<? extends Exception> constructor;
    Exception remoteException;//from w w w. j  a  v a  2s . c o m

    if (isIncludeExceptionMessage()) {
        constructor = getMessageConstructor(remoteExceptionClass);
    } else {
        constructor = null;
    }

    try {
        if (constructor != null) {
            if (log.isDebugEnabled()) {
                log.debug("Creating remote exception " + remoteExceptionClass.getName()
                        + " with message of original exception");
            }
            remoteException = BeanUtils.instantiateClass(constructor, new Object[] { exception.getMessage() });
        } else {
            remoteException = BeanUtils.instantiateClass(remoteExceptionClass);
        }
    } catch (BeanInstantiationException e) {
        log.error("Could not create remote exception: " + remoteExceptionClass.getName(), e);
        remoteException = null;
    }

    return remoteException;
}

From source file:org.carewebframework.security.spring.controller.LoginPaneController.java

/**
 * Initialize the login form.//from   w  w  w  .j a  v  a2 s. co m
 *
 * @param comp The root component
 */
@Override
public void doAfterCompose(Component comp) throws Exception {
    super.doAfterCompose(comp);
    savedRequest = (SavedRequest) arg.get("savedRequest");
    AuthenticationException authError = (AuthenticationException) arg.get("authError");
    String loginFailureMessage = Labels.getLabel(Constants.LBL_LOGIN_ERROR);//reset back to default

    if (LoginWindowController.getException(authError, CredentialsExpiredException.class) != null) {
        loginFailureMessage = Labels.getLabel(Constants.LBL_LOGIN_ERROR_EXPIRED_USER);//override generic UserLoginException default
    } else if (LoginWindowController.getException(authError, DisabledException.class) != null) {
        loginFailureMessage = authError.getMessage();//override generic UserLoginException default
    }

    String username = (String) session.removeAttribute(Constants.DEFAULT_USERNAME);
    username = authError == null ? defaultUsername : username;
    showMessage(authError == null ? null : loginFailureMessage);
    txtUsername.setText(username);
    txtPassword.setText(defaultPassword);

    if (StringUtils.isEmpty(username)) {
        txtUsername.setFocus(true);
    } else {
        txtPassword.setFocus(true);
    }

    Collection<ISecurityDomain> securityDomains = securityService.getSecurityDomains();
    String securityDomainId = securityDomains.size() == 1 ? securityDomains.iterator().next().getLogicalId()
            : null;

    if (StringUtils.isEmpty(securityDomainId)) {
        securityDomainId = (String) session.getAttribute(Constants.DEFAULT_SECURITY_DOMAIN);
    }

    if (StringUtils.isEmpty(securityDomainId)) {
        if (savedRequest != null) {
            String params[] = savedRequest.getParameterValues(Constants.DEFAULT_SECURITY_DOMAIN);

            if (params != null && params.length > 0) {
                securityDomainId = params[0];
            }
        } else {
            securityDomainId = execution.getParameter(Constants.DEFAULT_SECURITY_DOMAIN);
        }
    }

    if (StringUtils.isEmpty(securityDomainId)) {
        securityDomainId = defaultDomain;
    }

    if (log.isDebugEnabled()) {
        log.debug("Security domains:" + (securityDomains == null ? "null" : securityDomains.size()));
    }

    switch (securityDomains.size()) {
    case 0:
        showStatus(Labels.getLabel(Constants.LBL_LOGIN_NO_VALID_DOMAINS));
        return;

    case 1:
        setDomainSelectionMode(DomainSelectionMode.DISALLOW);
        break;

    default:
        setDomainSelectionMode(DomainSelectionMode.OPTIONAL);
        break;
    }

    for (ISecurityDomain securityDomain : securityDomains) {
        Listitem li = new Listitem();
        li.setValue(securityDomain);
        lstDomain.appendChild(li);
        li.appendChild(new Listcell(securityDomain.getName()));

        if (securityDomainId != null && securityDomainId.equals(securityDomain.getLogicalId())) {
            li.setSelected(true);
            securityDomainId = null;
        }
    }

    if (lstDomain.getSelectedIndex() == -1) {
        lstDomain.setSelectedIndex(0);
    }

    defaultLogoUrl = imgDomain.getSrc();
    domainChanged();

    if (authError == null && autoLogin) {
        comp.setVisible(false);
        Events.echoEvent("onSubmit", comp, null);
    }

}

From source file:com.virtusa.akura.common.controller.LoginController.java

/**
 * handle GET requests for Student_details view.
 * /* ww w. j a  v  a  2 s . c  o m*/
 * @param model - ModelMap
 * @param session - Session
 * @return the name of the view.
 * @throws AkuraAppException - The exception details that occurred when processing.
 */
@RequestMapping(value = USER_LOGIN_ERROR_HTM, method = RequestMethod.GET)
public String showUserLoginError(ModelMap model, HttpSession session) throws AkuraAppException {

    AuthenticationException authenticationException = null;
    String message = "";
    UserLogin userLogin = null;

    try {
        authenticationException = ((AuthenticationException) session
                .getAttribute(SPRING_SECURITY_LAST_EXCEPTION));
        if (authenticationException != null) {
            // get the user login
            userLogin = userService
                    .getAnyUser((String) (authenticationException.getAuthentication().getPrincipal()));
            throw authenticationException;
        }

    } catch (LockedException e) {
        message = authenticationException.getMessage();

    } catch (DisabledException e) {

        message = authenticationException.getMessage();

    } catch (BadCredentialsException e) {
        /* increase login attempts */

        // get the user login
        if (userLogin != null) {
            userLogin.setLoginAttempts(userLogin.getLoginAttempts() + 1);
            userService.updateUser(userLogin);
        }
        message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_KEY);
    }

    model.addAttribute(LOGIN_ERROR, message);
    return LOGIN;
}

From source file:com.jd.survey.web.security.AccountController.java

/**
 * Updates  logged in user password//from ww w . jav a2 s .c om
 * @param oldPassword
 * @param newPassword
 * @param newPasswordConfirm
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/rpass", method = RequestMethod.POST, produces = "text/html")
public String updatePasswordPost(@RequestParam(value = "password", required = true) String oldPassword,
        @RequestParam(value = "nPassword", required = true) String newPassword,
        @RequestParam(value = "cPassword", required = true) String newPasswordConfirm,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        if (proceed != null) {

            //check that the old password is correct
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    principal.getName(), oldPassword);
            authenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            try {
                Authentication auth = authenticationManager.authenticate(authenticationToken);
                if (auth == null || !auth.isAuthenticated()) {
                    //invalid password enetered
                    uiModel.asMap().clear();
                    uiModel.addAttribute("status", "E"); //Unmatching Passwords
                    return "account/rpass";
                }

            } catch (AuthenticationException e) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "E"); //Unmatching Passwords
                return "account/rpass";
            }
            //Check new password strenght 
            if (!GenericValidator.matchRegexp(newPassword, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                return "account/rpass";
            }
            //check that passwords match    
            if (!newPassword.equals(newPasswordConfirm)) {
                uiModel.asMap().clear();

                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "account/rpass";
            }
            User loggedInUser = userService.user_findByLogin(principal.getName());
            //All validations passed, save the HASH of the password in the database
            loggedInUser.setPassword(newPassword);
            userService.user_updatePassword(loggedInUser);
            uiModel.addAttribute("status", "S");//success
            return "account/rpass";
        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}