标签: django-authentication

@login_required 和 is_authenticated() -- 何时在 Django 中使用哪个?

我没有看到使用@login_required装饰器和: 之间有明显的区别is_authenticated():不知何故,我认为它们执行类似的检查(尽管不完全是)。

假设我functionviews.py

def dosomethingNow(request):
     if request.user.is_authenticated():
         //carry out the function
     else:
          //redirect to login page
Run Code Online (Sandbox Code Playgroud)

function与装饰器相同login_required

@login_required
def dosomethingNow(request):
     //carry out the function
Run Code Online (Sandbox Code Playgroud)

两者都function执行类似的检查,除了, 提供了重定向到if not inis_authenticated()的选项。homepagelogged

使用其中一种相对于另一种还有其他好处以及它们不能互换使用的地方吗?

谢谢

django django-authentication django-login login-required

5
推荐指数
1
解决办法
4539
查看次数

获取令牌身份验证视图时出现 Django REST HTTP 400 错误

我想在后端使用 Django 和 Django-REST 框架来对本机 android 应用程序上的用户进行身份验证。我目前正在使用基于令牌的身份验证系统。(更多细节

我已经实施了指南中列出的完全相同的过程来设置令牌身份验证。

现在我希望我的用户能够获取令牌以换取凭据。我使用以下代码发出 POST 请求:

      JSONObject cred = new JSONObject();

            try {
                cred.put("password",mPassword);
                cred.put("username",mEmail);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
               
                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(Common.getServerUrl()+"/api-token-auth/");
                StringEntity credentials = new StringEntity( cred.toString());
                credentials.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");
                httpPost.setEntity(credentials);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // Read content & Log
                inputStream = httpEntity.getContent();
                Log.i("Asynctask", cred .toString());
...
Run Code Online (Sandbox Code Playgroud)

但是,当我将其发布到“views.obtain_auth_token”的 django 后端时,我总是出现此错误:

在服务器上:

"POST …
Run Code Online (Sandbox Code Playgroud)

django android django-authentication django-rest-framework

5
推荐指数
1
解决办法
7401
查看次数

Django 自定义身份验证后端似乎没有被调用?

我在 Python 3 上使用 Django 1.8.4,并尝试创建一个身份验证后端,该后端验证来自旧版 ColdFusion 网站的 cookie,并在检查数据库中的值后创建/登录 Django 用户。在设置中,我包括后端:

AUTHENTICATION_BACKENDS = (
    'site_classroom.cf_auth_backend.ColdFusionBackend',
)
Run Code Online (Sandbox Code Playgroud)

以及后端本身的代码;SiteCFUser 是一个针对 SQL Server 数据库用户模型的模型,其中包含活动 cookie 令牌值:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from users.models import SiteCFUser


class ColdFusionBackend(ModelBackend):
    """
    Authenticates and logs in a Django user if they have a valid ColdFusion created cookie.

    ColdFusion sets a cookie called "site_web_auth"
    Example cookie: authenticated@site+username+domain+8E375588B1AAA9A13BE03E401A02BC46
    We verify this cookie in the MS SQL database 'site', table site_users, column user_last_cookie_token
    """

    def authenticate(self, request): …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-authentication django-class-based-views

5
推荐指数
1
解决办法
2110
查看次数

Django - AttributeError:“UserProfile”对象没有属性“urls”

我正在尝试User在 Django 中进行扩展。这个新的User属性应该比内置属性更多,User并且其中一些属性在注册过程中应该是必需的。此外,我希望在Admin. 我已遵循官方教程和YouTube 视频,但有一个error.

我是 Django 的新手,所以我不知道问题出在哪里。你知道出了什么问题吗?

编辑:我试图停止服务器并且makemigrations- 发生了同样的错误。

命令:

  File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages\venv\
lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages\venv\
lib\site-packages\django\utils\functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages\venv\
lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages\Solut
ionsForLanguagesProject\urls.py", line 22, in <module>
    url(r'^admin/', admin.site.urls),
  File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages\venv\
lib\site-packages\django\contrib\admin\sites.py", line 303, in …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-admin django-authentication

5
推荐指数
1
解决办法
5895
查看次数

自动生成的字段“user_ptr”与声明的同名字段冲突

我有一个带有 CustomUser 的 Django 应用程序。我的模型看起来像

class CustomUser(AbstractBaseUser):
    def get_short_name(self):
        pass

    def get_full_name(self):
        pass

    firstName = models.CharField(max_length=300)
    middleName = models.CharField(max_length=300, blank=True)
    lastName = models.CharField(max_length=300, blank=True)
    username = models.CharField(unique=True, max_length=50)
    businessName = models.CharField(max_length=500, default=None)
    mobileNumber = models.CharField(max_length=20)
    contactNumber = models.CharField(max_length=20)
    addressLine1 = models.CharField(max_length=300)
    addressLine2 = models.CharField(max_length=300)
    city = models.CharField(max_length=300)
    state = models.CharField(max_length=300)
    role = models.CharField(max_length=20)
    email_id = models.CharField(max_length=300, unique=True)
    aadharNumber = models.BigIntegerField(default=0)
    panNumber = models.CharField(max_length=20, default=None)
    registrationDate = models.BigIntegerField(default=0)
    bankDetail = models.ManyToManyField('BankDetail', related_name="bankDetail")
    dateCreated = models.DateTimeField(auto_now_add=True)
    dateModified = models.DateTimeField(auto_now=True)
    objects = AccountManager() …
Run Code Online (Sandbox Code Playgroud)

django django-authentication python-3.x django-rest-framework

5
推荐指数
1
解决办法
2146
查看次数

Django 多种身份验证模型

我正在开发一个项目,需要 3 种类型的用户。

  • 行政
  • 小贩
  • 顾客

我希望为所有三个供应商和客户拥有单独的模型,而不是在公共用户模型中拥有类型字段。

我解决这个问题的第一个方法是通过子类AbstractUser模型来定义所有模型

# models.py
from django.contrib.auth.models import AbstractUser

class Customer(AbstractUser):
    pass


class Vendor(AbstractUser):
    pass
Run Code Online (Sandbox Code Playgroud)

并添加自定义的身份验证后端来处理基于请求对象的用户身份验证。

# settings.py

AUTHENTICATION_BACKENDS = ['backends.CustomAuthBackend']
Run Code Online (Sandbox Code Playgroud)

我的 backends.py 文件将包含对用户进行身份验证的逻辑,并根据请求对象为每个用户使用不同的模型。

# backends.py
from __future__ import print_function


class CustomAuthBackend(object):

    def authenticate(self, request, username=None, password=None):
       # authenticate user based on request object

    def get_user(self, user_id):
        # logic to get user
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用,看起来我还需要在 settings.py 中指定用于身份验证的AUTH_USER_MODEL 。

Django 是否允许从 3 个不同的表进行身份验证?我怎样才能继续这个?还有其他方法吗?我应该改变什么?

python django django-models django-authentication

5
推荐指数
1
解决办法
6432
查看次数

django 休息框架社交身份验证与 jwt

你好,我正在使用 jwt 和 Angular 5 开发 SPA django Rest 框架。我建立了登录和注册部分。现在我正在寻找一种方法来添加社交登录或注册到我的应用程序并在深度搜索后获得 jwt 支持我发现一些模块的文档非常不清楚(至少对我来说)..这个模块 https://github.com/st4lk/ django-rest-social-auth看起来不错,他说使用:

/api/login/social/jwt_user/
Run Code Online (Sandbox Code Playgroud)

和:

/api/login/social/jwt/
Run Code Online (Sandbox Code Playgroud)

是 jwt 的终点,但是当我使用它们时这对我没有任何好处。

我们在闲聊中进行了一些聊天,但没有得出结论,任何人都可以向我和许多像我这样对这个问题感到困惑的开发人员解释解决方案吗?我们应该使用哪个模块,或者如果提到的模块可以,我们应该如何使用它

django-authentication django-socialauth single-page-application django-rest-framework

5
推荐指数
1
解决办法
4740
查看次数

当前路径 account/login/ 与其中任何一个都不匹配?

我正在尝试访问我的项目(本地),并且收到此回溯:

追溯

Page not found (404)
Request Method:
GET
Request URL:
http://127.0.0.1:8000/account/login/
Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: 
[name='login_redirect'] 
admin/ 
account/ ^$ 
account/ ^login$ 
account/ ^logout$ 
account/ ^register$ [name='register'] 
account/ ^profile$ [name='view_profile'] 
account/ ^profile/edit$ [name='edit_profile'] 
account/ ^change-password$ [name='change_password'] 
account/ ^reset-password$ [name='reset_password'] 
account/ ^reset-password/done$ [name='password_reset_done'] 
account/ ^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A- Za-z]{1,13}-[0-9A-Za-z]{1,23})/$ [name='password_reset_confirm'] 
account/ ^reset-password/complete$ [name='password_reset_complete'] 
The current path, account/login/, didn't match any of these. 
Run Code Online (Sandbox Code Playgroud)

主/urls.py

from django.contrib import admin
from django.urls import path, re_path, include
from …
Run Code Online (Sandbox Code Playgroud)

python django django-authentication

5
推荐指数
1
解决办法
8355
查看次数

使用 UserPassesTestMixin(基于类的视图)和重定向

我正在尝试使用基于类的视图,而我最终得到的是默认的 403 Forbidden 页面..mixin 类的顺序是否正确?代码是否甚至在 get/post 中被使用 - 还是所有内容都被绕过并发生默认的 403 重定向?

到目前为止看到的所有工作示例,仅指向基于函数的视图中的装饰器 @login_required 并使用请求对象重定向到登录页面。该文件提供了一些技巧,但我不能得到它与下面的代码工作..把错误堆栈为好。

查看

 "GET / HTTP/1.1" 200 2580
Forbidden (Permission denied): /app/custom-view
Traceback (most recent call last):
  File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\me\.envs\project\lib\site-packages\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, …
Run Code Online (Sandbox Code Playgroud)

django django-views django-authentication django-users django-class-based-views

5
推荐指数
1
解决办法
2321
查看次数

Django:跨多个域维护会话

我有两个/多个域,foo.com并且bar.com都具有相同的后端,这意味着两个域都将即将到来的请求重定向到托管在其他地方的同一个 “Web 实例”


当前行为

如果用户登录foo.com,他/她还需要登录bar.com才能访问任何端点/URL,例如bar.com/some/url/end-point/


SESSION_COOKIE_DOMAIN,如果我的域有可能做一些常见的模式。不幸的是,我没有。

问题
如何跨多个域维护用户会话?

python django django-authentication django-sessions

5
推荐指数
1
解决办法
1601
查看次数