当前位置: 首页>>代码示例>>Python>>正文


Python Server.parse_authorization_request方法代码示例

本文整理汇总了Python中oic.oauth2.Server.parse_authorization_request方法的典型用法代码示例。如果您正苦于以下问题:Python Server.parse_authorization_request方法的具体用法?Python Server.parse_authorization_request怎么用?Python Server.parse_authorization_request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在oic.oauth2.Server的用法示例。


在下文中一共展示了Server.parse_authorization_request方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_server_parse_parse_authorization_request

# 需要导入模块: from oic.oauth2 import Server [as 别名]
# 或者: from oic.oauth2.Server import parse_authorization_request [as 别名]
def test_server_parse_parse_authorization_request():
    srv = Server()
    ar = AuthorizationRequest(response_type=["code"],
                              client_id="foobar",
                              redirect_uri="http://foobar.example.com/oaclient",
                              state="cold")

    uencq = ar.to_urlencoded()

    areq = srv.parse_authorization_request(query=uencq)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"

    urluenc = "%s?%s" % ("https://example.com/authz", uencq)

    areq = srv.parse_authorization_request(url=urluenc)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"
开发者ID:dajiaji,项目名称:pyoidc,代码行数:28,代码来源:test_oauth2.py

示例2: TestServer

# 需要导入模块: from oic.oauth2 import Server [as 别名]
# 或者: from oic.oauth2.Server import parse_authorization_request [as 别名]
class TestServer(object):
    @pytest.fixture(autouse=True)
    def create_server(self):
        self.srv = Server()  # pylint: disable=attribute-defined-outside-init

    def test_parse_authz_req(self):
        ar = AuthorizationRequest(
            response_type=["code"], client_id="foobar", redirect_uri="http://foobar.example.com/oaclient", state="cold"
        )

        uencq = ar.to_urlencoded()

        areq = self.srv.parse_authorization_request(query=uencq)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

        urluenc = "%s?%s" % ("https://example.com/authz", uencq)
        areq = self.srv.parse_authorization_request(url=urluenc)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

    def test_parse_jwt_request(self):
        ar = AuthorizationRequest(
            response_type=["code"], client_id="foobar", redirect_uri="http://foobar.example.com/oaclient", state="cold"
        )

        self.srv.keyjar["foobar"] = KeyBundle(
            [
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "ver"},
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "sig"},
            ]
        )
        self.srv.keyjar[""] = KeyBundle(
            [
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "ver"},
                {"kty": "oct", "key": "A1B2C3D4".encode("utf-8"), "use": "sig"},
            ]
        )

        keys = self.srv.keyjar.get_signing_key(owner="foobar")
        _jwt = ar.to_jwt(key=keys, algorithm="HS256")

        req = self.srv.parse_jwt_request(txt=_jwt)

        assert isinstance(req, AuthorizationRequest)
        assert req["response_type"] == ["code"]
        assert req["client_id"] == "foobar"
        assert req["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert req["state"] == "cold"

    def test_server_parse_token_request(self):
        atr = AccessTokenRequest(
            grant_type="authorization_code",
            code="SplxlOBeZQQYbYS6WxSbIA",
            redirect_uri="https://client.example.com/cb",
            extra="foo",
        )
        uenc = atr.to_urlencoded()

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ["code", "redirect_uri", "grant_type", "extra"])

        assert tr["grant_type"] == "authorization_code"
        assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ["code", "grant_type", "redirect_uri", "extra"])

        assert tr["extra"] == "foo"

    def test_server_parse_refresh_token_request(self):
        ratr = RefreshAccessTokenRequest(refresh_token="ababababab", client_id="Client_id")
        uenc = ratr.to_urlencoded()

        tr = self.srv.parse_refresh_token_request(body=uenc)

        assert isinstance(tr, RefreshAccessTokenRequest)
        assert tr["refresh_token"] == "ababababab"
        assert tr["client_id"] == "Client_id"
开发者ID:joostd,项目名称:pyoidc,代码行数:93,代码来源:test_oauth2.py

示例3: Provider

# 需要导入模块: from oic.oauth2 import Server [as 别名]
# 或者: from oic.oauth2.Server import parse_authorization_request [as 别名]

#.........这里部分代码省略.........
                else:
                    try:
                        assert _secret == self.cdb[_id]["client_secret"]
                    except AssertionError:
                        logger.debug("Incorrect secret")
                        raise FailedAuthentication("Incorrect secret")
            else:
                try:
                    assert authn[:6].lower() == "bearer"
                    logger.debug("Bearer auth")
                    _token = authn[7:]
                except AssertionError:
                    raise FailedAuthentication("AuthZ type I don't know")

                try:
                    _id = self.cdb[_token]
                except KeyError:
                    logger.debug("Unknown access token")
                    raise FailedAuthentication("Unknown access token")
        else:
            try:
                _id = req["client_id"]
                if _id not in self.cdb:
                    logger.debug("Unknown client_id")
                    raise FailedAuthentication("Unknown client_id")
            except KeyError:
                raise FailedAuthentication("Missing client_id")

        return _id

    def authn_reply(self, areq, aresp, bsid, **kwargs):

        if "redirect_uri" in areq:
            # TODO verify that the uri is reasonable
            redirect_uri = areq["redirect_uri"]
        else:
            redirect_uri = self.urlmap[areq["client_id"]]

        location = location_url(areq["response_type"], redirect_uri,
                                aresp.to_urlencoded())

        LOG_DEBUG("Redirected to: '%s' (%s)" % (location, type(location)))

        # set cookie containing session ID

        cookie = make_cookie(self.cookie_name, bsid, self.seed)

        return Redirect(str(location), headers=[cookie])

    def authn_response(self, areq, **kwargs):
        """

        :param areq: Authorization request
        :param kwargs: Extra keyword arguments
        :return:
        """
        scode = kwargs["code"]
        areq["response_type"].sort()
        _rtype = " ".join(areq["response_type"])
        return self.response_type_map[_rtype](areq=areq, scode=scode,
                                              sdb=self.sdb)

    def input(self, query="", post=None):
        # Support GET and POST
        if query:
            return query
        elif post:
            return post
        else:
            raise MissingParameter("No input")

    def authorization_endpoint(self, request="", **kwargs):
        """ The AuthorizationRequest endpoint

        :param query: The query part of the request URL
        """
        _sdb = self.sdb

        LOG_DEBUG("- authorization -")
        LOG_DEBUG("Query: '%s'" % request)

        try:
            kaka = kwargs["cookie"]
        except KeyError:
            kaka = None
        identity = self.authn.authenticated_as(kaka)
        if identity is None:  # No!
            return self.authn(query=request)
        else:
            # I get back a dictionary
            user = identity["uid"]

        LOG_DEBUG("- authenticated -")

        try:
            areq = self.srvmethod.parse_authorization_request(query=request)
        except MissingRequiredAttribute, err:
            return BadRequest("%s" % err)
        except Exception, err:
            return BadRequest("%s" % err)
开发者ID:biancini,项目名称:pyoidc,代码行数:104,代码来源:provider.py

示例4: Provider

# 需要导入模块: from oic.oauth2 import Server [as 别名]
# 或者: from oic.oauth2.Server import parse_authorization_request [as 别名]

#.........这里部分代码省略.........
                        # Return the best guess by pick.
                        return res[0]
            else:  # same as any
                try:
                    acrs = areq["claims"]["id_token"]["acr"]["values"]
                except KeyError:
                    return self.authn_broker[0]
                else:
                    for acr in acrs:
                        res = self.authn_broker.pick(acr, comparision_type)
                        logger.debug("Picked AuthN broker for ACR %s: %s" % (
                            str(acr), str(res)))
                        if res:
                            # Return the best guess by pick.
                            return res[0]

        except KeyError as exc:
            logger.debug(
                "An error occured while picking the authN broker: %s" % str(
                    exc))

        # return the best I have
        return None, None

    def auth_init(self, request, request_class=AuthorizationRequest):
        """

        :param request: The AuthorizationRequest
        :return:
        """
        logger.debug("Request: '%s'" % request)
        # Same serialization used for GET and POST
        try:
            areq = self.server.parse_authorization_request(
                request=request_class, query=request)
        except (MissingRequiredValue, MissingRequiredAttribute) as err:
            logger.debug("%s" % err)
            areq = request_class().deserialize(request, "urlencoded")
            try:
                redirect_uri = self.get_redirect_uri(areq)
            except (RedirectURIError, ParameterError) as err:
                return self._error("invalid_request", "%s" % err)
            try:
                _rtype = areq["response_type"]
            except:
                _rtype = ["code"]
            return self._redirect_authz_error("invalid_request", redirect_uri,
                                              "%s" % err, areq["state"],
                                              _rtype)
        except KeyError:
            areq = request_class().deserialize(request, "urlencoded")
            # verify the redirect_uri
            try:
                self.get_redirect_uri(areq)
            except (RedirectURIError, ParameterError) as err:
                return self._error("invalid_request", "%s" % err)
        except Exception as err:
            message = traceback.format_exception(*sys.exc_info())
            logger.error(message)
            logger.debug("Bad request: %s (%s)" % (err, err.__class__.__name__))
            return BadRequest("%s" % err)

        if not areq:
            logger.debug("No AuthzRequest")
            return self._error("invalid_request", "Can not parse AuthzRequest")
开发者ID:danielquinn,项目名称:pyoidc,代码行数:69,代码来源:provider.py

示例5: Provider

# 需要导入模块: from oic.oauth2 import Server [as 别名]
# 或者: from oic.oauth2.Server import parse_authorization_request [as 别名]

#.........这里部分代码省略.........
                logger.info("Registered redirect_uris: %s" % _cinfo)
                raise RedirectURIError(
                    "Faulty redirect_uri: %s" % areq["redirect_uri"])

    def get_redirect_uri(self, areq):
        """ verify that the redirect URI is reasonable

        :param areq: The Authorization request
        :return: Tuple of (redirect_uri, Response instance)
            Response instance is not None of matching redirect_uri failed
        """
        if 'redirect_uri' in areq:
            self._verify_redirect_uri(areq)
            uri = areq["redirect_uri"]
        else:
            raise ParameterError(
                "Missing redirect_uri and more than one or none registered")

        return uri

    def pick_auth(self, areq, comparision_type=""):
        """

        :param areq: AuthorizationRequest instance
        :param comparision_type: How to pick the authentication method
        :return: An authentication method and its authn class ref
        """
        if comparision_type == "any":
            return self.authn_broker[0]

        try:
            if len(self.authn_broker) == 1:
                return self.authn_broker[0]
            elif "acr_values" in areq:
                if not comparision_type:
                    comparision_type = "exact"

                if not isinstance(areq["acr_values"], list):
                    areq["acr_values"] = [areq["acr_values"]]

                for acr in areq["acr_values"]:
                    res = self.authn_broker.pick(acr, comparision_type)
                    logger.debug("Picked AuthN broker for ACR %s: %s" % (
                        str(acr), str(res)))
                    if res:
                        #Return the best guess by pick.
                        return res[0]
            else:  # same as any
                try:
                    acrs = areq["claims"]["id_token"]["acr"]["values"]
                except KeyError:
                    return self.authn_broker[0]
                else:
                    for acr in acrs:
                        res = self.authn_broker.pick(acr, comparision_type)
                        logger.debug("Picked AuthN broker for ACR %s: %s" % (
                            str(acr), str(res)))
                        if res:
                            #Return the best guess by pick.
                            return res[0]

        except KeyError as exc:
            logger.debug(
                "An error occured while picking the authN broker: %s" % str(
                    exc))

        # return the best I have
        return None, None

    def auth_init(self, request):
        """

        :param request: The AuthorizationRequest
        :return:
        """
        logger.debug("Request: '%s'" % request)
        # Same serialization used for GET and POST
        try:
            areq = self.server.parse_authorization_request(query=request)
        except (MissingRequiredValue, MissingRequiredAttribute) as err:
            logger.debug("%s" % err)
            areq = AuthorizationRequest().deserialize(request, "urlencoded")
            try:
                redirect_uri = self.get_redirect_uri(areq)
            except (RedirectURIError, ParameterError), err:
                return self._error("invalid_request", "%s" % err)
            try:
                _rtype = areq["response_type"]
            except:
                _rtype = ["code"]
            return self._redirect_authz_error("invalid_request", redirect_uri,
                                              "%s" % err, areq["state"],
                                              _rtype)
        except KeyError:
            areq = AuthorizationRequest().deserialize(request, "urlencoded")
            # verify the redirect_uri
            try:
                self.get_redirect_uri(areq)
            except (RedirectURIError, ParameterError), err:
                return self._error("invalid_request", "%s" % err)
开发者ID:dallerbarn,项目名称:pyoidc,代码行数:104,代码来源:provider.py


注:本文中的oic.oauth2.Server.parse_authorization_request方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。