禁用或限制/o/applications(django rest framework,oauth2)

x9ybnkn6  于 2023-07-01  发布在  Go
关注(0)|答案(3)|浏览(94)

我目前正在使用Django rest框架编写一个REST API,并使用oauth2进行身份验证(使用django-oauth-toolkit)。我对他们两个都很满意,做的正是我想要的。
不过,我有一点担心。我正在将我的应用程序传递到生产环境,并意识到/o/applications/ view可能有问题,每个人都可以访问它!我发现自己很惊讶没有看到任何关于它的文档,当我试图谷歌它。我错过什么了吗
一些想法,要么使一个自定义的视图,要求作为超级用户的身份验证(但这将是奇怪的,因为它会混合不同类型的身份验证,不是吗?),或将401或403视图的虚拟路由添加到/o/applications/。但我觉得这些听起来很古怪。难道没有官方的“最佳”解决方案吗?如果我是第一个遇到这个问题的人,我会感到非常惊讶,我一定错过了一些东西。
感谢提前!

ruarlubt

ruarlubt1#

仅使用基本URL:authorize/token/revoke_token/

from oauth2_provider.urls import base_urlpatterns, app_name

urlpatterns = [
    ...,  # some other urls

    # oauth2 urls
    path('o/', include((base_urlpatterns, app_name), namespace=app_name)
]

而不是像官方示例中那样使用所有URL:

path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
vm0i2vca

vm0i2vca2#

找到解决方案了!
事实上,/o/application之所以可以访问,是因为我打开了一个超级管理员会话。
一切都很好,然后:)

xggvc2p6

xggvc2p63#

我遇到了同样的问题,这是非常令人沮丧的。我最终提出了一个公认的不太理想的解决方案,它涉及到为您希望保护普通用户的路由重新定义oauth2_provider的内置视图。
1.在应用程序中创建一个名为oauth的新目录,并创建一个views.pyurls.py
1.在views.py中:
a.创建两个新的mixin StaffRequiredMixinApplicationOwnerIsStaffMixin。两者都要求user.is_staffTrue
B.通过复制/粘贴重新定义oauth2_provider.views.application.py中的视图,并更新它们以使用新的mixin。

from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms.models import modelform_factory
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView
from oauth2_provider import models as oauth2_provider_models

class StaffRequiredMixin(LoginRequiredMixin):
    """Verify that the current user is staff."""
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_staff:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

class ApplicationOwnerIsStaffMixin(StaffRequiredMixin):
    """
    This mixin is used to provide an Application queryset filtered by request.user.is_staff.
    """

    fields = "__all__"

    def get_queryset(self):
        return oauth2_provider_models.get_application_model().objects.filter(user=self.request.user.is_staff)

class ApplicationRegistration(StaffRequiredMixin, CreateView):
    """
    View used to register a new Application for the request.user
    """

    template_name = "oauth2_provider/application_registration_form.html"

    def get_form_class(self):
        """
        Returns the form class for the application model
        """
        return modelform_factory(
            oauth2_provider_models.get_application_model(),
            fields=(
                "name",
                "client_id",
                "client_secret",
                "client_type",
                "authorization_grant_type",
                "redirect_uris",
                "algorithm",
            ),
        )

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class ApplicationDetail(ApplicationOwnerIsStaffMixin, DetailView):
    """
    Detail view for an application instance owned by the request.user
    """

    context_object_name = "application"
    template_name = "oauth2_provider/application_detail.html"

class ApplicationList(ApplicationOwnerIsStaffMixin, ListView):
    """
    List view for all the applications owned by the request.user
    """

    context_object_name = "applications"
    template_name = "oauth2_provider/application_list.html"

class ApplicationDelete(ApplicationOwnerIsStaffMixin, DeleteView):
    """
    View used to delete an application owned by the request.user
    """

    context_object_name = "application"
    success_url = reverse_lazy("oauth2_provider:list")
    template_name = "oauth2_provider/application_confirm_delete.html"

class ApplicationUpdate(ApplicationOwnerIsStaffMixin, UpdateView):
    """
    View used to update an application owned by the request.user
    """

    context_object_name = "application"
    template_name = "oauth2_provider/application_form.html"

    def get_form_class(self):
        """
        Returns the form class for the application model
        """
        return modelform_factory(
            oauth2_provider_models.get_application_model(),
            fields=(
                "name",
                "client_id",
                "client_secret",
                "client_type",
                "authorization_grant_type",
                "redirect_uris",
                "algorithm",
            ),
        )

1.在urls.py中:
a.重新定义urlpatterns以匹配oauth2_provider.urls.py,并在新视图中替换所有基于application/authorized_tokens/的路由。
注意文件的最后两行。为了使所有其他路由可用于授权请求和授予令牌等。我们还需要为这里的用户提供default视图。

from django.urls import re_path
from . import views
from oauth2_provider import views as oauth2_provider_views
from oauth2_provider import urls as oauth2_provider_urls

app_name = "oauth"
urlpatterns = [
    # Application management views
    re_path(r"^applications/$", views.ApplicationList.as_view(), name="list"),
    re_path(r"^applications/register/$", views.ApplicationRegistration.as_view(), name="register"),
    re_path(r"^applications/(?P<pk>[\w-]+)/$", views.ApplicationDetail.as_view(), name="detail"),
    re_path(r"^applications/(?P<pk>[\w-]+)/delete/$", views.ApplicationDelete.as_view(), name="delete"),
    re_path(r"^applications/(?P<pk>[\w-]+)/update/$", views.ApplicationUpdate.as_view(), name="update"),
    # Token management views
    re_path(r"^authorized_tokens/$", oauth2_provider_views.AuthorizedTokensListView.as_view(), name="authorized-token-list"),
    re_path(r"^authorized_tokens/(?P<pk>[\w-]+)/delete/$", oauth2_provider_views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete")
]
urlpatterns += oauth2_provider_urls.base_urlpatterns
urlpatterns += oauth2_provider_urls.oidc_urlpatterns

1.在您的主要应用程序配置中urls.py
a.更新它以使用新的oauth路由和视图。
B.如果你有django_oauth_toolkit例子中的那个,用这个替换它。

urlpatterns = [
  path("", ..., name="home"),
  ...
# Remove this one
# path("o/", include("oauth2_provider.urls", namespace="oauth2_provider")),
# Add this one
  path("o/", include("your_application.oauth.urls", namespace="oauth2_provider")),
  ...
]

相关问题