CSRF auth认证

csrf相关装饰器

from django.views.decorators.csrf import csrf_exempt,csrf_protect
"""
csrf_exempt 
    忽略csrf校验
csrf_protect
    开启csrf校验
"""
# 针对FBV
@csrf_protect\@csrf_exempt
def login(request):
    return render(request,'login.html')

# 针对CBV
csrf_protect 三种CBV添加装饰器的方式都可以
csrf_exempt  只有一种方式可以生效(给重写的dispatch方法装)

基于中间件思想编写项目

importlib模块
    可以通过字符串的形式导入模块
# 常规导入方式from ccc import bprint(b)  # <module 'ccc.b' from '/Users/jiboyuan/PycharmProjects/day61_1/ccc/b.py'>print(b.name)
# 字符串导入方式import importlibmodule_path = 'ccc.b'res = importlib.import_module(module_path)print(res.name)

from ccc.b import name  # 可以直接导变量数据
import importlib
module_path = 'ccc.b.name'
importlib.import_module(module_path)  # 不可以 最小导入单位是模块文件级别


'''以发送提示信息为需求 编写功能'''
方式1:封装成函数
方式2:封装成配置
import settings
import importlib
def send_all(msg):
    # 1.循环获取配置文件中字符串信息
    for str_path in settings.NOTIFY_FUNC_LIST:  # 'notify.email.Email'
        # 2.切割路径信息
        module_path, class_str_name = str_path.rsplit('.', maxsplit=1)  # ['notify.email','Email']
        # 3.根据module_path导入模块文件
        module = importlib.import_module(module_path)
        # 4.利用反射获取模块文件中对应的类名
        class_name = getattr(module, class_str_name)  # Email  Msg  QQ
        # 5.实例化
        obj = class_name()
        # 6.调用发送消息的功能
        obj.send(msg)

auth认证模块

# django提供给你快速完成用户相关功能的模块
    用户相关功能:创建、认证、编辑...
# django也配套提供了一张'用户表'
    执行数据库迁移命令之后默认产生的auth_user
# django自带的admin后台管理用户登录参考的就是auth_user表
    创建admin后台管理员用户:run manage.py task>>:createsuperuser
    自动对用户密码进行加密处理并保存

auth模块方法大全

from django.contrib import auth
# 1.验证用户名和密码是否正确
    auth.authenticate()
# 2.保存用户登录状态
    auth.login()
# 3.获取当前用户对象
    request.user
# 4.判断当前用户是否登录
    request.user.is_authenticated()
# 5.校验登录装饰器
    from django.contrib.auth.decorators import login_required
    @login_required(login_url='/lg/')  # 局部配置
    @login_required  # 全局配置
    LOGIN_URL = '/lg/'  # 需要在配置文件中添加配置
# 6.修改密码
    request.user.check_password() 
  
  request.user.set_password()
  request.user.save()
# 7.注销登录
  auth.logout(request)
# 8.注册用户
  from django.contrib.auth.models import User
  User.objects.create_superuser()
  User.objects.create_suser()

auth扩展表字段

# 方式1:编写一对一表关系(了解)
# 方式2:类继承(推荐)
from django.contrib.auth.models import AbstractUser
class Users(AbstractUser):
    # 编写AbstractUser类中没有的字段 不能冲突!!!
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=32)

AUTH_USER_MODEL = 'app01.Users'
"""
1.类继承之后 需要重新执行数据库迁移命令 并且库里面是第一次操作才可以
2.auth模块所有的方法都可以直接在自定义模型类上面使用
    自动切换参照表
"""
ps:课下可以先继承表 之后才练习auth所有的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot提供了Spring Security来实现OAuth2认证,下面是Spring Boot OAuth2认证过程的简要流程: 1. 用户访问客户端,客户端需要获取用户授权,重定向到授权服务器的授权页面; 2. 用户在授权页面输入账号密码并授权,授权服务器验证用户身份并返回授权码; 3. 客户端使用授权码向授权服务器请求访问令牌; 4. 授权服务器验证授权码并颁发访问令牌; 5. 客户端使用访问令牌向资源服务器请求数据。 下面是Spring Boot OAuth2认证的源码实现: 1. 导入OAuth2依赖 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.0.RELEASE</version> </dependency> ``` 2. 配置授权服务器 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Autowired private PasswordEncoder passwordEncoder; @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .withClient("client") .secret(passwordEncoder.encode("secret")) .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(1800) .refreshTokenValiditySeconds(3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()) .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } } ``` 3. 配置资源服务器 ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/**").authenticated() .and().csrf().disable(); } } ``` 4. 配置安全认证 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and().formLogin().permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 以上是Spring Boot OAuth2认证的简要流程和源码实现,具体的实现细节可以参考Spring官方文档和源码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lamb!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值