怎样做到SpringSecurity密码大小写不敏感

SpringSecurity里面是没有设置“大小写不敏感”的地方的。所以只有采用我的这个方法。

首先重写UsernamePasswordAuthenticationFilter,因为SpringSecurity的实现实际上就是很多Filter,所以这里还是重写一下

attemptAuthentication(HttpServletRequest request,HttpServletResponse response)的方法。

这个方法里面会读取password并且去验证。

@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request);
            username = username != null ? username : "";
            username = username.trim();
            String password = this.obtainPassword(request);
            password = password != null ? password : "";
            password = toUpperAndToLower.toUpperCase(password);//将接收到的密码全部调整成大写,这里就不上源码了,影响阅读。
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

然后去下面这个类里面去设定。这个类就是SpringSecurity的设定类。

public class SecurityConfig extends WebSecurityConfigurerAdapter

在这个方法里面:

protected void configure(HttpSecurity http) 

下面这段:

//添加自己定义的Filter
        http.addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

跳转页面设定保留下面的就可以了,其他删掉:

//设置在没登录的时候访问其他页面的时候系统直接跳转到登录页面
        http
                .formLogin()
                .loginPage("/");

然后在下面这个类里面:

public class SecurityConfig extends WebSecurityConfigurerAdapter

添加:

/**
     * 这个方法是自己写了一个AuthenticationFilter。因为原来的系统中的不能够调整用户登录的时候的密码大小写。自豪自己重写。
     * @return
     * @throws Exception
     */
    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception{
//        System.out.println("自己用的过滤器起作用了。");
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        //如果登录前没有访问地址的话,登录成功之后跳转的页面。这个handler是可以检查登录前页面的功能,如果登录前有访问页面是直接跳转到那个页面的
        handler.setDefaultTargetUrl("/index");
        filter.setAuthenticationSuccessHandler(handler);//将handler传入拦截器

        filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
        filter.setFilterProcessesUrl("/login");//登录信息提交地址

        //这句很关键,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己组装AuthenticationManager
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;

    }

这里面我重写了“AuthenticationFailureHandler”其他我,没动

/**
 * 这个就是个登陆后的错误处理类。
 */
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("status", 401);
        if (e instanceof LockedException) {
            map.put("msg", "账户被锁定,登录失败!");
        } else if (e instanceof BadCredentialsException) {
            map.put("msg", "用户名或密码输入错误,登录失败!");
        } else if (e instanceof DisabledException) {
            map.put("msg", "账户被禁用,登录失败!");
        } else if (e instanceof AccountExpiredException) {
            map.put("msg", "账户过期,登录失败!");
        } else if (e instanceof CredentialsExpiredException) {
            map.put("msg", "密码过期,登录失败!");
        } else {
            map.put("msg", "登录失败!");
        }
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}

好了,现在就没什么问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
# 该项目骨架集成了以下技术: - SpringBoot多环境配置 - SpringMVC - Spring - MyBaits - MyBatis Generator - MyBatis PageHelper - Druid - Lombok - JWT - Spring Security - JavaMail - Thymeleaf - HttpClient - FileUpload - Spring Scheduler - Hibernate Validator - Redis Cluster - MySQL主从复制,读写分离 - Spring Async - Spring Cache - Swagger - Spring Test - MockMvc - HTTPS - Spring DevTools - Spring Actuator - Logback+Slf4j多环境日志 - i18n - Maven Multi-Module - WebSocket - ElasticSearch # 功能们: ## 用户模块 - 获取图片验证码 - 登录:解决重复登录问题 - 注册 - 分页查询用户信息 - 修改用户信息 ## 站内信模块 - 一对一发送站内信 - 管理员广播 - 读取站内信(未读和已读) - 一对多发送站内信 ## 文件模块 - 文件上传 - 文件下载 ## 邮件模块 - 单独发送邮件 - 群发邮件 - Thymeleaf邮件模板 ## 安全模块 - 注解形式的权限校验 - 拦截器 ## 文章管理模块 - 增改删查 # 整合注意点 1. 每个Mapper上都要加@Mapper 2. yaml文件 @Value获取xx.xx.xx不可行,必须使用@ConfigurationProperties,指定prefix,属性设置setter和getter 3. logback日志重复打印:自定义logger上加上 ` additivity="false" ` 4. SpringBoot 项目没有项目名 5. 登录 Spring Security +JWT - 已登录用户验证token - 主要是在Filter中操作。 从requestHeader中取得token,检查token的合法性,检查这一步可以解析出username去查数据库; 也可以查询缓存,如果缓存中有该token,那么就没有问题,可以放行。 - 未登录用户进行登录 - 登录时要构造UsernamePasswordAuthenticationToken,用户名和密码来自于参数,然后调用AuthenticationManager的authenticate方法, 它会去调用UserDetailsService的loadFromUsername,参数是token的username,然后比对password,检查userDetails的一些状态。 如果一切正常,那么会返回Authentication。返回的Authentication的用户名和密码是正确的用户名和密码,并且还放入了之前查询出的Roles。 调用getAuthentication然后调用getPrinciple可以得到之前听过UserDetailsService查询出的UserDetails - 在Controller中使用@PreAuthorize等注解需要在spring-web配置文件中扫描security包下的类 6. 引用application.properties中的属性的方式:@ConfigurationProperties(prefix = "spring.mail") + @Component + setter + getter 7. 引用其他自定义配置文件中的属性的方式: - @Component - ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值