gpt4 book ai didi

python - Django 为 WebView 返回带有 TokenAuthentication 的 View

转载 作者:行者123 更新时间:2023-12-04 11:53:46 25 4
gpt4 key购买 nike

我正在尝试创建一个 flutter 应用程序,它将使用 webview 显示来自我的 Django 应用程序的经过身份验证的数据。
涉及步骤:

  • Flutter 应用发送身份验证请求
  • Django 验证用户凭据(用户 ID 和密码)并返回 authtoken
  • Flutter 然后通过 webview 将请求发送到 url(需要登录)。

  • 我想使用此 token 在 webapp 中登录用户并返回 webview。
    如果 url 不需要身份验证,它就像一个魅力。
    当 url 需要身份验证时,我被重定向到登录页面,我希望用户使用在步骤 1 中已经获得的 token 身份验证来绕过它
    这是我的 Django View 。
    class QuizTake(FormView):
    permission_classes = (IsAuthenticated,)
    form_class = QuestionForm
    template_name = 'question.html'
    result_template_name = 'result.html'
    single_complete_template_name = 'single_complete.html'
    login_template_name='login.html'


    def dispatch(self, request, *args, **kwargs):
    self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name'])
    print(self.kwargs['quiz_name'])

    """
    Authenticate if the request has token authentication
    """

    if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'):
    raise PermissionDenied

    try:
    self.logged_in_user = self.request.user.is_authenticated()
    except TypeError:
    self.logged_in_user = self.request.user.is_authenticated

    if self.logged_in_user:
    self.sitting = Sitting.objects.user_sitting(request.user,
    self.quiz)
    else:
    self.sitting = self.anon_load_sitting()

    if self.sitting is False:
    print("sitting false")
    if self.logged_in_user:
    return render(request, self.single_complete_template_name)
    else:
    redirecturl = "/login/?next=/quiz/"+self.kwargs['quiz_name']+"/take/"
    return redirect(redirecturl)
    return super(QuizTake, self).dispatch(request, *args, **kwargs)
    颤振代码
    class _QuizLauncherState extends State<QuizLauncher> {
    final String url, authtoken;
    final int userId;
    String quizUrl;
    _QuizLauncherState(this.url, this.authtoken,this.userId);

    void initState() {
    quizUrl = 'https://test.mysite.com/quiz/$url/take';
    print(quizUrl);
    //for reference https://test.mysite.com/quiz/56df5d90-7f67-45ff-8fe1-7c07728ba9ab/take/
    super.initState();
    }

    Completer<WebViewController> _controller = Completer<WebViewController>();
    final Set<String> _favorites = Set<String>();

    @override
    Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
    // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
    actions: <Widget>[
    NavigationControls(_controller.future),
    Menu(_controller.future, () => _favorites),
    ],
    ),
    body: WebView(
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (WebViewController webViewController) {
    Map<String, String> headers = {"Authorization": "Bearer " + authtoken};
    webViewController.loadUrl(quizUrl, headers: headers);
    },

    ),
    );
    }
    }
    这可能吗?如果有任何替代方法,请告诉我。基本上,我试图通过需要身份验证的 webview 访问 url,使用 authtoken。请帮忙。

    最佳答案

    您可以像这样使用自定义身份验证类,假设您正在使用 Authorization header :

    from rest_framework.authentication import BaseAuthentication

    class MyCustomAuth(BaseAuthentication):
    def authenticate(self, request):
    auth_method, token = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
    # Get your user via the token here
    if you_got_your_user:
    return user, None
    return None # or raise AuthFailedException


    class QuizTake(FormView):
    authentication_classes = (MyCustomAuth, )
    这仍然取决于您的 token 如何识别用户。例如,如果您正在使用 JWT,那么已有的身份验证类可以为您处理此问题。
    编辑:
    查看来自 here 的 Knox 文档.如果你用过 knox,那么你大概应该用他们自己的 TokenAuthentication类(class)。您可以尝试使用以下代码:
    from knox.auth import TokenAuthentication

    class QuizTake(FormView):
    authentication_classes = (TokenAuthentication, )

    关于python - Django 为 WebView 返回带有 TokenAuthentication 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68226886/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com