Java Code Examples for javax.servlet.http.httpservletrequest#logout()

The following examples show how to use javax.servlet.http.httpservletrequest#logout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationFilter.java    From apiman with Apache License 2.0 7 votes vote down vote up
/**
 * Handle BASIC authentication.  Delegates this to the container by invoking 'login'
 * on the inbound http servlet request object.
 * @param credentials the credentials
 * @param request the http servlet request
 * @param response the http servlet respose
 * @param chain the filter chain
 * @throws IOException when I/O failure occurs in filter chain
 * @throws ServletException when servlet exception occurs during auth
 */
protected void doBasicAuth(Creds credentials, HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        if (credentials.username.equals(request.getRemoteUser())) {
            // Already logged in as this user - do nothing.  This can happen
            // in some app servers if the app server processes the BASIC auth
            // credentials before this filter gets a crack at them.  WildFly 8
            // works this way, for example (despite the web.xml not specifying
            // any login config!).
        } else if (request.getRemoteUser() != null) {
            // switch user
            request.logout();
            request.login(credentials.username, credentials.password);
        } else {
            request.login(credentials.username, credentials.password);
        }
    } catch (Exception e) {
        // TODO log this error?
        e.printStackTrace();
        sendAuthResponse(response);
        return;
    }
    doFilterChain(request, response, chain, null);
}
 
Example 2
Source File: TestRequest.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.login(USER, PWD);

    if (!req.getRemoteUser().equals(USER))
        throw new ServletException();
    if (!req.getUserPrincipal().getName().equals(USER))
        throw new ServletException();

    req.logout();

    if (req.getRemoteUser() != null)
        throw new ServletException();
    if (req.getUserPrincipal() != null)
        throw new ServletException();

    resp.getWriter().write(OK);
}
 
Example 3
Source File: Login.java    From trader with Apache License 2.0 6 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	boolean success = false;
	String id = request.getParameter("id");
	String password = request.getParameter("password");

	try {
		if (request.getUserPrincipal() != null) request.logout(); //in case there's a left over auth cookie but we ended up here

		request.login(id, password);

		Cookie cookie = new Cookie("user", id); //clear text user id that can be used in Istio routing rules
		response.addCookie(cookie);

		success = true;
		logger.info("Successfully logged in user: "+id);
	} catch (Throwable t) {
		logException(t);
	}

	String url = "error";
	if (success) url = "summary";

	response.sendRedirect(url);
}
 
Example 4
Source File: ProtectedServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String realm = req.getPathInfo().split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }

    if (req.getPathInfo().contains("logout")) {
        req.logout();
        resp.sendRedirect(req.getContextPath() + "/" + realm);
        return;
    }

    KeycloakPrincipal principal = (KeycloakPrincipal) req.getUserPrincipal();

    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();

    writer.write("Realm: ");
    writer.write(principal.getKeycloakSecurityContext().getRealm());

    writer.write("<br/>User: ");
    writer.write(principal.getKeycloakSecurityContext().getIdToken().getPreferredUsername());

    writer.write(String.format("<br/><a href=\"/multitenant/%s/logout\">Logout</a>", realm));
}
 
Example 5
Source File: UserFacade.java    From aws-photosharing-example with Apache License 2.0 6 votes vote down vote up
public boolean login(String p_username, String p_password, HttpServletRequest req) {		
	try {			
		req.logout();
		beginTx();
			User u = findUser(p_username);
		
			if (u == null) {
                   _logger.info("User with username " + p_username + " not found");
                   commitTx();	
                   return false;
               }
		
			req.login(u.getId().toString(), Security.getPasswordHash(p_password, u.getSalt()));
			
			u.updatePassword(p_password);				
			u.setLastLogin(new Date());
		commitTx();			
		return true;
	} catch (ServletException e) {
		_logger.error(e.getMessage(), e);
		return false;
	}		
}
 
Example 6
Source File: HomeController.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/logout", method = RequestMethod.GET)
  public ModelAndView logOut(SecurityContextHolder sch,HttpServletRequest request) throws ServletException {
  	ModelAndView mav = new ModelAndView("home");
request.logout();
  	//sch.getContext().setAuthentication(null);
//sch.clearContext();
      return mav;
  }
 
Example 7
Source File: HomeController.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logOut(SecurityContextHolder sch, HttpServletRequest request) throws ServletException {
	ModelAndView mav = new ModelAndView("home");
	request.logout();
	//sch.getContext().setAuthentication(null);
	//sch.clearContext();
	return mav;
}
 
Example 8
Source File: KeycloakLogoutServlet.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.logout();
    String logoutRedirect = config.getLogoutRedirectUri();
    resp.sendRedirect(logoutRedirect);
}
 
Example 9
Source File: CustomerDatabaseServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.logout();
    PrintWriter pw = resp.getWriter();
    pw.println("<div id=\"customer_database_logout\">servlet logout from database ok</div>");
    pw.flush();  
}
 
Example 10
Source File: TestServlet.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if ("true".equals(request.getParameter("logout"))) {
        request.logout();
        request.getSession().invalidate();
    }
    
    doGet(request, response);
}
 
Example 11
Source File: LogoutServlet.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
        IOException {
    req.logout();
    if (req.getSession() != null && !req.getSession().isNew()) {
        req.getSession().invalidate();
    }
    resp.sendRedirect("/apimanui"); //$NON-NLS-1$
}
 
Example 12
Source File: SessionServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getRequestURI().endsWith("/logout")) {
        req.logout();
        return;
    }

    String counter;
    String counterWrapperValue;
    if (req.getRequestURI().endsWith("/donotincrease")) {
        counter = getCounter(req);
        counterWrapperValue = getCounterWrapper(req);
    } else {
        counter = increaseAndGetCounter(req);
        counterWrapperValue = increaseAndGetCounterWrapper(req);
    }

    resp.setContentType("text/html");
    PrintWriter pw = resp.getWriter();
    pw.printf("<html><head><title>%s</title></head><body>", "Session Test");
    pw.printf("Counter=%s<br>", counter);
    pw.printf("CounterWrapper=%s<br>", counterWrapperValue);
    pw.printf("Node name=%s<br>", System.getProperty("jboss.node.name", "property not specified"));
    pw.print("</body></html>");
    pw.flush();


}
 
Example 13
Source File: TestServlet.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if ("true".equals(request.getParameter("logout"))) {
        request.logout();
        request.getSession().invalidate();
    }
    
    doGet(request, response);
}
 
Example 14
Source File: CustomerServletNoConf.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        if (req.getRequestURI().endsWith("logout")) {
            resp.setStatus(200);
            pw.println("servlet logout ok");

            // Call logout before pw.flush
            req.logout();
            pw.flush();
            return;
        }
        KeycloakSecurityContext context = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

        //try {
        StringBuilder result = new StringBuilder();
        String urlBase;

        if (System.getProperty("app.server.ssl.required", "false").equals("true")) {
            urlBase = System.getProperty("app.server.ssl.base.url", "https://localhost:8643");
        } else {
            urlBase = System.getProperty("app.server.base.url", "http://localhost:8280");
        }

        URL url = new URL(urlBase + "/customer-db/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + context.getTokenString());
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        resp.setContentType("text/html");
        pw.println(result.toString());
        pw.flush();
//
//            Response response = target.request().get();
//            if (response.getStatus() != 401) { // assert response status == 401
//                throw new AssertionError("Response status code is not 401.");
//            }
//            response.close();
//            String html = target.request()
//                                .header(HttpHeaders.AUTHORIZATION, "Bearer " + context.getTokenString())
//                                .get(String.class);
//            pw.println(html);
//            pw.flush();
//        } finally {
//            client.close();
//        }
    }
 
Example 15
Source File: AccessController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@GetMapping("logout")
public void logout(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    request.logout(); 
    response.sendRedirect(REDIRECT_INDEX_PATH);
}
 
Example 16
Source File: AccessController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@GetMapping("logout")
public String logout(HttpServletRequest request) throws ServletException {
    request.logout(); 
    return REDIRECT_INDEX_PATH;
}
 
Example 17
Source File: AccessController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@GetMapping("logout")
public String logout(HttpServletRequest request) throws ServletException {
    request.logout(); 
    return REDIRECT_INDEX_PATH;
}
 
Example 18
Source File: Logout.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected void doGet(
        HttpServletRequest request, HttpServletResponse response) 
                      throws ServletException, IOException {
    request.logout(); 
    response.sendRedirect(getInitParameter("LOGIN_PATH"));
}
 
Example 19
Source File: PersonApplication.java    From blog with Apache License 2.0 4 votes vote down vote up
@GetMapping(path = "/logout")
public String logout(HttpServletRequest request) throws ServletException {
    request.logout();
    return "/";
}
 
Example 20
Source File: LoginWorker.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static void doBasicLogout(GenericValue userLogin, HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();

    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");

    // SCIPIO: We do NOT do this for the anonymous user. Core login should recognize this user.
    //if (security != null && userLogin != null) {
    if (security != null && userLogin != null && !"anonymous".equals(userLogin.getString("userLoginId"))) {
        security.clearUserData(userLogin);
    }

    // set the logged out flag
    // SCIPIO: We do NOT do this for the anonymous user. Core login should recognize this user.
    //if (userLogin != null) {
    if (userLogin != null && !"anonymous".equals(userLogin.getString("userLoginId"))) {
        LoginWorker.setLoggedOut(userLogin.getString("userLoginId"), delegator);
    }

    // this is a setting we don't want to lose, although it would be good to have a more general solution here...
    String currCatalog = (String) session.getAttribute("CURRENT_CATALOG_ID");
    // also make sure the delegatorName is preserved, especially so that a new Visit can be created
    String delegatorName = (String) session.getAttribute("delegatorName");
    // also save the shopping cart if we have one
    // DON'T save the cart, causes too many problems: security issues with things done in cart to easy to miss, especially bad on public systems; was put in here because of the "not me" link for auto-login stuff, but that is a small problem compared to what it causes
    //ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");

    // clean up some request attributes to which may no longer be valid now that user has logged out
    request.removeAttribute("delegator");
    request.removeAttribute("dispatcher");
    request.removeAttribute("security");

    // now empty out the session
    session.invalidate();
    session = request.getSession(true);

    if (EntityUtilProperties.propertyValueEquals("security", "security.login.tomcat.sso", "true")){
        try {
            // log out from Tomcat SSO
            request.logout();
        } catch (ServletException e) {
            Debug.logError(e, module);
        }
    }

    // setup some things that should always be there
    UtilHttp.setInitialRequestInfo(request);

    if (currCatalog != null) session.setAttribute("CURRENT_CATALOG_ID", currCatalog);
    if (delegatorName != null) {
        //Commented it as multi tenancy support is now available for front-store application as well.
        // if there is a tenantId in the delegatorName remove it now so that tenant selection doesn't last beyond logout
        /*if (delegatorName.indexOf('#') > 0) {
            delegatorName = delegatorName.substring(0, delegatorName.indexOf('#'));
        }*/
        session.setAttribute("delegatorName", delegatorName);

        delegator = DelegatorFactory.getDelegator(delegatorName);
        LocalDispatcher dispatcher = ContextFilter.makeWebappDispatcher(session.getServletContext(), delegator);
        setWebContextObjects(request, response, delegator, dispatcher);
    }

    // DON'T save the cart, causes too many problems: if (shoppingCart != null) session.setAttribute("shoppingCart", new WebShoppingCart(shoppingCart, session));
}