Construct new security handler for basic authentication.
329507
public SecurityHandler getObject() throws Exception {
        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        securityHandler.setAuthenticator(authenticator);
        securityHandler.setRealmName(realm);

        for (Entry<String, Constraint> constraint : constraints.entrySet()) {
            ConstraintMapping constraintMapping = new ConstraintMapping();
            constraintMapping.setConstraint(constraint.getValue());
            constraintMapping.setPathSpec(constraint.getKey());

            securityHandler.addConstraintMapping(constraintMapping);
        }

        securityHandler.setLoginService(loginService);

        return securityHandler;
    }
278217
protected function passwordProtectedRequest()
    {
        $oInput = Factory::service('Input');
        header('WWW-Authenticate: Basic realm="' . APP_NAME . ' - Restricted Area"');
        header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
        $oErrorHandler = Factory::service('ErrorHandler');
        $oErrorHandler->renderErrorView(401);
        exit(401);
    }
100508
def _basic_auth_str(username, password):
    """"""

    authstr = 'Basic ' + to_native_string(
        b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
    )

    return authstr
551866
def http_basic_auth_login_required(func=None):
    """"""

    wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])

    # If @http_basic_auth_login_required() is used (with parenthesis)
    if func is None:
        return wrapper

    # If @http_basic_auth_login_required is used without parenthesis
    return wrapper(func)
351442
def _require_auth(fnc):
    """"""
    @wraps(fnc)
    @_assure_identity
    def _wrapped(*args, **kwargs):
        if not identity.authenticated:
            msg = "Authentication required before calling '%s'." % fnc.__name__
            raise exc.NotAuthenticated(msg)
        return fnc(*args, **kwargs)
    return _wrapped
967133
def securityHandler(self, value):
        
        if isinstance(value, BaseSecurityHandler):
            if isinstance(value, security.AGOLTokenSecurityHandler):
                self._securityHandler = value
            elif isinstance(value, security.OAuthSecurityHandler):
                self._securityHandler = value
            else:
                pass
654476
def basicauth(self, realm = b'all', nofail = False):
        ""
        if b'authorization' in self.headerdict:
            auth = self.headerdict[b'authorization']
            auth_pair = auth.split(b' ', 1)
            if len(auth_pair) < 2:
                raise HttpInputException('Authorization header is malformed')
            if auth_pair[0].lower() == b'basic':
                try:
                    userpass = base64.b64decode(auth_pair[1])
                except Exception:
                    raise HttpInputException('Invalid base-64 string')
                userpass_pair = userpass.split(b':', 1)
                if len(userpass_pair) != 2:
                    raise HttpInputException('Authorization header is malformed')
                return userpass_pair
        if nofail:
            return (None, None)
        else:
            self.basicauthfail(realm)
911820
def create_security_handler(version, revision, params)

            # Ensure the document has an ID.
            doc_id = (trailer_key(:ID) || generate_id).first

            # Create the standard encryption dictionary.
            handler = Encryption::Standard::Dictionary.new
            handler.Filter = :Standard
            handler.V = version
            handler.R = revision
            handler.Length = params[:key_size]
            handler.P = -1 # params[:Permissions]

            # Build the crypt filter dictionary.
            if revision >= 4
                handler.EncryptMetadata = params[:encrypt_metadata]
                handler.CF = Dictionary.new
                crypt_filter = Encryption::CryptFilterDictionary.new
                crypt_filter.AuthEvent = :DocOpen

                if revision == 4
                    crypt_filter.CFM = :AESV2
                else
                    crypt_filter.CFM = :AESV3
                end

                crypt_filter.Length = params[:key_size] >> 3

                handler.CF[:StdCF] = crypt_filter
                handler.StmF = handler.StrF = :StdCF
            end

            user_passwd, owner_passwd = params[:user_passwd], params[:owner_passwd]

            # Setup keys.
            handler.set_passwords(owner_passwd, user_passwd, doc_id)
            encryption_key = handler.compute_user_encryption_key(user_passwd, doc_id)

            # Install the encryption dictionary to the document.
            self.trailer.Encrypt = self << handler

            [ handler, encryption_key ]
        end
138647
def handle_security(controller, im_self=None):
    
    if controller._pecan.get('secured', False):
        check_permissions = controller._pecan['check_permissions']

        if isinstance(check_permissions, six.string_types):
            check_permissions = getattr(
                im_self or six.get_method_self(controller),
                check_permissions
            )

        if not check_permissions():
            raise exc.HTTPUnauthorized
1311112
def basic_auth(user, password, realm=None):
    
    from neobolt.security import AuthToken
    return AuthToken("basic", user, password, realm)
1144752
def _auth(uri):
    '''
    
    '''

    user, password = _get_credentials()
    if user is False or password is False:
        return False

    basic = _HTTPBasicAuthHandler()
    basic.add_password(realm='Tomcat Manager Application', uri=uri,
                       user=user, passwd=password)
    digest = _HTTPDigestAuthHandler()
    digest.add_password(realm='Tomcat Manager Application', uri=uri,
                        user=user, passwd=password)
    return _build_opener(basic, digest)
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
1088144
def create_auth_manifest(**kwargs):
    
    class AuthProgram(Program):
        pre_input_middleware = [AuthenticationMiddleware]

    def register(username, password, password2):
        """
        Decorated version of basic_register with a callback added.
        """
        result = basic_register(username, password, password2)
        callback = kwargs.get('post_register_callback', None)
        if callback:
            user = User.objects.get(username=username)
            callback(user)
        return result

    return Manifest({
        'login': [
            AuthProgram(
                """
                Prints out the HTML form for logging in.
                """,
                name="Login (form)",
                input_middleware=[NotAuthenticatedOrRedirect('/')],
                view=BasicView(
                    html=jinja_template('login.html'),
                ),
            ),
            AuthProgram(
                """
                Matches up the username/password against the database, and adds the auth cookies.
                """,
                name="Login (post)",
                input_middleware=[NotAuthenticatedOrDie],
                controllers=['http-post', 'cmd'],
                model=[create_session, {'username': 'mock_user', 'session_key': 'XXXXXXXXXXXXXXX'}],
                view=BasicView(
                    persist=lambda m: {'giotto_session': m['session_key']},
                    html=lambda m: Redirection('/'),
                ),
            ),
        ],
        'logout': AuthProgram(
            """
            Send the user here to log them out. Removes their cookies and deletes the auth session.
            """,
            name="Logout",
            view=BasicView(
                html=Redirection('/'),
            ),
            output_middleware=[LogoutMiddleware],
        ),
        'register': [
            AuthProgram(
                """
                This program returns the HTML page with the form for registering a new account.
                HTTP-get only.
                """,
                name="Register (form)",
                input_middleware=[NotAuthenticatedOrRedirect('/')],
                view=BasicView(
                    html=jinja_template('register.html'),
                ),
            ),
            AuthProgram(
                """
                When you POST the register form, this program handles creating the new user, then redirecting you to '/'
                """,
                name="Register (post)",
                controllers=['http-post'],
                model=[register],
                view=BasicView(
                    persist=lambda m: {'giotto_session': m['session_key']},
                    html=lambda m: Redirection('/'),
                ),
            ),
        ],
    })
831483
function useBasicAuth() {
  return new Promise((resolve, reject) => {
    if (!defaults.userToken || !defaults.masterToken) {
      reject(__generateFakeResponse__(0, '', {}, 'userToken or masterToken are missing for basic authentication'))
    }
    else {
      let details = {
        "token_type": "Basic",
        "expires_in": 0,
        "appName": defaults.appName,
        "username": "",
        "role": "",
        "firstName": "",
        "lastName": "",
        "fullName": "",
        "regId": 0,
        "userId": null
      };
      let basicToken = 'Basic ' + createBasicToken(defaults.masterToken, defaults.userToken);
      utils.storage.set('user', {
        token: {
          Authorization:  basicToken
        },
        details: details
      });
      resolve(__generateFakeResponse__(200, 'OK', {}, details, {}));
    }
  });

}
900952
def authenticationReject():
    """"""
    a = TpPd(pd=0x5)
    b = MessageType(mesType=0x11)  # 00010001
    packet = a / b
    return packet
1172195
def _authenticate_plain(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')
    cmd = SON([('saslStart', 1),
               ('mechanism', 'PLAIN'),
               ('payload', Binary(payload)),
               ('autoAuthorize', 1)])
    sock_info.command(source, cmd)
1329826
private void configureSecurity(ServletContextHandler context, String realmName, String authMethod,
								   String formLoginPage, String formErrorPage) {
		final SecurityHandler securityHandler = context.getSecurityHandler();

		Authenticator authenticator = null;
		if (authMethod == null) {
			LOG.warn("UNKNOWN AUTH METHOD: " + authMethod);
		} else {
			switch (authMethod) {
				case Constraint.__FORM_AUTH:
					authenticator = new FormAuthenticator();
					securityHandler.setInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE, formLoginPage);
					securityHandler.setInitParameter(FormAuthenticator.__FORM_ERROR_PAGE, formErrorPage);
					break;
				case Constraint.__BASIC_AUTH:
					authenticator = new BasicAuthenticator();
					break;
				case Constraint.__DIGEST_AUTH:
					authenticator = new DigestAuthenticator();
					break;
				case Constraint.__CERT_AUTH:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__CERT_AUTH2:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__SPNEGO_AUTH:
					authenticator = new SpnegoAuthenticator();
					break;
				default:
					authenticator = getAuthenticator(authMethod);
					break;
			}
		}

		securityHandler.setAuthenticator(authenticator);

		securityHandler.setRealmName(realmName);

	}