Django--csrf跨站请求伪造Auth认证模块

Posted tulintao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django--csrf跨站请求伪造Auth认证模块相关的知识,希望对你有一定的参考价值。

form表单中使用跨站请求伪造

   % csrf_token %
  会动态生成一个input框,内部的value是随机刷新的

 

 

如果不想校验csrf

  from django.views.decorators.csrf import csrf_exempt, csrf_protect

  然后在不想装饰的函数的上面加上@csrf_exempt

  

如果只想校验单独一个的话就在那个函数的上面加上@csrf_protect

 

 

 

在CBV中添加csrf就是通过导入第三方模块

  from django.utils.decorators import method_decorator

  然后在方法上面利用method_decorator进行装饰,第一个参数传的是csrf_protect,第二个参数name要制定方法

 

csrf_protect在装饰的时候跟正常的CBV的装饰器一样,也是三种方式都可以的

csrf_exempt只能有下面两种方式

@method_decorator(csrf_exempt, name=dispatch)
class Index(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        super().dispatch(request, *args, **kwargs)

 

 

Auth模块: 

  命令行创建超级用户

    createsuperuser

  Auth模块是Django自带的用户认证模块

    我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统。此时我们需要实现包括用户注册、用户登录、用户认证、注销、修改密码等功能

    Django内置了强大的用户认证系统--auth, 它默认使用auth_user表来存储用户数据

 

  auth模块常用的方法:

    authenticate()

      提供了用户认证功能,即验证用户名以及密码是否正确,一般需要username、password两个关键字参数 

      如果认证成功,便会返回一个User对象

      authenticate()会在该User对象上设置一个属性来标识后端已经认证了该用户,并且该信息在后续的登陆过程中是需要的

  

    login(HttpRequest,user)

      该函数接受一个HttpRequest对象,以及一个认证过的User对象

      该函数实现一个用户登录的功能,它本质上会在后端为该用户生成相关的session数据

 

    logout(request)

      该函数没有返回值

      当调用该函数时,当前请求session会被全部清除。该用户即使没有登录,使用该函数也不会报错

 

    is_authenticated()

      用来判断当前请求是否通过了认证

  

    login_required()  

      auth给我们提供的一个装饰器工具,用来快捷给某个视图函数添加登录校验

from django.contrib.auth.decorators import login_required
      
@login_required
def my_view(request):
  ...

 

      若用户没有登录,就会跳转到Django默认的登录URL ‘/accounts/login/ ‘ 并传递当前访问url的绝对路径(若登陆成功后,会重定向到该路径)。

      如果需要自定义登录到URL,则需要在settings.py文件中通过LOGIN_URL进行修改

LOGIN_URL = /login/  # 这里配置成你项目登录页面的路由

    create_user()

      auth提供的一个创建新用户的方法,需要提供必要的参数(username, password)等

from django.contrib.auth.models import User
user = User.objects.create_user(username=用户名,password=密码,email=邮箱,...)

    

    create_superuser()

      auth提供的一个创建新用户的方法,需要提供必要的参数(username, password)等

from django.contrib.auth.models import User
user = User.objects.create_superuser(username=用户名,password=密码,email=邮箱,...)

 

      

    check_password(password)

      auth提供的一个检查密码是否正确的方法,需要提供当前请求用户的密码,密码正确就返回True,否则就返回False

ok = user.check_password(密码)

 

  

    set_password(password)

      auth提供的一个修改密码的方法,接受要设置的新密码 作为参数

      注意:设置完一定要调用用户对象的save方法       

user.set_password(password=‘‘)
user.save()

 

  

@login_required
def set_password(request):
    user = request.user
    err_msg = ‘‘
    if request.method == POST:
        old_password = request.POST.get(old_password, ‘‘)
        new_password = request.POST.get(new_password, ‘‘)
        repeat_password = request.POST.get(repeat_password, ‘‘)
        # 检查旧密码是否正确
        if user.check_password(old_password):
            if not new_password:
                err_msg = 新密码不能为空
            elif new_password != repeat_password:
                err_msg = 两次密码不一致
            else:
                user.set_password(new_password)
                user.save()
                return redirect("/login/")
        else:
            err_msg = 原密码输入错误
    content = 
        err_msg: err_msg,
    
    return render(request, set_password.html, content)

 

 

 

    User对象的属性

      username、password

      is_staff:用户是否拥有网站的管理权限

      is_active:是否允许用户登录,设置为False,可以在不删除用户的前提下禁止用户登录

 

  扩展默认的auth_user表

    auth_user表的字段就那么几个,我在项目中没办法直接拿来使用,比如我想要存储一个用户的手机号的字段,首先想到的肯定是一对一进行表与表之间的关联

    我们可以通过继承内置的AbstractUser类,来自定义一个Model类,这样既可以根据项目需求灵活的设计用户表,又能使用Django强大的认证系统了

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    """
    用户信息表
    """
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)
    
    def __str__(self):
        return self.username

    按上面的方式扩展了内置的auth_user表之后,一定要在settings.py中告诉Django,我现在使用我新定义的UserInfo表来做用户的认证,

# 引用Django自带的User表,继承使用时需要设置
AUTH_USER_MODEL = "app名.UserInfo"

    一旦我们指定了新的认证系统所使用的的表,我们就需要重新在数据库中创建该表,而不能继续使用原来默认的auth_user表了

 

 

 

 

 

 

 

 

 

    

 

以上是关于Django--csrf跨站请求伪造Auth认证模块的主要内容,如果未能解决你的问题,请参考以下文章

Django--CSRF 跨站请求伪造

Django CSRF跨站请求伪造

Django框架进阶7 django请求生命周期流程图, django中间件, csrf跨站请求伪造, auth认证模块

Python Django 生命周期 中间键 csrf跨站请求伪造 auth认证模块 settings功能插拔式源码

csrf跨站请求伪造;auth模块

django csrf,xss,sql注入