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

    // OPTIONS methods is used for CORS, no auth is required with this
    // method
    if (!"OPTIONS".equals(httpRequest.getMethod())) {
      final String authHeader = httpRequest.getHeader("authorization");
      if (authHeader == null) {
        log.warn("Login failed : no auth header!");
        httpResponse.setContentType("text/html");
        httpResponse.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Unauthorized access, no authorization header.");
        return;
      }

      final String encodedValue = authHeader.split(" ")[1];
      final String[] decodedValue = Base64.base64Decode(encodedValue).split(":");

      if (decodedValue.length != 2) {
        log.warn("Login failed : malformed auth header!");
        httpResponse.setContentType("text/html");
        httpResponse.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "Unauthorized access, malformed authorization header.");
        return;
      }

      final String login = decodedValue[0];
      final String password = decodedValue[1];

      if (!USR.equals(login)) {
        log.info("Login failed for " + login);
        httpResponse.setContentType("text/html");
        httpResponse.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Unauthorized access, unknown user.");
        return;
      }

      if (!PWD.equals(password)) {
        log.info("Login failed for " + login);
        httpResponse.setContentType("text/html");
        httpResponse.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Unauthorized access, wrong password.");
        return;
      }

      log.info("Login success for " + login);
    }
    chain.doFilter(request, response);
  }
  /* This function performs the decoding of the authentication header */
  public void decodeAuthorizationHeader() {
    // check if this request has basic authentication
    if (!authHeader.contains("Basic ")) {
      throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }

    authHeader = authHeader.substring("Basic ".length());
    String[] decodedHeader;
    decodedHeader = Base64.base64Decode(authHeader).split(":");

    if (decodedHeader == null) {
      throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }

    oAuthenticationAccount.setusername(decodedHeader[0]);
    oAuthenticationAccount.setpassword(decodedHeader[1]);
  }
  protected boolean authenticate(HttpServletRequest request) {
    if (provider.isAuthenticated(request.getSession())) return true;

    String user = null, pass = null;
    String authorization = request.getHeader("Authorization");
    if (authorization != null) {
      String userpass = Base64.base64Decode(authorization.substring(6));
      user = userpass.substring(0, userpass.indexOf(":"));
      pass = userpass.substring(userpass.indexOf(":") + 1);
    }

    if (provider.authenticate(request.getSession(), user, pass)) {
      log.info("Web API authenticated " + request.getSession() + " for user " + user);
      if (user != null) {
        request.getSession().setAttribute(AUTHENTICATED_USER_SESSION_ATTRIBUTE, user);
      }
      return true;
    }

    return false;
  }
Beispiel #4
0
 @Override
 public String decode(final String value) {
   return com.sun.jersey.core.util.Base64.base64Decode(value);
 }
  @GET
  @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  // Browser XML response, XML application response and JSON application response all in the same
  // method automatically.
  public Device getDevice() {

    logger.debug("URL .../rest/devices/<device_name> called.");
    javax.naming.Context context = null; // JDBC
    DataSource dataSource = null;
    Connection connection = null;
    Device device = null;

    // Check access rights and filters

    // Get login credentials for HTTP basic authentication (over HTTPS):
    String header = headers.getRequestHeader("authorization").get(0);
    header = header.substring("Basic ".length());
    String[] creds = new String(Base64.base64Decode(header)).split(":");
    String username = creds[0];
    String password = creds[1];
    System.out.println(
        "["
            + this.getClass()
            + "] Basic HTTP authentication ('username','password'): '"
            + username
            + "','"
            + password
            + "'.");
    // Debug print. DO NOT LEAVE HERE BECAUSE EXPOSES THE CREDENTIALS TO CONSOLE/LOGS.

    // Check authorization in the case this service is accidentally installed on a non-secure Tomcat
    // server:
    if (username == null || username.length() == 0)
      throw new javax.ws.rs.WebApplicationException(
          javax.ws.rs.core.Response.Status
              .UNAUTHORIZED); // Proper HTTP 401 response when invalid user.
    /* No need to have the method introduce RuntimeExceptions in its signature, see inheritance:
    java.lang.Object
     extended by java.lang.Throwable
    	  extended by java.lang.Exception
       extended by java.lang.RuntimeException
    	    extended by javax.ws.rs.WebApplicationException */

    // Parse request parameters from a HttpServletRequest (not the Jersey way of doing things but
    // needed here because we lack context information):
    device_name = req.getParameter("device_name");
    logger_application_name = req.getParameter("logger_application_name");
    timestamp = req.getParameter("timestamp");
    start_time = req.getParameter("start_time");
    end_time = req.getParameter("end_time");

    // Test print of request parameters in different ways:
    System.out.println(
        "[" + this.getClass() + "] Full request URL: " + uriInfo.getRequestUri().toString());
    System.out.println("[" + this.getClass() + "] URL request parameters ('name','value'):");
    System.out.println("'device_name','" + device_name + "'");
    System.out.println("'logger_application_name','" + logger_application_name + "'");
    System.out.println("'timestamp','" + timestamp + "'");
    System.out.println("'start_time','" + start_time + "'");
    System.out.println("'end_time','" + end_time + "'");

    // Check access restrictions: NOT NEEDED HERE BECAUSE THE URL IDENTIFIES & VERIFIES THE USER.
    // if ( ( device_name == null || device_name.length() == 0 ) &&
    // !ConditionalAccess.NAME_DB_ADMINISTRATOR.equals(username) )
    // 	throw new javax.ws.rs.WebApplicationException(javax.ws.rs.core.Response.Status.FORBIDDEN);
    // A proper HTTP 403 response when an authenticated user has insufficient rights to the
    // resource.
    // Wikipedia (http://en.wikipedia.org/wiki/List_of_HTTP_status_codes):
    // "The request was a valid request, but the server is refusing to respond to it.[2] Unlike a
    // 401 Unauthorized response, authenticating will
    // make no difference.[2] On servers where authentication is required, this commonly means that
    // the provided credentials were successfully
    // authenticated but that the credentials still do not grant the client permission to access the
    // resource (e.g. a recognized user attempting
    // to access restricted content)."

    // Run a database request and create a REST response

    try {
      logger.debug("intializing JDBC connection.");
      context = new InitialContext();
      dataSource = (DataSource) context.lookup("java:comp/env/jdbc/postgres");
      connection = dataSource.getConnection();
      logger.debug("Got connection..");
      // Get named device from the database:
      device =
          Queries.findDevice(
              connection, deviceName); // Returns first match only or null if no device.
      logger.debug("Fetching device '" + deviceName + "' done.");
    } catch (Exception e) {
      e.printStackTrace();
      logger.warn(e.getMessage());
    } finally {
      if (context != null) {
        try {
          connection.close();
          context.close();
        } catch (Exception e) {
          System.out.print(e.toString());
        }
        context = null;
      }
    }
    if (device == null)
      //  throw new RuntimeException("GET: Device (user) with the name '" + deviceName +  "' not
      // found!");
      throw new javax.ws.rs.WebApplicationException(
          javax.ws.rs.core.Response.Status
              .NOT_FOUND); // Proper HTTP 404 response if resource was not found.
    /* No need to have the method introduce RuntimeExceptions in its signature, see inheritance:
      java.lang.Object
    extended by java.lang.Throwable
     		 extended by java.lang.Exception
       		  extended by java.lang.RuntimeException
        		   extended by javax.ws.rs.WebApplicationException */
    return device;
  }