FORM authentication<br/>
Official Example: https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org
/apache/http/examples/client/ClientFormLogin.java
776642
private void doFormLogin(FormAuthInfo authInfo) {
        logger.info("FORM authentication for: {}", authInfo.getLoginTarget());
        String fullUri =
                authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() +
                        authInfo.getLoginTarget();
        HttpPost httpPost = new HttpPost(fullUri);
        List<NameValuePair> formParams = new ArrayList<>();
        formParams.add(
                new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername()));
        formParams.add(
                new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword()));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
        httpPost.setEntity(entity);

        try {
            httpClient.execute(httpPost);
            logger.debug("Successfully request to login in with user: {} to: {}", authInfo.getUsername(),
                    authInfo.getHost());
        } catch (ClientProtocolException e) {
            logger.error("While trying to login to: {} - Client protocol not supported",
                    authInfo.getHost(), e);
        } catch (IOException e) {
            logger.error("While trying to login to: {} - Error making request", authInfo.getHost(),
                    e);
        }
    }
306745
public void authenticate(HttpURLConnection httpConn, String url) {
        String authorization = null;
        if (hasAccessToken() && isOperationOauth(url)) {
            logger.debug("Using OAuth token to authenticate");
            authorization = getAccessTokenType() + " " + getAccessToken();
        } else if (hasApiKey()) {
            logger.debug("Using API Key to authenticate");
            String apiKey = getApiKey() + ":";
            authorization = "Basic " + DatatypeConverter.printBase64Binary(apiKey.getBytes()).trim();
        }
        if (authorization != null) {
            logger.debug("Authorization: " + authorization);
            httpConn.setRequestProperty("authorization", authorization);
        }
    }
1007912
public Http auth(String username, String password) {
        return username(username).password(password);
    }
975086
public Principal authenticate(String username,
                                  Object credentials,
                                  HttpRequest request)
    {
        KnownUser user;
        synchronized (this)
        {
            user = (KnownUser)super.get(username);
        }
        if (user==null)
            return null;

        if (user.authenticate(credentials))
            return user;
        
        return null;
    }
413807
def example(host, user, password, token):
    """"""
    client = None
    try:
        if token:
            print('token login')
            client = MatrixClient(host, token=token, user_id=user)
        else:
            print('password login')
            client = MatrixClient(host)
            token = client.login_with_password(user, password)
            print('got token: %s' % token)
    except MatrixRequestError as e:
        print(e)
        if e.code == 403:
            print("Bad username or password")
            exit(2)
        elif e.code == 401:
            print("Bad username or token")
            exit(3)
        else:
            print("Verify server details.")
            exit(4)
    except MissingSchema as e:
        print(e)
        print("Bad formatting of URL.")
        exit(5)
    except InvalidSchema as e:
        print(e)
        print("Invalid URL schema")
        exit(6)
    print("is in rooms")
    for room_id, room in client.get_rooms().items():
        print(room_id)
711031
def _authenticate_client(self, client, secret):
        
        client_s = str.join(':', [client, secret])
        credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
            'Authorization': 'Basic ' + credentials
            }
        params = {
            'client_id': client,
            'grant_type': 'client_credentials'
            }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate as %s" % (client))
            response.raise_for_status()
1223905
public boolean authenticate(HttpServletRequest pRequest) {
        String auth = pRequest.getHeader("Authorization");
        if (auth == null) {
            return false;
        }
        AuthorizationHeaderParser.Result authInfo = AuthorizationHeaderParser.parse(auth);
        return authInfo.isValid() && doAuthenticate(pRequest, authInfo);
    }
1291972
@Override
    public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.authenticate(arg0);
        } finally {
            collaborator.postInvoke();
        }
    }
188626
@Override
    public Uid authenticate(
            final ObjectClass objectClass,
            final String username,
            final GuardedString password,
            final OperationOptions options) {

        LOG.ok("User uthentication");

        // check objectclass
        if (objectClass == null || (!objectClass.equals(ObjectClass.ACCOUNT))) {
            throw new IllegalArgumentException("Invalid objectclass");
        }

        // check creadentials
        if (username == null || password == null) {
            throw new IllegalArgumentException("Invalid credentuals");
        }

        // get web service client
        final Provisioning provisioning = connection.getProvisioning();
        if (provisioning == null) {
            throw new IllegalStateException("Web Service client not found");
        }

        try {
            return new Uid(provisioning.authenticate(username, password.toString()));
        } catch (ProvisioningException e) {
            throw new ConnectorException("Authentication failed", e);
        } catch (Throwable t) {
            throw new ConnectorException("Communication exception", t);
        }
    }
118912
public Principal authenticate(String username,
                                  Object credentials,
                                  HttpRequest request)
    {

    	synchronized(this)
    	{
    		long now = System.currentTimeMillis();
    		if (now - _lastHashPurge > _cacheTime || _cacheTime == 0)
    		{
    			super.clear();
    			_roles.clear();
    			_lastHashPurge = now;
    		}
    		Principal user = (Principal)super.get(username);
    		if (user == null)
    		{
    			loadUser(username);
    			user = (Principal)super.get(username);
    		}
    	}
        return super.authenticate(username, credentials, request);
    }
543534
@Override
  public Access authenticate() {
    try {
      JSONObject user = new JSONObject();
      user.put("id", mUserId);
      user.put("password", mPassword);
      JSONObject password = new JSONObject();
      password.put("user", user);
      JSONArray methods = new JSONArray();
      methods.add("password");
      JSONObject identity = new JSONObject();
      identity.put("methods", methods);
      identity.put("password", password);
      JSONObject project = new JSONObject();
      project.put("id", mProjectId);
      JSONObject scope = new JSONObject();
      scope.put("project", project);
      JSONObject auth = new JSONObject();
      auth.put("identity", identity);
      auth.put("scope", scope);
      JSONObject requestBody = new JSONObject();
      requestBody.put("auth", auth);
      HttpURLConnection connection =
          (HttpURLConnection) new URL(mAuthUrl).openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept", "application/json");
      connection.setRequestProperty("Content-Type", "application/json");
      OutputStream output = connection.getOutputStream();
      output.write(requestBody.toString().getBytes());
      HttpStatusChecker.verifyCode(STATUS_CHECKERS, connection.getResponseCode());
      final String res;
      try (final BufferedReader bufReader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        res = bufReader.readLine();
      }
      JSONParser parser = new JSONParser();
      JSONObject jsonResponse = (JSONObject) parser.parse(res);

      String token = connection.getHeaderField("X-Subject-Token");
      PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token,
          mPrefferedRegion);
      connection.disconnect();
      return access;
    } catch (IOException | ParseException e) {
      LOG.error(e.getMessage());
      throw new CommandException("Unable to execute the HTTP call or to convert the HTTP Response",
              e);
    }
  }
989843
private WebReply unprotectedSpecialURI(WebRequest webRequest, String uriName, String methodName) {
        LoginConfiguration loginConfig = webRequest.getLoginConfig();
        if (loginConfig == null)
            return null;

        String authenticationMethod = loginConfig.getAuthenticationMethod();
        FormLoginConfiguration formLoginConfig = loginConfig.getFormLoginConfiguration();
        if (formLoginConfig == null || authenticationMethod == null)
            return null;

        String loginPage = formLoginConfig.getLoginPage();
        String errorPage = formLoginConfig.getErrorPage();

        // We check to see if we are either a FORM or CLIENT_CERT auth method.
        // These are the only valid auth methods supported (CLIENT_CERT can
        // fail over to FORM).
        if (isValidAuthMethodForFormLogin(authenticationMethod) && loginPage != null && errorPage != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, " We have a custom login or error page request, web app login URL:[" + loginPage
                             + "], errorPage URL:[" + errorPage + "], and the requested URI:[" + uriName + "]");
            }
            if (loginPage.equals(uriName) || errorPage.equals(uriName)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, login or error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            } else if ((uriName != null && uriName.equals("/j_security_check")) &&
                       (methodName != null && methodName.equals("POST"))) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, login or error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            }
        } else {
            if (webRequest.getHttpServletRequest().getDispatcherType().equals(DispatcherType.ERROR)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            }
        }
        return null;
    }
697983
function pForm (url, form){
    var options = {
        method: 'POST',
        uri: url,
        form: form,
        headers: {
            'content-type': 'application/x-www-form-urlencoded'
        }
    };
    return rp(options);
}
13523
private UsernamePasswordToken usernamePassword(ServiceRequestContext ctx, AggregatedHttpMessage req) {
        // check the Basic HTTP authentication first (https://tools.ietf.org/html/rfc7617)
        final BasicToken basicToken = AuthTokenExtractors.BASIC.apply(req.headers());
        if (basicToken != null) {
            return new UsernamePasswordToken(basicToken.username(), basicToken.password());
        }

        final MediaType mediaType = req.headers().contentType();
        if (mediaType != MediaType.FORM_DATA) {
            return throwResponse(ctx, HttpStatus.BAD_REQUEST,
                                 "The content type of a login request must be '%s'.", MediaType.FORM_DATA);
        }

        final Map<String, List<String>> parameters = new QueryStringDecoder(req.contentUtf8(),
                                                                            false).parameters();
        // assume that the grant_type is "password"
        final List<String> usernames = parameters.get("username");
        final List<String> passwords = parameters.get("password");
        if (usernames != null && passwords != null) {
            final String username = usernames.get(0);
            final String password = passwords.get(0);
            return new UsernamePasswordToken(loginNameNormalizer.apply(username), password);
        }

        return throwResponse(ctx, HttpStatus.BAD_REQUEST,
                             "A login request must contain username and password.");
    }
597194
@Override
    public Result authenticate(HttpExchange httpExchange) {
        Result result = null;
        for (Authenticator a : authenticators) {
            result = a.authenticate(httpExchange);
            if ((result instanceof Success && mode == Mode.ANY) ||
                (!(result instanceof Success) && mode == Mode.ALL)) {
                return result;
            }
        }
        // Return last result, which is either SUCCESS for mode.ALL or FAILURE for mode.ANY
        return result;
    }
837104
def authenticate(self, user, password):
        

        request = Request(AUTH_URL)
        request.add_header('X-Simperium-API-Key', API_KEY)
        if sys.version_info < (3, 3):
            request.add_data(json.dumps({'username': user, 'password': password}))
        else:
            request.data = json.dumps({'username': user, 'password': password}).encode()
        try:
            res = urllib2.urlopen(request).read()
            token = json.loads(res.decode('utf-8'))["access_token"]
        except HTTPError:
            raise SimplenoteLoginFailed('Login to Simplenote API failed!')
        except IOError: # no connection exception
            token = None
        return token
1003625
private String authenticate(Credentials credentials, URI requestURI) throws AuthenticationException {
        if (!(credentials instanceof SpnegoCredentials)) {
            throw new AuthenticationException("Invalid credentials type provided to " + this.getClass().getName() + "." +
                    "Expected " + SpnegoCredentials.class.getName() + " but got " + credentials.getClass().getName());
        }
        final SpnegoCredentials spnegoCredentials = (SpnegoCredentials) credentials;
        try {
            initializeNegotiator(requestURI, spnegoCredentials);
            return getNegotiateToken();
        } catch (GSSException e) {
            throw new AuthenticationException("Could not authenticate", e);
        } catch (UnknownHostException e) {
            throw new AuthenticationException("Could not authenticate", e);
        }
    }