若依开源框架登录扩展Springboot+security,密码、验证码多种登录

2023-11-20

自定义登录扩展类

  • 继承DaoAuthenticationProvider类型,重写additionalAuthenticationChecks方法
  • CustomLoginAuthenticationProvider.java
package com.qcn.framework.config;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 自定义登录扩展
 * @version 1.0
 * @author xiyan
 * @date 2020/08/11 18:24
 */
public class CustomLoginAuthenticationProvider extends DaoAuthenticationProvider {

    public CustomLoginAuthenticationProvider(UserDetailsService userDetailsService) {
        super();
        setUserDetailsService(userDetailsService);
    }

    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            if("CUSTOM_LOGIN_SMS".equals(presentedPassword)){
                //短信登录,不验证密码(还可以继续扩展,只要传进来的password标识即可)
            }else{
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
                    this.logger.debug("Authentication failed: password does not match stored value");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
            }
        }
    }
}


修改spring security配置

在这里插入图片描述

package com.qcn.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
import com.qcn.framework.security.filter.JwtAuthenticationTokenFilter;
import com.qcn.framework.security.handle.AuthenticationEntryPointImpl;
import com.qcn.framework.security.handle.LogoutSuccessHandlerImpl;

/**
 * spring security配置
 * 
 * @author ruoyi
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;
    
    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 退出处理类
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * 跨域过滤器
     */
    @Autowired
    private CorsFilter corsFilter;
    
    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                // CRSF禁用,因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/captchaImage","/api/anonymous/**").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
    }

    
    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomLoginAuthenticationProvider(userDetailsService));
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }
}

controller

	@ApiOperation("手机号+密码登录")
    @Log(title = "手机号+密码登录", businessType = BusinessType.OTHER)
    @PostMapping(value="/loginByMobile")
    public AjaxResult loginByMobile(@Validated @RequestBody LoginByPwdBody body)
    {
        CardUser entity=cardUserService.loginByMobileAndPwd(body.getMobile(),body.getPassword());
        String token=cardLoginService.login(body.getMobile(),body.getPassword());
        AjaxResult result = AjaxResult.success("登录成功!",entity);
        result.put(Constants.TOKEN, token);
        return result;
    }

    @ApiOperation("手机号+短信验证码登录")
    @Log(title = "手机号+短信验证码登录", businessType = BusinessType.OTHER)
    @PostMapping(value="/loginByCode")
    public AjaxResult loginByCode(@Validated @RequestBody LoginByCodeBody body)
    {
        CardUser entity=cardUserService.loginByMobileAndCode(body);
        String token=cardLoginService.login(body.getMobile(),"CUSTOM_LOGIN_SMS");
        AjaxResult result = AjaxResult.success("登录成功!",entity);
        result.put(Constants.TOKEN, token);
        smsService.deleteSmsRedis(body.getSource());
        return result;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

若依开源框架登录扩展Springboot+security,密码、验证码多种登录 的相关文章

随机推荐

  • 关于linux进程间的close-on-exec机制

    转载请注明出处 帘卷西风的专栏 http blog csdn net ljxfblog 前几天写了一篇博客 讲述了端口占用情况的查看和解决 关于linux系统端口查看和占用的解决方案 大部分这种问题都能够解决 在文章的最后 提到了一种特殊情
  • 判断字符串的两半是否相似(1704.leetcode)-------------------c++实现

    判断字符串的两半是否相似 1704 leetcode unordered map c 实现 题目表述 给你一个偶数长度的字符串 s 将其拆分成长度相同的两半 前一半为 a 后一半为 b 两个字符串 相似 的前提是它们都含有相同数目的元音 a
  • Tensorflow学习(五)——多任务学习验证码识别实战

    一 验证码生成 验证码生成脚本 使用captcha包提供的ImageCaptcha方法 from captcha image import ImageCaptcha import sys import random import numpy
  • 成功解决笔记本重装系统后没有无线网

    笔记本重装系统后没有无线网 一般的解决思路就是下载笔记本厂家官方提供的各类驱动程序 重新安装驱动 驱动下载的地址 建议到各个厂家的官网上去寻找驱动资源 以本人的笔记本型号为例 点击window R 然后输入dxdiag运行 然后找到该官方开
  • 用js/react写一个计算器

    效果图如下 直接上代码 目录如下 Button和Text是自己封装的Button组件和Input组件 Button index js import react Component from react import index css cl
  • 图像风格迁移cvpr2020_今日 Paper

    目录 CurricularFace 深度人脸识别的适应性课程学习损失 MaskGAN 多样和交互的面部图像操作 结合检测和跟踪的视频人体姿态估计 通过解纠缠表示的局部面部妆容迁移 基于自动生成的训练数据进行大规模事件抽取学习 Curricu
  • 【UiBot】RPA定时触发:机器人如何在指定时间执行任务?

    Q RPA机器人如何在指定时间点执行任务 A 用流程机器人 UiBot Worker 设置定时触发 人机交互的流程机器人 UiBot Worker 除了手动运行流程之外 还提供了 触发器 的功能 可以在满足一定条件时 有计划 有选择性地执行
  • C++定义二维数组并赋值,亲测可用

    代码在这里 拿走不谢 include
  • IDEA springboot项目导出jar包及运行jar包

    首先点击Terminal 在Terminal下输入 mvn clean package 看到以下这个提示则是打包成功 接着咱们可以在自己的项目下看到打包成功的jar包 如图 运行jar包 我的jar包位置如下 写一个bat文件 里面的内容为
  • 实时监控Cat之旅~配置Cat集群需要注意的问题

    在配置cat集群时 有一些设置是我们应该注意的 从它的部署文档中我们可以看到相关信息 但说的还不够明确和重要 大叔今天总结一下Cat集群配置的注意事项 服务端datasources xml用来设置连接的mysql 集群里的服务器对这项配置是
  • pyecharts运行后产生的html文件用浏览器打开空白

    引用 https github com pyecharts pyecharts issues 503 使用logging日志打印代码错误 coding utf 8 from future import unicode literals im
  • Mageia 9 发布:搭载 Linux 内核 6.4,支持 PulseAudio

    导读 Mageia 最初是 Mandriva Linux 的一个分支 但现在已经发展成全面的 独立 Linux 发行版 从 2010 年以来 Mageia 已经成为一个用于桌面或服务器的稳定且安全的操作系统 并且定期更新 它的近期的发布公告
  • C语言排序算法实现

    C语言实现各种排序算法 冒泡排序 选择排序 插入排序 希尔排序 插入方式 非交换方式 快速排序 归并排序 分治思想 基数排序 桶排序 基数排序的基本思想 典型的空间换时间方式 冒泡排序 include
  • moviepy 生成的视频只有声音没有图像

    问题描述 PDF转成视频 用moviepy 将图片生成视频的时候 生成的视频 有些播放器 播放只有声音没有图像 解决方案 查看源码后发现在 ffmpeg writer py 文件里面有一段这样的代码 if codec libx264 and
  • 在线AI日语视频音频翻译中文字幕

    新番视频没有字幕 AI日语字幕识别让你先睹为快 蓝海智能在线AI工具 niceaitools com languageTra 目前价格是每视频音频分钟0 42元 具体使用方法如下 1 格式工厂处理 把你的日语视频或音频文件 通过格式工厂处理
  • VBA 自定义函数 库存消耗截止

    两个自定义函数 按照库存 计算哪一周库存能消耗完 标出周 自定义函数 按照库存 计算消耗完的那一周实际消耗多少数量 自定义函数 从消耗完的那一周开始算起 后面的周消耗数量都变为0 按钮 Function HaoJin StockQty As
  • Pytorch中常用的损失函数

    Pytorch中常用的损失函数 回归 nn L1Loss nn MSELoss 分类 nn CrossEntropyLoss 回归 nn L1Loss 平均绝对误差 也称L1范数损失 计算预测值与真实值之间的误差绝对值 L 1 L o s
  • python中模块,包,库的概念

    https www cnblogs com mlgjb p 7875494 html 模块 就是 py文件 里面定义了一些函数和变量 需要的时候就可以导入这些模块 包 在模块之上的概念 为了方便管理而将文件进行打包 包目录下第一个文件便是
  • OpenGL入门教程之 深入理解

    一 OpenGL简介 OpenGL是一种用于渲染2D 3D矢量图形的跨语言 跨平台的应用程序编程规范 OpenGL包含一系列可以操作图形和图像的函数 但OpenGL没有实现这些函数 OpenGL仅规定每个函数应该如何执行以及其输出值 类似接
  • 若依开源框架登录扩展Springboot+security,密码、验证码多种登录

    自定义登录扩展类 继承DaoAuthenticationProvider类型 重写additionalAuthenticationChecks方法 CustomLoginAuthenticationProvider java package