コード例 #1
0
    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client_1")

        _sdb = self.server.sdb
        sid = _sdb.token.key(user="******", areq=authreq)
        access_grant = _sdb.token(sid=sid)
        ae = AuthnEvent("user")
        _sdb[sid] = {
            "authn_event": ae,
            "oauth_state": "authz",
            "authzreq": "",
            "client_id": "client_1",
            "code": access_grant,
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz"
        }
        _sdb.do_sub(sid)

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client_1", client_secret="secret", )

        print areq.to_dict()
        txt = areq.to_urlencoded()

        resp = self.server.token_endpoint(request=txt, remote_user="******",
                                          request_method="POST")
        print resp
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        print atr.keys()
        assert _eq(atr.keys(), ['error'])
コード例 #2
0
ファイル: provider.py プロジェクト: imsoftware/pyoidc
    def token_endpoint(self, environ, start_response, **kwargs):
        """
        This is where clients come to get their access tokens
        """

        _log_info = logger.info
        _log_debug = logger.debug
        _sdb = self.sdb

        _log_debug("- token -")

        try:
            body = kwargs["query"]
        except KeyError:
            body = get_post(environ)

        if self.test_mode:
            _log_info("token_request: %s" % body)

        areq = AccessTokenRequest().deserialize(body, "urlencoded")

        if not self.verify_client(environ, areq):
            _log_info("could not verify client")
            err = TokenErrorResponse(error="unathorized_client")
            resp = Unauthorized(err.to_json(), content="application/json")
            return resp(environ, start_response)

        _log_debug("AccessTokenRequest: %s" % areq)

        assert areq["grant_type"] == "authorization_code"

        _access_code = areq["code"]
        # assert that the code is valid
        if self.sdb.is_revoked(_access_code):
            return self._error(environ, start_response,
                               error="access_denied", descr="Token is revoked")

        _info = _sdb[_access_code]

        # If redirect_uri was in the initial authorization request
        # verify that the one given here is the correct one.
        if "redirect_uri" in _info:
            assert areq["redirect_uri"] == _info["redirect_uri"]

        _log_debug("All checks OK")

        try:
            _tinfo = _sdb.update_to_token(_access_code)
        except Exception,err:
            _log_info("Error: %s" % err)
            # Should revoke the token issued to this access code
            _sdb.revoke_all_tokens(_access_code)
            return self._error(environ, start_response,
                               error="access_denied", descr= "%s" % err)
コード例 #3
0
def token_error(exception):

    error_response = TokenErrorResponse(error=exception.oauth_error,
                                        error_description=str(exception))

    response = make_response((jsonify(error_response.to_dict()), 400))

    if isinstance(exception, InvalidClientAuthentication):
        response.status = '401'
        response.headers['WWW-Authenticate'] = 'basic'

    return response
コード例 #4
0
ファイル: test_oic_provider.py プロジェクト: atidev/pyoidc
    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client_1")

        _sdb = self.provider.sdb
        sid = _sdb.token.key(user="******", areq=authreq)
        access_grant = _sdb.token(sid=sid)
        ae = AuthnEvent("user", "salt")
        _sdb[sid] = {
            "authn_event": ae,
            "oauth_state": "authz",
            "authzreq": "",
            "client_id": "client_1",
            "code": access_grant,
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz"
        }
        _sdb.do_sub(sid, "client_salt")

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client_1",
                                  client_secret="secret", )

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt, remote_user="******",
                                            request_method="POST")
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "unauthorized_client"
コード例 #5
0
    def test_token_endpoint_auth(self):
        state, location = self.cons.begin("openid",
                                          "code",
                                          path="http://localhost:8087")

        resp = self.provider.authorization_endpoint(
            request=urlparse(location).query)

        aresp = self.cons.parse_response(AuthorizationResponse,
                                         resp.message,
                                         sformat="urlencoded")

        # Construct Access token request
        areq = self.cons.construct_AccessTokenRequest(
            redirect_uri="http://example.com/authz",
            client_id="client_1",
            client_secret='abcdefghijklmnop',
            state=state)

        txt = areq.to_urlencoded()
        self.cons.client_secret = 'drickyoughurt'

        csb = ClientSecretBasic(self.cons)
        http_args = csb.construct(areq)

        resp = self.provider.token_endpoint(
            request=txt,
            remote_user="******",
            request_method="POST",
            authn=http_args['headers']['Authorization'])

        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["token_type"] == 'Bearer'
コード例 #6
0
    def test_token_endpoint_malformed(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id=CLIENT_ID,
                                       response_type="code",
                                       scope=["openid"])

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        ae = AuthnEvent("user", "salt")
        _sdb[sid] = {
            "oauth_state": "authz",
            "authn_event": ae,
            "authzreq": authreq.to_json(),
            "client_id": CLIENT_ID,
            "code": access_grant,
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz",
        }
        _sdb.do_sub(sid, "client_salt")

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant[0:len(access_grant) - 1],
                                  client_id=CLIENT_ID,
                                  redirect_uri="http://example.com/authz",
                                  client_secret=CLIENT_SECRET,
                                  grant_type='authorization_code')

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr['error'] == "invalid_request"
コード例 #7
0
    def token_endpoint(self, data):
        if "grant_type=refresh_token" in data:
            req = self.parse_refresh_token_request(body=data)
            _info = self.sdb.refresh_token(req["refresh_token"])
        elif "grant_type=authorization_code":
            req = self.parse_token_request(body=data)
            _info = self.sdb.upgrade_to_token(req["code"])
        else:
            response = TokenErrorResponse(error="unsupported_grant_type")
            return response, ""

        resp = AccessTokenResponse(**by_schema(AccessTokenResponse, **_info))
        response = Response()
        response.headers = {"content-type": "application/json"}
        response.text = resp.to_json()

        return response
コード例 #8
0
ファイル: fakeoicsrv.py プロジェクト: joostd/pyoidc
    def token_endpoint(self, data):
        if "grant_type=refresh_token" in data:
            req = self.parse_refresh_token_request(body=data)
            _info = self.sdb.refresh_token(req["refresh_token"])
        elif "grant_type=authorization_code":
            req = self.parse_token_request(body=data)
            _info = self.sdb.upgrade_to_token(req["code"])
        else:
            response = TokenErrorResponse(error="unsupported_grant_type")
            return response, ""

        resp = AccessTokenResponse(**by_schema(AccessTokenResponse, **_info))
        response = Response()
        response.headers = {"content-type": "application/json"}
        response.text = resp.to_json()

        return response
コード例 #9
0
ファイル: oidc_provider.py プロジェクト: SUNET/se-leg-op
def token_endpoint():
    try:
        token_response = current_app.provider.handle_token_request(flask.request.get_data().decode('utf-8'),
                                                                   flask.request.headers, extra_userinfo)
        return jsonify(token_response.to_dict())
    except InvalidClientAuthentication as e:
        current_app.logger.debug('invalid client authentication at token endpoint', exc_info=True)
        error_resp = TokenErrorResponse(error='invalid_client', error_description=str(e))
        response = make_response(error_resp.to_json(), 401)
        response.headers['Content-Type'] = 'application/json'
        response.headers['WWW-Authenticate'] = 'Basic'
        return response
    except OAuthError as e:
        current_app.logger.debug('invalid request: %s', str(e), exc_info=True)
        error_resp = TokenErrorResponse(error=e.oauth_error, error_description=str(e))
        response = make_response(error_resp.to_json(), 400)
        response.headers['Content-Type'] = 'application/json'
        return response
コード例 #10
0
    def test_token_endpoint_with_invalid_client_authentication(self, context, frontend, authn_req):
        context.request = AccessTokenRequest(redirect_uri=authn_req["redirect_uri"], code="code").to_dict()
        credentials = "{}:{}".format("unknown", "unknown")
        basic_auth = urlsafe_b64encode(credentials.encode("utf-8")).decode("utf-8")
        context.request_authorization = "Basic {}".format(basic_auth)

        response = frontend.token_endpoint(context)
        parsed_message = TokenErrorResponse().deserialize(response.message, "json")
        assert response.status == "401 Unauthorized"
        assert parsed_message["error"] == "invalid_client"
コード例 #11
0
    def test_token_endpoint_with_invalid_code(self, context, frontend, authn_req):
        self.insert_client_in_client_db(frontend, authn_req["redirect_uri"])
        context.request = AccessTokenRequest(redirect_uri=authn_req["redirect_uri"], code="invalid").to_dict()
        credentials = "{}:{}".format(CLIENT_ID, CLIENT_SECRET)
        basic_auth = urlsafe_b64encode(credentials.encode("utf-8")).decode("utf-8")
        context.request_authorization = "Basic {}".format(basic_auth)

        response = frontend.token_endpoint(context)
        parsed_message = TokenErrorResponse().deserialize(response.message, "json")
        assert response.status == "400 Bad Request"
        assert parsed_message["error"] == "invalid_grant"
コード例 #12
0
ファイル: test_oic_provider.py プロジェクト: asheidan/pyoidc
def test_token_endpoint_unauth():
    server = provider_init

    authreq = AuthorizationRequest(state="state",
                                   redirect_uri="http://example.com/authz",
                                   client_id="client_1")

    _sdb = server.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.token(sid=sid)
    _sdb[sid] = {
        "oauth_state": "authz",
        "sub": "user_id",
        "authzreq": "",
        "client_id": "client_1",
        "code": access_grant,
        "code_used": False,
        "scope": ["openid"],
        "redirect_uri":"http://example.com/authz"
    }

    # Construct Access token request
    areq = AccessTokenRequest(code=access_grant,
                              redirect_uri="http://example.com/authz",
                              client_id="client_1", client_secret="secret",)

    print areq.to_dict()
    str = areq.to_urlencoded()
    fil = StringIO.StringIO(buf=str)
    environ = BASE_ENVIRON.copy()
    environ["CONTENT_LENGTH"] = len(str)
    environ["wsgi.input"] = fil
    environ["REMOTE_USER"] = "******"
    environ["REQUEST_METHOD"] = "POST"

    resp = server.token_endpoint(environ, start_response)
    print resp
    atr = TokenErrorResponse().deserialize(resp[0] ,"json")
    print atr.keys()
    assert _eq(atr.keys(), ['error'])
コード例 #13
0
    def token_endpoint(self, context):
        """
        Handle token requests (served at /token).
        :type context: satosa.context.Context
        :rtype: oic.utils.http_util.Response

        :param context: the current context
        :return: HTTP response to the client
        """
        headers = {"Authorization": context.request_authorization}
        try:
            response = self.provider.handle_token_request(
                urlencode(context.request), headers)
            return Response(response.to_json(), content="application/json")
        except InvalidClientAuthentication as e:
            logger.debug('invalid client authentication at token endpoint',
                         exc_info=True)
            error_resp = TokenErrorResponse(error='invalid_client',
                                            error_description=str(e))
            response = Unauthorized(error_resp.to_json(),
                                    headers=[("WWW-Authenticate", "Basic")],
                                    content="application/json")
            return response
        except OAuthError as e:
            logger.debug('invalid request: %s', str(e), exc_info=True)
            error_resp = TokenErrorResponse(error=e.oauth_error,
                                            error_description=str(e))
            return BadRequest(error_resp.to_json(), content="application/json")
コード例 #14
0
def test_token_endpoint_unauth():
    server = provider_init

    authreq = AuthorizationRequest(state="state",
                                   redirect_uri="http://example.com/authz",
                                   client_id="client_1")

    _sdb = server.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.token(sid=sid)
    _sdb[sid] = {
        "oauth_state": "authz",
        "sub": "sub",
        "authzreq": "",
        "client_id": "client_1",
        "code": access_grant,
        "code_used": False,
        "scope": ["openid"],
        "redirect_uri": "http://example.com/authz"
    }

    # Construct Access token request
    areq = AccessTokenRequest(
        code=access_grant,
        redirect_uri="http://example.com/authz",
        client_id="client_1",
        client_secret="secret",
    )

    print areq.to_dict()
    txt = areq.to_urlencoded()

    resp = server.token_endpoint(request=txt,
                                 remote_user="******",
                                 request_method="POST")
    print resp
    atr = TokenErrorResponse().deserialize(resp.message, "json")
    print atr.keys()
    assert _eq(atr.keys(), ['error'])
コード例 #15
0
ファイル: claims_provider.py プロジェクト: asheidan/pyoidc
    def claims_endpoint(self, environ, start_response, *args):
        _log_info = logger.info

        query = get_or_post(environ)
        ucreq = self.srvmethod.parse_user_claims_request(query)

        _log_info("request: %s" % ucreq)

        if not self.function["verify_client"](environ, ucreq, self.cdb):
            _log_info("could not verify client")
            err = TokenErrorResponse(error="unathorized_client")
            resp = Unauthorized(err.to_json(), content="application/json")
            return resp(environ, start_response)

        if "claims_names" in ucreq:
            args = dict([(n, {"optional": True}) for n in ucreq["claims_names"]])
            uic = UserInfoClaim(claims=Claims(**args))
        else:
            uic = None

        _log_info("User info claims: %s" % uic)

        #oicsrv, userdb, subject, client_id="", user_info_claims=None
        info = self.function["userinfo"](self, self.userdb, ucreq["sub"],
                                         ucreq["client_id"],
                                         user_info_claims=uic)

        _log_info("User info: %s" % info.to_dict())

        if self.do_aggregation(info, ucreq["sub"]):
            cresp = self._aggregation(info)
        else:
            cresp = self._distributed(info)

        _log_info("response: %s" % cresp.to_dict())

        resp = Response(cresp.to_json(), content="application/json")
        return resp(environ, start_response)
コード例 #16
0
ファイル: openid_connect.py プロジェクト: SUNET/SATOSA
    def token_endpoint(self, context):
        """
        Handle token requests (served at /token).
        :type context: satosa.context.Context
        :rtype: oic.utils.http_util.Response

        :param context: the current context
        :return: HTTP response to the client
        """
        headers = {"Authorization": context.request_authorization}
        try:
            response = self.provider.handle_token_request(urlencode(context.request), headers)
            return Response(response.to_json(), content="application/json")
        except InvalidClientAuthentication as e:
            logger.debug('invalid client authentication at token endpoint', exc_info=True)
            error_resp = TokenErrorResponse(error='invalid_client', error_description=str(e))
            response = Unauthorized(error_resp.to_json(), headers=[("WWW-Authenticate", "Basic")],
                                    content="application/json")
            return response
        except OAuthError as e:
            logger.debug('invalid request: %s', str(e), exc_info=True)
            error_resp = TokenErrorResponse(error=e.oauth_error, error_description=str(e))
            return BadRequest(error_resp.to_json(), content="application/json")
コード例 #17
0
ファイル: fakeoicsrv.py プロジェクト: zack53/pyoidc
    def token_endpoint(self, data):
        if "grant_type=refresh_token" in data:
            req = self.parse_refresh_token_request(body=data)
            _info = self.sdb.refresh_token(req["refresh_token"],
                                           req['client_id'])
        elif "grant_type=authorization_code" in data:
            req = self.parse_token_request(body=data)
            if 'offline_access' in self.sdb[req['code']]['scope']:
                _info = self.sdb.upgrade_to_token(req["code"],
                                                  issue_refresh=True)
            else:
                _info = self.sdb.upgrade_to_token(req["code"])
        else:
            response = TokenErrorResponse(error="unsupported_grant_type")
            return response, ""

        resp = AccessTokenResponse(**by_schema(AccessTokenResponse, **_info))
        response2 = Response()
        response2.headers = {"content-type": "application/json"}
        response2.text = resp.to_json()

        return response2
コード例 #18
0
def token_endpoint():
    try:
        token_response = current_app.provider.handle_token_request(flask.request.get_data().decode('utf-8'),
                                                                   flask.request.headers)
        return jsonify(token_response.to_dict())
    except InvalidClientAuthentication as e:
        current_app.logger.debug('invalid client authentication at token endpoint', exc_info=True)
        error_resp = TokenErrorResponse(error='invalid_client', error_description=str(e))
        response = make_response(error_resp.to_json(), 401)
        response.headers['Content-Type'] = 'application/json'
        response.headers['WWW-Authenticate'] = 'Basic'
        return response
    except OAuthError as e:
        current_app.logger.debug('invalid request: %s', str(e), exc_info=True)
        error_resp = TokenErrorResponse(error=e.oauth_error, error_description=str(e))
        response = make_response(error_resp.to_json(), 400)
        response.headers['Content-Type'] = 'application/json'
        return response
コード例 #19
0
 def oidc_token(self) -> Union[str, Response]:
     print(request)
     try:
         token_response = self.provider.handle_token_request(
             request.get_data().decode("utf-8"), request.headers)
         return Response(token_response.to_json(),
                         mimetype="application/json")
     except InvalidClientAuthentication as err:
         error_resp = TokenErrorResponse(error="invalid_client",
                                         error_description=str(err))
         http_response = Response(error_resp.to_json(),
                                  status=401,
                                  mimetype="application/json")
         http_response.headers["WWW-Authenticate"] = "Basic"
         logging.error(error_resp.to_dict())
         return http_response
     except OAuthError as err:
         error_resp = TokenErrorResponse(error=err.oauth_error,
                                         error_description=str(err))
         return Response(error_resp.to_json(),
                         status=400,
                         mimetype="application/json")
コード例 #20
0
ファイル: provider.py プロジェクト: wayward710/pyoidc
        logger.info("token_request: %s" % request)

        req = AccessTokenRequest().deserialize(request, "urlencoded")
        if "refresh_token" in req:
            req = RefreshAccessTokenRequest().deserialize(request, "urlencoded")

        logger.debug("%s: %s" % (req.__class__.__name__, req))

        try:
            resp = self.client_authn(self, req, authn)
        except Exception, err:
            logger.error("Failed to verify client due to: %s" % err)
            resp = False

        if not resp:
            err = TokenErrorResponse(error="unathorized_client")
            return Unauthorized(err.to_json(), content="application/json")

        if isinstance(req, AccessTokenRequest):
            return self._access_token_endpoint(req, **kwargs)
        else:
            return self._refresh_access_token_endpoint(req, **kwargs)


    def _collect_user_info(self, session, userinfo_claims=None):
        """
        Collect information about a user.
        This can happen in two cases, either when constructing an IdToken or
        when returning user info through the UserInfo endpoint

        :param session: Session information