Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:io.gravitee.management.security.config.basic.filter.JWTAuthenticationFilter.java

@Override
@SuppressWarnings(value = "unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    final Optional<Cookie> optionalStringToken;

    if (req.getCookies() == null) {
        optionalStringToken = Optional.empty();
    } else {//from  ww w  .j av  a2  s.c  om
        optionalStringToken = Arrays.stream(req.getCookies())
                .filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny();
    }
    if (optionalStringToken.isPresent()) {
        String stringToken = optionalStringToken.get().getValue();

        final String authorizationSchema = "Bearer";
        if (stringToken.contains(authorizationSchema)) {
            stringToken = stringToken.substring(authorizationSchema.length()).trim();
            try {
                final Map<String, Object> verify = jwtVerifier.verify(stringToken);

                final List<SimpleGrantedAuthority> authorities = ((List<Map>) verify.get(JWTClaims.PERMISSIONS))
                        .stream().map(map -> new SimpleGrantedAuthority(map.get("authority").toString()))
                        .collect(Collectors.toList());

                final UserDetails userDetails = new UserDetails(getStringValue(verify.get(JWTClaims.SUBJECT)),
                        "", authorities, getStringValue(verify.get(JWTClaims.EMAIL)),
                        getStringValue(verify.get(JWTClaims.FIRSTNAME)),
                        getStringValue(verify.get(JWTClaims.LASTNAME)));

                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()));
            } catch (Exception e) {
                LOGGER.error("Invalid token", e);

                final Cookie bearerCookie = jwtCookieGenerator.generate(null);
                res.addCookie(bearerCookie);

                res.sendError(HttpStatusCode.UNAUTHORIZED_401);
            }
        } else {
            LOGGER.info("Authorization schema not found");
        }
    } else {
        LOGGER.info("Authorization cookie not found");
    }
    chain.doFilter(request, response);
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnResponse(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    String remoteAddress = request.getRemoteAddr();
    this.logger.debug("[Authn for {}] Going to process authentication response.", remoteAddress);

    String base64SAMLDocument = request.getParameter("SAMLResponse");
    if (base64SAMLDocument == null || base64SAMLDocument.length() == 0) {
        throw new AuthenticationException(
                "SAMLResponse request parameter was null. Unable to process response.");
    }//from   w w w . j a v  a2s.  com

    byte[] samlDocument;
    try {
        samlDocument = Base64.decodeBase64(base64SAMLDocument.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationException(
                "Unable to complete authentication because a required character encoding is not supported.", e);
    }
    // Use the AuthnProcessor to unmarshal the response document.
    Response responseObject = spep.getAuthnProcessor().unmarshalResponse(samlDocument);
    this.logger.info(
            "[Authn for {}] Got an authentication response, going to process. Response ID: {}  InResponseTo: {}",
            new Object[] { remoteAddress, responseObject.getID(), responseObject.getInResponseTo() });

    spep.getAuthnProcessor().processAuthnResponse(data, responseObject);

    String sessionID = data.getSessionID();
    if (sessionID == null) {
        throw new AuthenticationException(
                "Session identifier from AuthnProcessor was null. Unable to process SSO event");
    }

    Cookie cookie = new Cookie(spep.getTokenName(), sessionID);

    cookie.setPath("/");
    response.addCookie(cookie);

    try {
        String redirectURL = null;
        String base64RequestURL = data.getRequestURL();
        if (base64RequestURL != null) {
            redirectURL = new String(Base64.decodeBase64(base64RequestURL.getBytes()));
        } else {
            redirectURL = spep.getDefaultUrl();
        }

        this.logger.info(
                "[Authn for {}] Processed response ID: {} .. Created local session with session ID: {}  Redirecting user to requested content: {}",
                new Object[] { remoteAddress, responseObject.getID(), sessionID, redirectURL });

        response.sendRedirect(redirectURL);
    } catch (IOException e) {
        throw new AuthenticationException(
                "Unable to send redirect back to authenticated content as an I/O error occurred", e);
    }
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

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

    try {/*from w w w  .  java 2 s  .  co m*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:in.raster.oviyam.servlet.Validator.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    /*AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
    String loginId=principal.getName();*/

    /*??*///w ww  .ja v a  2  s .com
    String pid = (String) request.getParameter("PatientID").trim();
    if (pid == null || "".equals(pid)) {
        out.println("??!");
        out.close();
        return;
    }

    /*?????*/
    String r = dataAccess.getReportAddress(pid);
    /*?dcmpacs?*/
    //String r=dataAccess.addDicom("x");

    /*?*/
    Boolean a = dataAccess.checsIsExist(pid);
    if (!a) {
        out.println("?!");
        out.close();
        return;
    }

    /*????*/
    //boolean b=dataAccess.checkCheckId(loginId,pid);
    //if(!b)return;

    /**/
    /*PacsQueryLogModel pqlm = new PacsQueryLogModel();
    pqlm.setApplicationId(pid);
    pqlm.setDoctorId(loginId);
    dataAccess.addPacsLog(pqlm);*/

    AE ae;
    ServletContext servletContext = getServletContext();
    ServerConfiguration serverConfiguration;
    EchoService echoService;

    String agree = request.getParameter("agree");

    if (agree != null && agree.equals("agree")) {
        Cookie agreeCookie = new Cookie("agree", "agree");
        agreeCookie.setMaxAge(60 * 60 * 24 * 365);
        response.addCookie(agreeCookie);
    }

    try {
        ae = new AE();
        //assigns the serverConfiguration instance.         
        serverConfiguration = ae.getServerConfiguration();
        /*
         * writes the serverConfiguration instance in the servletContext (application scope).
         * So all the SERVLET classes and JSP pages can access the serverConfig attribute.
         * User can use either <jsp:useBean> tag or ${applicationScope.serverConfig} EL 
         * to access the serverConfig attribute. From SERVLET classes the User can use
         * the getServletContext().getAttribute("serverConfig") to access the serverConfiguration attribute.
         */
        servletContext.setAttribute("serverConfig", serverConfiguration);

        echoService = new EchoService();
        echoService.checkEcho();
        /*If the status of EchoService is failed then the request will be forwarded to 
         * EchoFailed.jsp. Otherwise, request is forwarded to oviyam7.jsp
         * 
         */
        if (echoService.getStatus().equals("Echo failed")) {
            /*
             * writes the echoURL(dcmProtocol://aeTitle@hostName:port) attribute in request instance.
             * and forwards the request and response object to EchoFailed.jsp .
             * echoFailed attribute can be accessed through either ${request.echoURL} or 
             * <% request.getAttribute("echoURL")%>
             */
            request.setAttribute("echoURL", ae.toString());
            request.getRequestDispatcher("EchoFailed.jsp").forward(request, response);
        } else {
            // forwards the request and response to oviyam7.jsp
            String studyUID = request.getParameter("studyUID");
            String seriesUID = request.getParameter("seriesUID");
            String patientID = request.getParameter("patientID");
            if (studyUID != null && studyUID.length() <= 0) {
                request.setAttribute("param", "studyUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid studyUID parameter for Oviyam.");
            } else if (seriesUID != null && seriesUID.length() <= 0) {
                request.setAttribute("param", "seriesUID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid seriesUID parameter for Oviyam.");
            } else if (patientID != null && patientID.length() <= 0) {
                request.setAttribute("param", "patientID");
                request.getRequestDispatcher("InvalidParam.jsp").forward(request, response);
                log.error("Invalid patientID parameter for Oviyam.");
            } else {
                request.getRequestDispatcher("oviyam7.jsp").forward(request, response);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage());

    }
}

From source file:org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.java

public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication successfulAuthentication) {
    // Exit if the principal hasn't asked to be remembered
    if (!rememberMeRequested(request, parameter)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Did not send remember-me cookie (principal did not set parameter '" + this.parameter
                    + "')");
        }//from  w ww .  j  av a 2 s.c  o m

        return;
    }

    // Determine username and password, ensuring empty strings
    Assert.notNull(successfulAuthentication.getPrincipal());
    Assert.notNull(successfulAuthentication.getCredentials());

    String username = retrieveUserName(successfulAuthentication);
    String password = retrievePassword(successfulAuthentication);

    // If unable to find a username and password, just abort as
    // TokenBasedRememberMeServices unable to construct a valid token in
    // this case
    if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
        return;
    }

    long expiryTime = System.currentTimeMillis() + (tokenValiditySeconds * 1000);

    // construct token to put in cookie; format is:
    // username + ":" + expiryTime + ":" + Md5Hex(username + ":" +
    // expiryTime + ":" + password + ":" + key)
    String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key);
    String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
    String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes()));
    response.addCookie(makeValidCookie(tokenValueBase64, request, tokenValiditySeconds));

    if (logger.isDebugEnabled()) {
        logger.debug(
                "Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
    }
}

From source file:com.mhe.imagebanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = AmazonServiceUtilTag.getImageThumbnailURL();
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;//from   www.j  av a2 s  . c om
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId, ASSETBANK_TYPE);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");

        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {//from ww w .j  av a  2  s  . c  o m
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:com.mhe.mediabanksearch.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //TO HANDLE:   Scenario 1. User comes directly on login page first time.
    //            Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application
    //            Scenario 3. User fill up the login details and click on submit.

    //TODO: 1. Check for already logged-in user or ERIGHTS cookie
    //      2. If not already logged in then check if user has tries to login
    //      3. If user has not tried to login then send to login screen

    String thumbnailPath = Configuration.getSystemValue(Constants.IMAGE_THUMBNAIL_URL_PATH);
    String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT);
    String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME);
    HttpSession session = request.getSession();
    session.setAttribute("baseUrl", thumbnailPath);
    session.setAttribute("perPageRecordCount", perPageRecordCount);
    session.setAttribute("searchManagerName", searchManagerName);

    String userAction = null;/* w  w  w  .  j  av  a2 s. c  o  m*/
    //Implementing Scenario 1.
    String sessionId = null;
    String logOutCondition = null;
    boolean validSession = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS);

        logOutCondition = getCookieValue(cookies, LOGOUT, "false");
        logOutCondition = logOutCondition.split("~")[0];
        if ("true".equalsIgnoreCase(logOutCondition)) {
            response.addCookie(new Cookie(LOGOUT, "true~refreshed"));
            return new ModelAndView(LOGIN_VIEW);
        }

        if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) {
            validSession = true;
            validSession = rmsManager.isValidSession(sessionId);
        }

        if (validSession) {
            userAction = "previouslyloggedin";
            //userId1 =  rmsManager.sessionListUserId(sessionId);            
        } else {
            userAction = "firsttimelogin";
        }
    } else {
        userAction = "firsttimelogin";
    }

    //Implementing Scenario 2.      
    long startTime = System.currentTimeMillis();
    String userName = request.getParameter(REQ_PARAM_USER_NAME);
    String password = request.getParameter(REQ_PARAM_PASSWORD);
    if (userName != null && password != null && session.isNew()) {
        response.addCookie(new Cookie(LOGOUT, "true"));
        request.setAttribute("loginErrorMessage", "userError");
        return new ModelAndView(LOGIN_VIEW);
    }
    boolean inError = false;
    boolean isServerDown = false;
    boolean wrongCredentials = false;
    boolean isSession = true;
    String role = null;
    LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData");
    if ((userName != null && password != null)) {
        if (loginInfo == null) {
            try {
                loginInfo = rmsManager.loginUser(userName, password);
                if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) {
                    request.setAttribute("loginErrorMessage", "invalidUser");
                    return new ModelAndView(LOGIN_VIEW);
                }
                isSession = false;
            } catch (Exception e) {
                e.printStackTrace();
                inError = true;
                if (e.getCause() != null) {
                    if (e.getCause() instanceof SOAPFaultException) {
                        SOAPFaultException ex = (SOAPFaultException) e.getCause();
                        String faultString = ex.getFaultString();
                        String errorCode = faultString.substring(0, faultString.indexOf(":"));
                        if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) {
                            wrongCredentials = true;
                        } else {
                            isServerDown = true;
                        }
                    } else {
                        isServerDown = true;
                    }
                } else {
                    isServerDown = true;
                }
            }

            if (isServerDown) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN);
                return new ModelAndView(LOGIN_VIEW);
            } else if (inError) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
                return new ModelAndView(LOGIN_VIEW);
            } else if (wrongCredentials) {
                request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS);
                return new ModelAndView(LOGIN_VIEW);
            }
        }

        if (loginInfo != null) {
            if (!isSession) {
                String userId = loginInfo.getUserId();
                role = rmsManager.getUserRole(userId);
                User user = rmsManager.getUserById(userId);
                String authenticationKey = loginInfo.getSessionId();
                session.setAttribute(USER_ID, userId);
                session.setAttribute(ROLE, role);
                session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role));
                session.setAttribute(AUTHENTICATION_KEY, authenticationKey);
                session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName());
                session.setAttribute("userData", loginInfo);
                response.addCookie(new Cookie("ERIGHTS", authenticationKey));
            } else {
                session.getAttribute(ROLE);
            }
            if (_logger.isDebugEnabled()) {
                long endTime = System.currentTimeMillis();
                _logger.debug(
                        "Total execution time for Login Controller is : " + (endTime - startTime) + " ms.");
            }
            //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342
            //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs"));

            //session.setAttribute("providerIsbn", "0073273163");
            //session.setAttribute("courseIsbn", "0072859342");

            //License lic =  rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId()));

            request.setAttribute("isStandalone", true);
            response.addCookie(new Cookie(LOGOUT, "false"));
            return new ModelAndView("initial.view");
        } else {
            request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR);
            return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN);
        }
    }

    //Implementing Scenario 3.      

    //sending to appropriate view
    if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) {
        return new ModelAndView(LOGIN_VIEW);
    } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) {
        request.setAttribute("isStandalone", true);
        return new ModelAndView("initial.view");
    }
    return new ModelAndView(LOGIN_VIEW);
}

From source file:org.sharetask.security.StoreUserInformationAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    if (authentication instanceof ClientAuthenticationToken) {
        log.debug("Token is pac4j token.");

        String language = Language.EN.getCode();
        UsernamePasswordAuthenticationToken authentToken;
        final CommonProfile profile = (CommonProfile) ((ClientAuthenticationToken) authentication)
                .getUserProfile();//from   w w  w.  j a  va2  s  .c om
        if (userRepository.findByUsername(profile.getEmail()) == null) {
            log.debug("User with name: {} doesne exist's. Will be created", profile.getEmail());
            final UserInformation userInformation = new UserInformation(profile.getEmail());
            userInformation.setName(profile.getFirstName());
            userInformation.setSurName(profile.getFamilyName());
            userInformation.setLanguage(language);
            final ArrayList<Role> list = new ArrayList<Role>();
            list.add(Role.ROLE_USER);
            userInformation.setRoles(list);
            userRepository.save(userInformation);
            final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.name()));
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        } else {
            final UserInformation user = userRepository.read(profile.getEmail());
            language = user.getLanguage();
            final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        }
        // language cookie
        final Cookie locale = new Cookie(RequestUltil.LOCALE, language);
        locale.setMaxAge(-1);
        locale.setPath("/");
        response.addCookie(locale);

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

    super.onAuthenticationSuccess(request, response, authentication);
}