Java Code Examples for javax.servlet.http.HttpServletRequest#login()

The following examples show how to use javax.servlet.http.HttpServletRequest#login() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: apiman   File: AuthenticationFilter.java    License: Apache License 2.0 6 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 Project: quarkus-http   File: LoginFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    String username = req.getHeader("username");
    String password = req.getHeader("password");
    if(username == null) {
        chain.doFilter(request, response);
        return;
    }
    try {
        req.login(username, password);
        chain.doFilter(request, response);
    } catch (ServletException e) {
        ((HttpServletResponse)response).setStatus(StatusCodes.UNAUTHORIZED);
    }
}
 
Example 3
@PostMapping("login")
public String login(
		@RequestParam String username, 
        @RequestParam String password,
        HttpServletRequest request) {
    
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        return REDIRECT_MEMBER_PATH;
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        return INDEX_PATH;
    }
}
 
Example 4
@PostMapping("login")
public String login(
		@RequestParam String username, 
        @RequestParam String password,
        HttpServletRequest request) {
    
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        return REDIRECT_MEMBER_PATH;
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        return INDEX_PATH;
    }
}
 
Example 5
@PostMapping("login")
public void login(
        HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        response.sendRedirect(REDIRECT_MEMBER_PATH);
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        request.getRequestDispatcher(INDEX_PATH)
               .forward(request, response);
    }
}
 
Example 6
@PostMapping("login")
public void login(
        HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    UserService userService = (UserService) request.getServletContext().getAttribute("userService");
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        response.sendRedirect(REDIRECT_MEMBER_PATH);
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        request.getRequestDispatcher(INDEX_PATH)
               .forward(request, response);
    }
}
 
Example 7
@PostMapping("login")
public String login(
		@RequestParam String username, 
        @RequestParam String password,
        HttpServletRequest request) {
    
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        return REDIRECT_MEMBER_PATH;
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        return INDEX_PATH;
    }
}
 
Example 8
Source Project: ignite   File: WebSessionSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    if (req.getPathInfo().equals("/login")) {
        try {
            req.login("admin", "admin");
        } catch (Exception e) {
            X.printerrln("Login failed due to exception.", e);
        }

        HttpSession ses = req.getSession();

        X.println(">>>", "Logged In session: " + ses.getId(), ">>>");

        res.getWriter().write(ses.getId());

        res.getWriter().flush();
    }
}
 
Example 9
protected void doPost(
        HttpServletRequest request, HttpServletResponse response) 
                        throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    UserService userService = (UserService) getServletContext().getAttribute("userService");
    Optional<String> optionalPasswd = userService.encryptedPassword(username, password);
    
    try {
        request.login(username, optionalPasswd.get());
        request.getSession().setAttribute("login", username);
        response.sendRedirect(getInitParameter("SUCCESS_PATH"));
    } catch(NoSuchElementException | ServletException e) {
        request.setAttribute("errors", Arrays.asList("登入失敗"));
        List<Message> newest = userService.newestMessages(10);
        request.setAttribute("newest", newest);
        request.getRequestDispatcher(getInitParameter("ERROR_PATH"))
               .forward(request, response);
    }
}
 
Example 10
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 11
Source Project: Tomcat7.0.67   File: TestRequest.java    License: 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 12
Source Project: trader   File: Login.java    License: 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 13
@Override
protected void think(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();
    if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly"));
        return;
    }
    String uid = getProperty(req, "uid");
    String pwd = getProperty(req, "pwd");
    String realm = getProperty(req, "realm");
    if (uid != null && pwd != null) {
        MCRSession session = MCRSessionMgr.getCurrentSession();
        req.login(uid, pwd);
        session.setUserInformation(new Servlet3ContainerUserInformation(session, realm));
        req.getSession().setAttribute(MCRRequestAuthenticationFilter.SESSION_KEY, Boolean.TRUE);
        LOGGER.info("Logged in: {}", session.getUserInformation().getUserID());
    }
}
 
Example 14
Source Project: tomcatsrc   File: TestRequest.java    License: 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 15
Source Project: ignite   File: WebSessionFilter.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void login(String username, String password) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest)getRequest();

    req.login(username, password);

    final String newId = req.getSession(false).getId();

    if (!F.eq(newId, ses.getId())) {
        try {
            ses = createSessionV2(ses, newId);
        }
        catch (IOException e) {
            throw new IgniteException(e);
        }
    }
}
 
Example 16
Source Project: scipio-erp   File: LoginServices.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean TomcatSSOLogin(HttpServletRequest request, String userName, String currentPassword) {
    try {
        request.login(userName, currentPassword);
    } catch (ServletException e) {
        StringManager sm = StringManager.getManager("org.apache.catalina.connector");
        if (sm.getString("coyoteRequest.alreadyAuthenticated").equals(e.getMessage())){
            return true;
        } else {
            Debug.logError(e, module);
            return false;
        }
    }
    return true;
}
 
Example 17
Source Project: Tutorials   File: LoginView.java    License: Apache License 2.0 5 votes vote down vote up
public String login() {
	FacesContext context = FacesContext.getCurrentInstance();
	HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

	try {
		request.login(email, password);
	} catch (ServletException e) {
		context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed!", null));
		return "signin";
	}

	Principal principal = request.getUserPrincipal();

	this.user = userEJB.findUserById(principal.getName());

	log.info("Authentication done for user: " + principal.getName());

	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
	Map<String, Object> sessionMap = externalContext.getSessionMap();
	sessionMap.put("User", user);

	if (request.isUserInRole("users")) {
		return "/user/privatepage?faces-redirect=true";
	} else {
		return "signin";
	}
}
 
Example 18
Source Project: ignite   File: WebSessionFilter.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void login(String username, String password) throws ServletException {
    HttpServletRequest req = (HttpServletRequest)getRequest();

    req.login(username, password);

    String newId = req.getSession(false).getId();

    this.ses.setId(newId);

    this.ses = createSession(ses, newId);
    this.ses.servletContext(ctx);
    this.ses.filter(WebSessionFilter.this);
    this.ses.resetUpdates();
}
 
Example 19
Source Project: tomee   File: LogginServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.login(req.getParameter("myUser"), req.getParameter("myPass"));
    // think to persist the information in the session if you need it later
    resp.getWriter().write("logged user ==> " + bean.info() + "; isUserInRole(admin)? " + req.isUserInRole("admin"));
}
 
Example 20
Source Project: sailfish-core   File: AuthBean.java    License: Apache License 2.0 3 votes vote down vote up
public void login() throws IOException {

		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext externalContext = context.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

		try {

			request.login(username, password + PasswordHasher.getSalt());

			User user = BeanUtil.getSfContext().getAuthStorage().getUser(username);

			if (user == null) {

                logger.error("User with login [{}] not found in storage!", username);

				BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR,
						"Invalid login/password pair", "");

				return;
			}

			externalContext.getSessionMap().put(BeanUtil.KEY_USER, user);

			externalContext.redirect(originalURL);

		} catch (ServletException e) {

			// Handle unknown username/password in request.login().
            logger.warn("Bad login attempt with username [{}]; message: {}", username, e.getMessage());
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Invalid login/password pair", "");

			return;
		}

		logger.info("Successful login for user [{}]", username);
	}