Ejemplo n.º 1
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")
Ejemplo n.º 2
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'
Ejemplo n.º 3
0
    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"
Ejemplo n.º 4
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"
Ejemplo n.º 5
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
Ejemplo n.º 6
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"
Ejemplo n.º 7
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"
Ejemplo n.º 8
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
Ejemplo n.º 9
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")
Ejemplo n.º 10
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
Ejemplo n.º 11
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'])
Ejemplo n.º 12
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"],
                                           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