示例#1
0
    def test_authorization_header(self):
        a = http.parse_authorization_header("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
        assert a.type == "basic"
        assert a.username == "Aladdin"
        assert a.password == "open sesame"

        a = http.parse_authorization_header(
            "Basic 0YDRg9GB0YHQutC40IE60JHRg9C60LLRiw=="
        )
        assert a.type == "basic"
        assert a.username == "русскиЁ"
        assert a.password == "Буквы"

        a = http.parse_authorization_header("Basic 5pmu6YCa6K+dOuS4reaWhw==")
        assert a.type == "basic"
        assert a.username == "普通话"
        assert a.password == "中文"

        a = http.parse_authorization_header(
            '''Digest username="******",
            realm="*****@*****.**",
            nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
            uri="/dir/index.html",
            qop=auth,
            nc=00000001,
            cnonce="0a4f113b",
            response="6629fae49393a05397450978507c4ef1",
            opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
        )
        assert a.type == "digest"
        assert a.username == "Mufasa"
        assert a.realm == "*****@*****.**"
        assert a.nonce == "dcd98b7102dd2f0e8b11d0f600bfb0c093"
        assert a.uri == "/dir/index.html"
        assert a.qop == "auth"
        assert a.nc == "00000001"
        assert a.cnonce == "0a4f113b"
        assert a.response == "6629fae49393a05397450978507c4ef1"
        assert a.opaque == "5ccc069c403ebaf9f0171e9517f40e41"

        a = http.parse_authorization_header(
            '''Digest username="******",
            realm="*****@*****.**",
            nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
            uri="/dir/index.html",
            response="e257afa1414a3340d93d30955171dd0e",
            opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
        )
        assert a.type == "digest"
        assert a.username == "Mufasa"
        assert a.realm == "*****@*****.**"
        assert a.nonce == "dcd98b7102dd2f0e8b11d0f600bfb0c093"
        assert a.uri == "/dir/index.html"
        assert a.response == "e257afa1414a3340d93d30955171dd0e"
        assert a.opaque == "5ccc069c403ebaf9f0171e9517f40e41"

        assert http.parse_authorization_header("") is None
        assert http.parse_authorization_header(None) is None
        assert http.parse_authorization_header("foo") is None
示例#2
0
    def test_authorization_header(self):
        a = http.parse_authorization_header("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
        assert a.type == "basic"
        assert a.username == u"Aladdin"
        assert a.password == u"open sesame"

        a = http.parse_authorization_header(
            "Basic 0YDRg9GB0YHQutC40IE60JHRg9C60LLRiw=="
        )
        assert a.type == "basic"
        assert a.username == u"русскиЁ"
        assert a.password == u"Буквы"

        a = http.parse_authorization_header("Basic 5pmu6YCa6K+dOuS4reaWhw==")
        assert a.type == "basic"
        assert a.username == u"普通话"
        assert a.password == u"中文"

        a = http.parse_authorization_header(
            '''Digest username="******",
            realm="*****@*****.**",
            nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
            uri="/dir/index.html",
            qop=auth,
            nc=00000001,
            cnonce="0a4f113b",
            response="6629fae49393a05397450978507c4ef1",
            opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
        )
        assert a.type == "digest"
        assert a.username == "Mufasa"
        assert a.realm == "*****@*****.**"
        assert a.nonce == "dcd98b7102dd2f0e8b11d0f600bfb0c093"
        assert a.uri == "/dir/index.html"
        assert a.qop == "auth"
        assert a.nc == "00000001"
        assert a.cnonce == "0a4f113b"
        assert a.response == "6629fae49393a05397450978507c4ef1"
        assert a.opaque == "5ccc069c403ebaf9f0171e9517f40e41"

        a = http.parse_authorization_header(
            '''Digest username="******",
            realm="*****@*****.**",
            nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
            uri="/dir/index.html",
            response="e257afa1414a3340d93d30955171dd0e",
            opaque="5ccc069c403ebaf9f0171e9517f40e41"'''
        )
        assert a.type == "digest"
        assert a.username == "Mufasa"
        assert a.realm == "*****@*****.**"
        assert a.nonce == "dcd98b7102dd2f0e8b11d0f600bfb0c093"
        assert a.uri == "/dir/index.html"
        assert a.response == "e257afa1414a3340d93d30955171dd0e"
        assert a.opaque == "5ccc069c403ebaf9f0171e9517f40e41"

        assert http.parse_authorization_header("") is None
        assert http.parse_authorization_header(None) is None
        assert http.parse_authorization_header("foo") is None
示例#3
0
def parse(region, service, headers):
    if 'Authorization' not in headers:
        raise exceptions.Unsigned()

    auth_header = headers.get('Authorization')
    if not auth_header.startswith('Basic '):
        raise exceptions.Unsigned()

    auth = parse_authorization_header(auth_header)
    if not auth:
        raise exceptions.InvalidSignature()

    date = datetime.datetime.utcnow()

    key = current_app.auth_backend.get_access_key(
        'basic-auth',
        region,
        service,
        date.date(),
        auth.username,
    )

    secret = make_basic_auth_key(
        region,
        service,
        date,
        auth.username,
        auth.password,
    )

    if not hmac.compare_digest(key['key'], secret):
        raise exceptions.InvalidSignature()

    return key['identity'], False
示例#4
0
def _authorize_login(region, service, action, resource, headers, context):
    if 'Authorization' not in headers:
        return {
            'Authorized': False,
            'ErrorCode': 'NoSuchKey',
            'Status': 401,
        }

    auth = parse_authorization_header(headers.get('Authorization'))
    if not auth:
        return {
            'Authorized': False,
            'ErrorCode': 'NoSuchKey',
            'Status': 401,
        }

    user = User.query.filter(User.username == auth.username).first()
    if not user or not user.password:
        return {
            'Authorized': False,
            'ErrorCode': 'NoSuchKey',
            'Status': 401,
        }

    if not user.is_valid_password(auth.password):
        return {
            'Authorized': False,
            'ErrorCode': 'InvalidSecretKey',
            'Status': 401,
        }

    return _authorize_user(region, service, user.username, action, resource, headers, context)
示例#5
0
 def actual_token(cls) -> str:
     """Gets the **unhashed** token. Use `hash_token` to hash it."""
     x = request.headers.environ['HTTP_AUTHORIZATION']
     header = parse_authorization_header(x)
     if header is None:
         raise StandardError('The Authorization header is not well written: ' + x, 400)
     return header['username']
示例#6
0
    def _get_token_from_headers(self, request: Request) -> Optional[str]:
        """Extract JWT token from HTTP Authorization header

        This will first try to obtain a Bearer token. If none is found but we have a 'Basic' Authorization header,
        and basic auth JWT payload has not been disabled, and the provided username matches the configured JWT token
        username, we will try to use the provided password as if it was a JWT token.
        """
        header = request.headers.get('Authorization')
        if not header:
            return None

        try:
            authz_type, payload = header.split(" ", 1)
        except ValueError:
            return None

        if authz_type.lower() == 'bearer':
            self._log.debug("Found token in Authorization: Bearer header")
            return payload
        elif authz_type.lower() == 'basic' and self.basic_auth_user:
            parsed_header = parse_authorization_header(header)
            if parsed_header and parsed_header.username == self.basic_auth_user:
                self._log.debug("Found token in Authorization: Basic header")
                return parsed_header.password

        return None
示例#7
0
 def actual_token(cls) -> str:
     """Gets the **unhashed** token. Use `hash_token` to hash it."""
     x = request.headers.environ['HTTP_AUTHORIZATION']
     header = parse_authorization_header(x)
     if header is None:
         raise Exception(
             'The Authorization header is not well written: ' + x, 400)
     return header['username']
示例#8
0
文件: core.py 项目: saipavang/httpbin
def digest_auth(qop=None, user='******', passwd='passwd', algorithm='MD5', stale_after='never'):
    """Prompts the user for authorization using HTTP Digest auth"""
    require_cookie_handling = (request.args.get('require-cookie', '').lower() in
                               ('1', 't', 'true'))
    if algorithm not in ('MD5', 'SHA-256', 'SHA-512'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    authorization = request.headers.get('Authorization')
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (not authorization or
            not credentials or
            (require_cookie_handling and 'Cookie' not in request.headers)):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('fake', value='fake_value')
        return response

    if (require_cookie_handling and
            request.cookies.get('fake') != 'fake_value'):
        response = jsonify({'errors': ['missing cookie set on challenge']})
        response.set_cookie('fake', value='fake_value')
        response.status_code = 403
        return response

    current_nonce = credentials.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies:
        stale_after_value = request.cookies.get('stale_after')

    if ('last_nonce' in request.cookies and
            current_nonce == request.cookies.get('last_nonce') or
            stale_after_value == '0'):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce',  value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie('fake', value='fake_value')
    if stale_after_value :
        response.set_cookie('stale_after', value=next_stale_after_value(stale_after_value))

    return response
示例#9
0
文件: core.py 项目: siddthota/httpbin
def digest_auth(qop=None, user='******', passwd='passwd', algorithm='MD5', stale_after='never'):
    """Prompts the user for authorization using HTTP Digest auth"""
    require_cookie_handling = (request.args.get('require-cookie', '').lower() in
                               ('1', 't', 'true'))
    if algorithm not in ('MD5', 'SHA-256', 'SHA-512'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    authorization = request.headers.get('Authorization')
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (not authorization or
            not credentials or
            (require_cookie_handling and 'Cookie' not in request.headers)):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('fake', value='fake_value')
        return response

    if (require_cookie_handling and
            request.cookies.get('fake') != 'fake_value'):
        response = jsonify({'errors': ['missing cookie set on challenge']})
        response.set_cookie('fake', value='fake_value')
        response.status_code = 403
        return response

    current_nonce = credentials.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies:
        stale_after_value = request.cookies.get('stale_after')

    if ('last_nonce' in request.cookies and
            current_nonce == request.cookies.get('last_nonce') or
            stale_after_value == '0'):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce',  value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie('fake', value='fake_value')
    if stale_after_value :
        response.set_cookie('stale_after', value=next_stale_after_value(stale_after_value))

    return response
示例#10
0
    def test_authorization_header(self):
        a = http.parse_authorization_header(
            'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
        assert a.type == 'basic'
        assert a.username == u'Aladdin'
        assert a.password == u'open sesame'

        a = http.parse_authorization_header(
            'Basic 0YDRg9GB0YHQutC40IE60JHRg9C60LLRiw==')
        assert a.type == 'basic'
        assert a.username == u'русскиЁ'
        assert a.password == u'Буквы'

        a = http.parse_authorization_header('Basic 5pmu6YCa6K+dOuS4reaWhw==')
        assert a.type == 'basic'
        assert a.username == u'普通话'
        assert a.password == u'中文'

        a = http.parse_authorization_header('''Digest username="******",
                     realm="*****@*****.**",
                     nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                     uri="/dir/index.html",
                     qop=auth,
                     nc=00000001,
                     cnonce="0a4f113b",
                     response="6629fae49393a05397450978507c4ef1",
                     opaque="5ccc069c403ebaf9f0171e9517f40e41"''')
        assert a.type == 'digest'
        assert a.username == 'Mufasa'
        assert a.realm == '*****@*****.**'
        assert a.nonce == 'dcd98b7102dd2f0e8b11d0f600bfb0c093'
        assert a.uri == '/dir/index.html'
        assert a.qop == 'auth'
        assert a.nc == '00000001'
        assert a.cnonce == '0a4f113b'
        assert a.response == '6629fae49393a05397450978507c4ef1'
        assert a.opaque == '5ccc069c403ebaf9f0171e9517f40e41'

        a = http.parse_authorization_header('''Digest username="******",
                     realm="*****@*****.**",
                     nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                     uri="/dir/index.html",
                     response="e257afa1414a3340d93d30955171dd0e",
                     opaque="5ccc069c403ebaf9f0171e9517f40e41"''')
        assert a.type == 'digest'
        assert a.username == 'Mufasa'
        assert a.realm == '*****@*****.**'
        assert a.nonce == 'dcd98b7102dd2f0e8b11d0f600bfb0c093'
        assert a.uri == '/dir/index.html'
        assert a.response == 'e257afa1414a3340d93d30955171dd0e'
        assert a.opaque == '5ccc069c403ebaf9f0171e9517f40e41'

        assert http.parse_authorization_header('') is None
        assert http.parse_authorization_header(None) is None
        assert http.parse_authorization_header('foo') is None
示例#11
0
def _authorize(request):
    if request.headers.get('Authorization'):
        credentials = parse_authorization_header(
            request.headers.get('Authorization'))
        if not credentials or not \
                (credentials.type == 'basic'
                 and credentials.password == users[credentials.username]):
            abort(403)
        return credentials
    else:
        abort(403)
示例#12
0
文件: helpers.py 项目: 4honor/httpbin
def check_digest_auth(user, passwd):
    """Check user authentication using HTTP Digest auth"""

    if request.headers.get("Authorization"):
        credentails = parse_authorization_header(request.headers.get("Authorization"))
        if not credentails:
            return
        response_hash = response(credentails, passwd, dict(uri=request.path, body=request.data, method=request.method))
        if credentails["response"] == response_hash:
            return True
    return False
示例#13
0
def check_digest_auth(user, passwd):
    """Check user authentication using HTTP Digest auth"""

    if request.headers.get('Authorization'):
        credentails = parse_authorization_header(request.headers.get('Authorization'))
        if not credentails:
            return
        response_hash = response(credentails, passwd, dict(uri=request.path,
                                                           body=request.data,
                                                           method=request.method))
        if credentails['response'] == response_hash:
            return True
    return False
示例#14
0
def digest_auth(qop=None,
                user='******',
                passwd='passwd',
                algorithm='MD5',
                stale_after='never'):
    """Prompts the user for authorization using HTTP Digest auth"""
    if algorithm not in ('MD5', 'SHA-256'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    if 'Authorization' not in request.headers or \
            'Cookie' not in request.headers:
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        return response

    credentails = parse_authorization_header(
        request.headers.get('Authorization'))
    if not credentails:
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        return response

    current_nonce = credentails.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies:
        stale_after_value = request.cookies.get('stale_after')

    if 'last_nonce' in request.cookies and current_nonce == request.cookies.get('last_nonce') or \
            stale_after_value == '0' :
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        return response

    response = jsonify(authenticated=True, user=user)
    if stale_after_value:
        response.set_cookie('stale_after',
                            value=next_stale_after_value(stale_after_value))

    return response
示例#15
0
def check_digest_auth(user, passwd):
    """Check user authentication using HTTP Digest auth"""

    if request.headers.get('Authorization'):
        credentials = parse_authorization_header(request.headers.get('Authorization'))
        if not credentials:
            return
        request_uri = request.script_root + request.path
        if request.query_string:
            request_uri +=  '?' + request.query_string
        response_hash = response(credentials, passwd, dict(uri=request_uri,
                                                           body=request.data,
                                                           method=request.method))
        if credentials.get('response') == response_hash:
            return True
    return False
示例#16
0
def check_digest_auth(user, passwd):
    """Check user authentication using HTTP Digest auth"""

    if request.headers.get('Authorization'):
        credentials = parse_authorization_header(request.headers.get('Authorization'))
        if not credentials:
            return
        request_uri = request.script_root + request.path
        if request.query_string:
            request_uri +=  '?' + request.query_string
        response_hash = response(credentials, passwd, dict(uri=request_uri,
                                                           body=request.data,
                                                           method=request.method))
        if credentials.get('response') == response_hash:
            return True
    return False
示例#17
0
    def check_auth(self, environ, *args, **kwargs):
        LOCKS_AUTH = os.environ.get('LOCKS_AUTH', '')

        if ':' in LOCKS_AUTH:
            allowed = False
            auth = parse_authorization_header(environ.get('HTTP_AUTHORIZATION'))
            username, password = LOCKS_AUTH.split(':', 1)
            if auth and auth.username == username  and auth.password == password:
                allowed = True
        else:
            allowed = True

        if allowed:
            return func(self, environ, *args, **kwargs)
        else:
            raise UpstreamException(401, '', 'not-authorized')
示例#18
0
文件: mock.py 项目: javidgon/endpoint
 def basic_auth_mock(self, request, **values):
     example = {
                "name": "Wow! You got in a restricted area with security level 1 (Basic auth)", 
                "status": 200,
                "requested_at": str(datetime.datetime.now()),
                "body": json.dumps(request.form)
                }
     
     if 'Authorization' in request.headers:
         auth = parse_authorization_header(request.headers['Authorization'])
         try:
             if auth['username'] == 'dev' and auth['password'] == 'example':
                 return Response(json.dumps(example))
         except KeyError:
             pass
    
     raise Unauthorized
示例#19
0
def digest_auth(qop=None, user='******', passwd='passwd', algorithm='MD5', stale_after='never'):
    """Prompts the user for authorization using HTTP Digest auth"""
    if algorithm not in ('MD5', 'SHA-256'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    if 'Authorization' not in request.headers or \
            'Cookie' not in request.headers:
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        return response

    credentails = parse_authorization_header(request.headers.get('Authorization'))
    if not credentails :
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        return response

    current_nonce = credentails.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies :
        stale_after_value = request.cookies.get('stale_after')

    if 'last_nonce' in request.cookies and current_nonce == request.cookies.get('last_nonce') or \
            stale_after_value == '0' :
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce',  value=current_nonce)
        return response

    if not check_digest_auth(user, passwd) :
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        return response

    response = jsonify(authenticated=True, user=user)
    if stale_after_value :
        response.set_cookie('stale_after', value=next_stale_after_value(stale_after_value))

    return response
示例#20
0
    def test_authorization_header(self):
        a = http.parse_authorization_header('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
        assert a.type == 'basic'
        assert a.username == 'Aladdin'
        assert a.password == 'open sesame'

        a = http.parse_authorization_header('''Digest username="******",
                     realm="*****@*****.**",
                     nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                     uri="/dir/index.html",
                     qop=auth,
                     nc=00000001,
                     cnonce="0a4f113b",
                     response="6629fae49393a05397450978507c4ef1",
                     opaque="5ccc069c403ebaf9f0171e9517f40e41"''')
        assert a.type == 'digest'
        assert a.username == 'Mufasa'
        assert a.realm == '*****@*****.**'
        assert a.nonce == 'dcd98b7102dd2f0e8b11d0f600bfb0c093'
        assert a.uri == '/dir/index.html'
        assert 'auth' in a.qop
        assert a.nc == '00000001'
        assert a.cnonce == '0a4f113b'
        assert a.response == '6629fae49393a05397450978507c4ef1'
        assert a.opaque == '5ccc069c403ebaf9f0171e9517f40e41'

        a = http.parse_authorization_header('''Digest username="******",
                     realm="*****@*****.**",
                     nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                     uri="/dir/index.html",
                     response="e257afa1414a3340d93d30955171dd0e",
                     opaque="5ccc069c403ebaf9f0171e9517f40e41"''')
        assert a.type == 'digest'
        assert a.username == 'Mufasa'
        assert a.realm == '*****@*****.**'
        assert a.nonce == 'dcd98b7102dd2f0e8b11d0f600bfb0c093'
        assert a.uri == '/dir/index.html'
        assert a.response == 'e257afa1414a3340d93d30955171dd0e'
        assert a.opaque == '5ccc069c403ebaf9f0171e9517f40e41'

        assert http.parse_authorization_header('') is None
        assert http.parse_authorization_header(None) is None
        assert http.parse_authorization_header('foo') is None
示例#21
0
def test_authorization_to_header(value: str) -> None:
    assert http.parse_authorization_header(value).to_header() == value
示例#22
0
文件: core.py 项目: xueshi36/httpbin
def digest_auth(qop=None,
                user='******',
                passwd='passwd',
                algorithm='MD5',
                stale_after='never'):
    """"Prompts the user for authorization using Digest Auth + Algorithm.
    allow settings the stale_after argument.
    ---
    tags:
      - Auth
    parameters:
      - in: path
        name: qop
        type: string
        description: auth or auth-int
      - in: path
        name: user
        type: string
      - in: path
        name: passwd
        type: string
      - in: path
        name: algorithm
        type: string
        description: MD5, SHA-256, SHA-512
        default: MD5
      - in: path
        name: stale_after
        type: string
        default: never
    produces:
      - application/json
    responses:
      200:
        description: Sucessful authentication.
      401:
        description: Unsuccessful authentication.
    """
    require_cookie_handling = (request.args.get('require-cookie', '').lower()
                               in ('1', 't', 'true'))
    if algorithm not in ('MD5', 'SHA-256', 'SHA-512'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    authorization = request.headers.get('Authorization')
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (not authorization or not credentials
            or credentials.type.lower() != 'digest'
            or (require_cookie_handling and 'Cookie' not in request.headers)):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('fake', value='fake_value')
        return response

    if (require_cookie_handling
            and request.cookies.get('fake') != 'fake_value'):
        response = jsonify({'errors': ['missing cookie set on challenge']})
        response.set_cookie('fake', value='fake_value')
        response.status_code = 403
        return response

    current_nonce = credentials.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies:
        stale_after_value = request.cookies.get('stale_after')

    if ('last_nonce' in request.cookies
            and current_nonce == request.cookies.get('last_nonce')
            or stale_after_value == '0'):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie('fake', value='fake_value')
    if stale_after_value:
        response.set_cookie('stale_after',
                            value=next_stale_after_value(stale_after_value))

    return response
示例#23
0
def test_register_report(client, github_auth_header):
    responses.add(responses.GET,
                  'https://api.github.com/user',
                  status=200,
                  json={'login': '******'})
    responses.add(responses.GET,
                  'https://api.github.com/user/orgs',
                  status=200,
                  json=[{
                      'login': '******'
                  }])
    responses.add(responses.GET,
                  'https://keeper.lsst.codes/token',
                  status=200,
                  json={'token': 'ltdtoken'})
    # Initial product registration
    responses.add(
        responses.POST,
        'https://keeper.lsst.codes/products/',
        status=201,
        json={},
        headers={'Location': 'https://keeper.lsst.codes/products/testr-000'})
    # Getting info about the product resource
    responses.add(responses.GET,
                  'https://keeper.lsst.codes/products/testr-000',
                  status=200,
                  json={
                      'slug': 'testr-000',
                      'published_url': 'https://testr-000.lsst.io',
                      'self_url':
                      'https://keeper.lsst.codes/products/testr-000'
                  })

    with client:
        headers = dict(github_auth_header)
        headers['Content-Type'] = 'application/json'
        response = client.post('/nbreport/reports/',
                               headers=headers,
                               data=json.dumps({
                                   'handle':
                                   'TESTR-000',
                                   'title':
                                   'Demo report',
                                   'git_repo':
                                   'https://github.com/lsst-sqre/nbreport'
                               }))
        assert response.status_code == 201
        response_data = json.loads(response.data.decode('utf-8'))

        assert g.ltd_user == current_app.config['KEEPER_USERNAME']
        assert g.ltd_token == 'ltdtoken'

        assert response_data['product'] == 'testr-000'

        # Test the call to POST keeper.lsst.codes/products/
        post_products_request_data = json.loads(
            responses.calls[3].request.body.decode('utf-8'))
        assert post_products_request_data['slug'] == 'testr-000'
        assert post_products_request_data['title'] == 'Demo report'
        assert post_products_request_data['main_mode'] == 'manual'
        # Test authorization header
        auth = parse_authorization_header(
            responses.calls[3].request.headers['Authorization'])
        assert auth is not None
        assert auth.username == 'ltdtoken'
        assert auth.password == ''

        # Test the call to GET /products/testr-000
        assert responses.calls[4].request.url \
            == 'https://keeper.lsst.codes/products/testr-000'
示例#24
0
文件: base.py 项目: ccns1/ccns11
 def authorization(self) -> Optional[Authorization]:
     return parse_authorization_header(self.headers.get("Authorization"))
示例#25
0
def test_basic_auth():
    builder = EnvironBuilder(auth=("username", "password"))
    request = builder.get_request()
    auth = parse_authorization_header(request.headers["Authorization"])
    assert auth.username == "username"
    assert auth.password == "password"
示例#26
0
 def test_bad_authorization_header_encoding(self):
     """If the base64 encoded bytes can't be decoded as UTF-8"""
     content = base64.b64encode(b"\xffser:pass").decode()
     assert http.parse_authorization_header(f"Basic {content}") is None
示例#27
0
def digest_auth(
    qop=None, user="******", passwd="passwd", algorithm="MD5", stale_after="never"
):
    """Prompts the user for authorization using Digest Auth + Algorithm.
    allow settings the stale_after argument.
    ---
    tags:
      - Auth
    parameters:
      - in: path
        name: qop
        type: string
        description: auth or auth-int
      - in: path
        name: user
        type: string
      - in: path
        name: passwd
        type: string
      - in: path
        name: algorithm
        type: string
        description: MD5, SHA-256, SHA-512
        default: MD5
      - in: path
        name: stale_after
        type: string
        default: never
    produces:
      - application/json
    responses:
      200:
        description: Sucessful authentication.
      401:
        description: Unsuccessful authentication.
    """
    require_cookie_handling = request.args.get("require-cookie", "").lower() in (
        "1",
        "t",
        "true",
    )
    if algorithm not in ("MD5", "SHA-256", "SHA-512"):
        algorithm = "MD5"

    if qop not in ("auth", "auth-int"):
        qop = None

    authorization = request.headers.get("Authorization")
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (
        not authorization
        or not credentials
        or credentials.type.lower() != "digest"
        or (require_cookie_handling and "Cookie" not in request.headers)
    ):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("fake", value="fake_value")
        return response

    if require_cookie_handling and request.cookies.get("fake") != "fake_value":
        response = jsonify({"errors": ["missing cookie set on challenge"]})
        response.set_cookie("fake", value="fake_value")
        response.status_code = 403
        return response

    current_nonce = credentials.get("nonce")

    stale_after_value = None
    if "stale_after" in request.cookies:
        stale_after_value = request.cookies.get("stale_after")

    if (
        "last_nonce" in request.cookies
        and current_nonce == request.cookies.get("last_nonce")
        or stale_after_value == "0"
    ):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("last_nonce", value=current_nonce)
        response.set_cookie("fake", value="fake_value")
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("last_nonce", value=current_nonce)
        response.set_cookie("fake", value="fake_value")
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie("fake", value="fake_value")
    if stale_after_value:
        response.set_cookie(
            "stale_after", value=next_stale_after_value(stale_after_value)
        )

    return response
示例#28
0
def basicAuthSession(request):
    result = parse_authorization_header(request.headers.get('authorization'))
    return result.password
示例#29
0
文件: request.py 项目: guyskk/weirb
 def authorization(self):
     """The `Authorization` object in parsed form."""
     header = self.headers.get('Authorization', '')
     return parse_authorization_header(header)
示例#30
0
文件: core.py 项目: Lucretiel/httpbin
def digest_auth(qop=None, user='******', passwd='passwd', algorithm='MD5', stale_after='never'):
    """"Prompts the user for authorization using Digest Auth + Algorithm.
    allow settings the stale_after argument.
    ---
    tags:
      - Auth
    parameters:
      - in: path
        name: qop
        type: string
        description: auth or auth-int
      - in: path
        name: user
        type: string
      - in: path
        name: passwd
        type: string
      - in: path
        name: algorithm
        type: string
        description: MD5, SHA-256, SHA-512
        default: MD5
      - in: path
        name: stale_after
        type: string
        default: never
    produces:
      - application/json
    responses:
      200:
        description: Sucessful authentication.
      401:
        description: Unsuccessful authentication.
    """
    require_cookie_handling = (request.args.get('require-cookie', '').lower() in
                               ('1', 't', 'true'))
    if algorithm not in ('MD5', 'SHA-256', 'SHA-512'):
        algorithm = 'MD5'

    if qop not in ('auth', 'auth-int'):
        qop = None

    authorization = request.headers.get('Authorization')
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (not authorization or
            not credentials or credentials.type.lower() != 'digest' or
            (require_cookie_handling and 'Cookie' not in request.headers)):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('fake', value='fake_value')
        return response

    if (require_cookie_handling and
            request.cookies.get('fake') != 'fake_value'):
        response = jsonify({'errors': ['missing cookie set on challenge']})
        response.set_cookie('fake', value='fake_value')
        response.status_code = 403
        return response

    current_nonce = credentials.get('nonce')

    stale_after_value = None
    if 'stale_after' in request.cookies:
        stale_after_value = request.cookies.get('stale_after')

    if ('last_nonce' in request.cookies and
            current_nonce == request.cookies.get('last_nonce') or
            stale_after_value == '0'):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce',  value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie('stale_after', value=stale_after)
        response.set_cookie('last_nonce', value=current_nonce)
        response.set_cookie('fake', value='fake_value')
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie('fake', value='fake_value')
    if stale_after_value :
        response.set_cookie('stale_after', value=next_stale_after_value(stale_after_value))

    return response
 def authorization(self):
     """The `Authorization` object in parsed form."""
     header = self.environ.get('HTTP_AUTHORIZATION')
     return parse_authorization_header(header)
示例#32
0
 def authorization_header_value_matcher(actual: Optional[str],
                                        expected: str) -> bool:
     return parse_authorization_header(
         actual) == parse_authorization_header(expected)
def test_reserve_instance(client, github_auth_header):
    responses.add(
        responses.GET,
        'https://api.github.com/user',
        status=200,
        json={
            'login': '******'
        }
    )
    responses.add(
        responses.GET,
        'https://api.github.com/user/orgs',
        status=200,
        json=[
            {
                'login': '******'
            }
        ]
    )
    responses.add(
        responses.GET,
        'https://keeper.lsst.codes/token',
        status=200,
        json={'token': 'ltdtoken'}
    )
    # Initial reservation of the edition with LTD Keeper
    responses.add(
        responses.POST,
        'https://keeper.lsst.codes/products/testr-000/editions/',
        status=201,
        json={},
        headers={'Location': 'https://keeper.lsst.codes/editions/1'}
    )
    # Request to obtain the full edition resource
    responses.add(
        responses.GET,
        'https://keeper.lsst.codes/editions/1',
        status=200,
        json={
            'slug': '1',
            'published_url': 'https://testr-000.lsst.io/v/1',
            'self_url': 'https://keeper.lsst.codes/editions/1'},
        headers={'Location': 'https://keeper.lsst.codes/editions/1'}
    )

    with client:
        headers = dict(github_auth_header)
        headers['Content-Type'] = 'application/json'
        response = client.post(
            '/nbreport/reports/testr-000/instances/',
            headers=headers,
        )
        assert response.status_code == 201

        response_data = json.loads(response.data.decode('utf-8'))
        assert response_data['instance_id'] == '1'

        # Test the POST /products/<slug>/editions/ request
        post_editions_request_data = json.loads(
            responses.calls[3].request.body.decode('utf-8'))
        assert post_editions_request_data['autoincrement'] is True
        assert post_editions_request_data['mode'] == 'manual'
        # Test authorization header
        auth = parse_authorization_header(
            responses.calls[3].request.headers['Authorization'])
        assert auth is not None
        assert auth.username == 'ltdtoken'
        assert auth.password == ''
示例#34
0
def test_authorization_to_header(value: str) -> None:
    parsed = http.parse_authorization_header(value)
    assert parsed is not None
    assert parsed.to_header() == value
示例#35
0
 def authorization(self):
     header = self.environ.get('HTTP_AUTHORIZATION')
     return parse_authorization_header(header)
示例#36
0
def basicAuthSession(request):
    result = parse_authorization_header(request.headers.get('authorization'))
    return result.password
示例#37
0
文件: core.py 项目: Runscope/httpbin
def digest_auth(
    qop=None, user="******", passwd="passwd", algorithm="MD5", stale_after="never"
):
    """Prompts the user for authorization using Digest Auth + Algorithm.
    allow settings the stale_after argument.
    ---
    tags:
      - Auth
    parameters:
      - in: path
        name: qop
        type: string
        description: auth or auth-int
      - in: path
        name: user
        type: string
      - in: path
        name: passwd
        type: string
      - in: path
        name: algorithm
        type: string
        description: MD5, SHA-256, SHA-512
        default: MD5
      - in: path
        name: stale_after
        type: string
        default: never
    produces:
      - application/json
    responses:
      200:
        description: Sucessful authentication.
      401:
        description: Unsuccessful authentication.
    """
    require_cookie_handling = request.args.get("require-cookie", "").lower() in (
        "1",
        "t",
        "true",
    )
    if algorithm not in ("MD5", "SHA-256", "SHA-512"):
        algorithm = "MD5"

    if qop not in ("auth", "auth-int"):
        qop = None

    authorization = request.headers.get("Authorization")
    credentials = None
    if authorization:
        credentials = parse_authorization_header(authorization)

    if (
        not authorization
        or not credentials
        or credentials.type.lower() != "digest"
        or (require_cookie_handling and "Cookie" not in request.headers)
    ):
        response = digest_challenge_response(app, qop, algorithm)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("fake", value="fake_value")
        return response

    if require_cookie_handling and request.cookies.get("fake") != "fake_value":
        response = jsonify({"errors": ["missing cookie set on challenge"]})
        response.set_cookie("fake", value="fake_value")
        response.status_code = 403
        return response

    current_nonce = credentials.get("nonce")

    stale_after_value = None
    if "stale_after" in request.cookies:
        stale_after_value = request.cookies.get("stale_after")

    if (
        "last_nonce" in request.cookies
        and current_nonce == request.cookies.get("last_nonce")
        or stale_after_value == "0"
    ):
        response = digest_challenge_response(app, qop, algorithm, True)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("last_nonce", value=current_nonce)
        response.set_cookie("fake", value="fake_value")
        return response

    if not check_digest_auth(user, passwd):
        response = digest_challenge_response(app, qop, algorithm, False)
        response.set_cookie("stale_after", value=stale_after)
        response.set_cookie("last_nonce", value=current_nonce)
        response.set_cookie("fake", value="fake_value")
        return response

    response = jsonify(authenticated=True, user=user)
    response.set_cookie("fake", value="fake_value")
    if stale_after_value:
        response.set_cookie(
            "stale_after", value=next_stale_after_value(stale_after_value)
        )

    return response
示例#38
0
 def authorization(self):
     header = self.environ.get('HTTP_AUTHORIZATION')
     return parse_authorization_header(header)