Example usage for javax.servlet.http HttpServletRequest login

List of usage examples for javax.servlet.http HttpServletRequest login

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest login.

Prototype

public void login(String username, String password) throws ServletException;

Source Link

Document

Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.

Usage

From source file:dk.dma.msinm.user.security.SecurityUtils.java

/**
 * Attempts to log-in the user./*from  w w w. j  av a  2  s.  co  m*/
 * <p>
 * The web-app is using a custom login-module, {@linkplain JbossLoginModule}, and the
 * natural solution would be that this module set the {@code User} as the user principal
 * upon successful authentication.
 * <br>
 * However, this tends to cause ClassCastException's when the web-app has been reloaded,
 * because a different class-loader is used for the login-modules.
 * <br>
 * Hence, the login-module sets a {@code SimplePrincipal} as the request user principal, and this
 * method swaps the {@code SimplePrincipal} for a {@code User} principal.
 *
 * @param userService the user service
 * @param request the servlet request
 * @param username the user name
 * @param password the password
 * @return the updated request
 */
public static HttpServletRequest login(UserService userService, HttpServletRequest request, String username,
        String password) throws ServletException {
    // Will throw an exception if the login fails
    //request.logout();
    request.login(username, password);

    // The email is used as it is unique for the user
    String email = request.getUserPrincipal().getName();
    final User user = userService.findByEmail(email);
    return new HttpServletRequestWrapper(request) {
        @Override
        public java.security.Principal getUserPrincipal() {
            return user;
        }
    };
}

From source file:de.mare.mobile.ui.jsf.pages.LoginPage.java

/**
 * Perform login of the user//from  www  .  ja v  a  2 s  .c  om
 * 
 */
public String loginAction() {

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    try {
        request.login(this.username, this.password);
        String username = request.getUserPrincipal().getName();
        User currentUser = userRepository.findUser(username);
        userSession.setUser(currentUser);
        LOG.info("username is: " + username);
    } catch (ServletException e) {
        if (StringUtils.contains(e.getMessage(), "User already logged in")) {
            String username = request.getUserPrincipal().getName();
            User currentUser = userRepository.findUser(username);
            userSession.setUser(currentUser);
            LOG.info("User already loggedn in");
            LOG.info("username is: " + username);
        } else {
            context.addMessage(null, new FacesMessage("Login failed."));
            return "login.error";
        }

    }
    return "portal.start";
}

From source file:be.fedict.hsm.admin.webapp.security.AuthenticationController.java

public void login(ComponentSystemEvent event) {
    LOG.debug("login");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext.getResponseComplete()) {
        return;/*from   ww w . j a v  a 2 s. c o m*/
    }
    if (null == this.authenticationCertificate) {
        /*
         * Caused by a direct navigation to post-login.jsf
         */
        redirect(facesContext, "/index.xhtml");
        return;
    }
    byte[] encodedCertificate;
    try {
        encodedCertificate = this.authenticationCertificate.getEncoded();
    } catch (CertificateEncodingException e) {
        LOG.error("certificate encoding error: " + e.getMessage(), e);
        return;
    }
    /*
     * The challenged certificate is the unique user identifier.
     */
    String username = DigestUtils.sha1Hex(encodedCertificate);
    String password = this.identity.getCardNumber();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    try {
        httpServletRequest.login(username, password);
    } catch (ServletException e) {
        LOG.error("login error: " + e.getMessage(), e);
        accessDenied(facesContext);
        return;
    }
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        accessDenied(facesContext);
        return;
    }
    LOG.debug("user principal: " + userPrincipal.getName());
    LOG.debug("admin role: " + httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR));
    if (false == httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR)) {
        accessDenied(facesContext);
        return;
    }
    String targetViewId = SecurityPhaseListener.getTargetViewId(externalContext);
    redirect(facesContext, targetViewId);
}

From source file:org.artificer.server.filters.MavenRepositoryAuthFilter.java

/**
 * Validates the basic authentication credentials.
 * @param credentials/*from w  w w  .  ja v  a 2s  .  c  om*/
 * @param request
 * @param response
 * @throws IOException 
 */
protected boolean login(Creds credentials, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {
        request.login(credentials.username, credentials.password);
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:xbdd.webapp.rest.BasicAuthFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (httpRequest.getUserPrincipal() == null) {
        final String basicAuth = httpRequest.getHeader(AUTHORIZATION_HEADER);

        if (basicAuth != null && StringUtils.startsWithIgnoreCase(basicAuth, BASIC_PREFIX)) {
            final String usernamePassword = new String(
                    Base64.decodeBase64(basicAuth.substring(BASIC_PREFIX.length()).trim()), "UTF-8");
            final String[] args = usernamePassword.split(BASIC_AUTH_SEPARATOR, 2);
            httpRequest.login(args[0], args[1]);
        } else {/*from w  ww .  j a v  a  2s . c o m*/
            httpRequest.authenticate(httpResponse);
            return;
        }
    }

    filterChain.doFilter(request, response);
}

From source file:io.hops.hopsworks.api.user.AuthService.java

private void login(Users user, String email, String password, HttpServletRequest req) throws UserException {
    if (user == null) {
        throw new IllegalArgumentException("User not set.");
    }//from w w  w .j a v  a2  s  .  co  m
    if (user.getBbcGroupCollection() == null || user.getBbcGroupCollection().isEmpty()) {
        throw new UserException(RESTCodes.UserErrorCode.NO_ROLE_FOUND, Level.FINE);
    }
    if (statusValidator.checkStatus(user.getStatus())) {
        try {
            req.login(email, password);
            authController.registerLogin(user, req);
        } catch (ServletException e) {
            LOGGER.log(Level.WARNING, e.getMessage());
            authController.registerAuthenticationFailure(user, req);
            throw new UserException(RESTCodes.UserErrorCode.AUTHENTICATION_FAILURE, Level.SEVERE, null,
                    e.getMessage(), e);
        }
    } else { // if user == null
        throw new UserException(RESTCodes.UserErrorCode.AUTHENTICATION_FAILURE, Level.INFO);
    }
}

From source file:io.apiman.common.servlet.AuthenticationFilter.java

/**
 * Handle BASIC authentication.  Delegates this to the container by invoking 'login'
 * on the inbound http servlet request object.
 * @param credentials//from   w w w . ja v a  2 s. c  o  m
 * @param request
 * @param response
 * @param chain
 * @throws IOException
 * @throws ServletException
 */
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((HttpServletResponse) response);
        return;
    }
    doFilterChain(request, response, chain, null);
}

From source file:io.zipi.common.servlet.AuthenticationFilter.java

/**
 * Handle BASIC authentication.  Delegates this to the container by invoking 'login'
 * on the inbound http servlet request object.
 * @param credentials the credentials/*w ww .  ja v  a  2 s .co  m*/
 * @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);
}

From source file:photosharing.api.LoginServlet.java

/**
 * Manages the authorization for a given user, creates a session or returns session invalid
 * //from  w ww .  j  a v a  2  s  .c om
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /*
     * Checks to see if the User is logged in forces logout for any existing user, you wouldn't actually do this in production
     */
    Principal user = request.getUserPrincipal();
    if (user != null) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        request.logout();

    }

    /*
     * Authorizes the User
     */
    String auth = request.getHeader("Authorization");

    if (auth != null && !auth.isEmpty()) {
        auth = auth.replace("Basic ", "");

        String authDecoded = new String(Base64.decodeBase64(auth));

        String[] creds = authDecoded.split(":");
        String username = creds[0];
        String password = creds[1];
        try {
            request.login(username, password);
            request.getSession(true);
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

    } else {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
    }

}

From source file:ub.botiga.ServletDispatcher.java

private void controlWebServices(HttpServletRequest request, HttpServletResponse response) throws IOException {

    /*/*from w  ww. j a  v  a 2 s.c om*/
    Camps del JSON:
        - status: LIMIT_INFERIOR_SALDO,
          LIMIT_SUPERIOR_SALDO,
          INVALID_STRING_SALDO,
          INVALID_USER_PASS,
          OK
        - saldoactual: saldoanterior + saldo nou
    */

    JSONObject obj = new JSONObject();

    String user = request.getParameter("user");
    String pass = request.getParameter("pass");
    int augment = 0;
    JSONArray status = new JSONArray();
    boolean correct = true;
    try {
        augment = Integer.parseInt(request.getParameter("saldo"));
        if (augment < 5) {
            status.put("LIMIT_INFERIOR_SALDO");
            correct = false;
        }
        if (augment > 3000) {
            status.put("LIMIT_SUPERIOR_SALDO");
            correct = false;
        }
    } catch (NumberFormatException ex) {
        status.put("INVALID_STRING_SALDO");
        correct = false;
    }

    float saldoactual = -1;

    try {
        request.login(user, pass);
        User u = data.getUsers().get(user);
        if (correct) {
            status.put("OK");
            data.augmentarSaldo(u, augment);
            saldoactual = u.getCredits();
        }
        request.getSession().invalidate();
    } catch (ServletException ex) {
        status.put("INVALID_USER_PASS");
    }
    try {
        obj.put("status", status);
        if (saldoactual >= 0)
            obj.put("saldoactual", saldoactual);
    } catch (JSONException ex) {
        Logger.getLogger(ServletDispatcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    /********************************/
    /*     Retornem un json
    /********************************/

    try {
        response.setContentType("application/json");
        // Get the printwriter object from response to write the required json object to the output stream      
        PrintWriter out = response.getWriter();
        // Assuming your json object is **jsonObject**, perform the following, it will return your json object
        out.print(obj.toString(2));
        out.close();
    } catch (JSONException ex) {
        Logger.getLogger(ServletDispatcher.class.getName()).log(Level.SEVERE, null, ex);
    }
}