SpringSecurity报错authenticationManager must be spec的解决

目录
  • 有两个地方要改下
  • 然后在过滤器里面显示的设置一下
  • 顺便贴一下两个类的完整代码
    • 过滤器
    • 配置文件

在重写类UsernamePasswordAuthenticationFilter时抛出了这个异常,字面上理解是authenticationManager不明确,所以要显示的注入。

有两个地方要改下

首先要在配置文件重写authenticationManager

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

然后在过滤器里面显示的设置一下

    @Autowired
    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

顺便贴一下两个类的完整代码

仅供参考:

过滤器

@Component
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    JwtTokenUtils jwtTokenUtils;

    public TokenLoginFilter() {
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //获取表单提交数据
        try {
            UserInfo user = new ObjectMapper().readValue(request.getInputStream(), UserInfo.class);
            return super.getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getLoginName(),user.getPassword(),
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        UserSecurity userSecurity = (UserSecurity) authResult.getPrincipal();
        String token = jwtTokenUtils.createToken(userSecurity.getUsername());
        ResponseUtils.out(response, R.ok(token));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseUtils.out(response, R.fail(ServiceError.LOGIN_FAIL));
    }

    @Autowired
    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }
}

配置文件

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserInfoServiceImpl userInfoService;

    @Autowired
    JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter;

    @Autowired
    TokenLoginFilter tokenLoginFilter;

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userInfoService).passwordEncoder(passwordEncoderBean());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/hello").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").anonymous()
                .anyRequest().authenticated()
                .and()
                .addFilterAt(tokenLoginFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(jwtAuthorizationTokenFilter, TokenLoginFilter.class).httpBasic();

    }

    @Bean
    public PasswordEncoder passwordEncoderBean() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot整合Security权限控制登录首页

    目录 在 pom 文件中增加thymeleaf页面支持 application.yml 配置文件 login 页面 controller目录下跳转配置 UserController 在 pom 文件中增加thymeleaf页面支持 <!-- 引入页面模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thym

  • SpringBoot Security使用MySQL实现验证与权限管理

    目录 1. 创建用户表和虚拟凭据 2. 配置数据源属性 3. 声明弹簧安全性和MySQL JDBC驱动程序的依赖关系 4. 配置 JDBC 身份验证详细信息 5. 自定义登录验证过程 6. 登录页面 7. 测试登录和注销 结论 在本教程中,我将指导您如何编写代码,以使用具有基于表单的身份验证的Spring安全API来保护Spring Boot应用程序中的网页.用户详细信息存储在MySQL数据库中,并使用春季JDBC连接到数据库.我们将从本教程中的 ProductManager 项目开始,向现有的

  • Spring Security中如何获取AuthenticationManager对象

    有时需要使用AuthenticationManager(以下简称Manager)对象,可是这个对象不是Bean,没有直接保存在Spring的Bean库中.那么如何获取Spring Security中的这个对象呢? 在Spring Security 5.7.0-M2之前,通常会扩展WebSecurityConfigurerAdapter(以下简称Adapter)类来自定义网络安全配置.Adapter类中有一个方法authenticationManager()可以提供Manager对象.但是从Spr

  • Spring Security 登录时添加图形验证码实现实例

    目录 前言 验证码生成 加入验证码依赖 验证码配置 验证码接口 加入依赖 基于过滤器 编写自定义认证逻辑 测试 基于认证器 编写自定义认证逻辑 测试 前言 在前面的几篇文章中,登录时都是使用用户名 + 密码进行登录的,但是在实际项目当中,登录时,还需要输入图形验证码.那如何在 Spring Security 现有的认证体系中,加入自己的认证逻辑呢?这就是本文的内容,本文会介绍两种实现方案,一是基于过滤器实现:二是基于认证器实现. 验证码生成 既然需要输入图形验证码,那先来生成验证码吧. 加入验证

  • SpringBoot 整合Security权限控制的初步配置

    正文 在源码目录下新建 config 目录, 在该目录下新建 WebSecurityConfig 类文件 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding co

  • Spring Security获取用户认证信息的实现流程

    目录 登录用户数据获取 SecurityContextHolder SecurityContextHolderStrategy 多线程情况下获取用户数据 页面上获取用户信息 登录用户数据获取 SecurityContextHolder ​ Spring Security 会将登录用户数据保存在 Session 中.但是,为了使用方便,Spring Security在此基础上还做了一些改进,其中最主要的一个变化就是线程绑定.当用户登录成功后,Spring Security 会将登录成功的用户信息保

  • SpringSecurity报错authenticationManager must be spec的解决

    目录 有两个地方要改下 然后在过滤器里面显示的设置一下 顺便贴一下两个类的完整代码 过滤器 配置文件 在重写类UsernamePasswordAuthenticationFilter时抛出了这个异常,字面上理解是authenticationManager不明确,所以要显示的注入. 有两个地方要改下 首先要在配置文件重写authenticationManager @Bean @Override protected AuthenticationManager authenticationManage

  • AngularJS报错$apply already in progress的解决方法分析

    本文实例分析了AngularJS报错$apply already in progress的解决方法.分享给大家供大家参考,具体如下: 如果我们使用了AngularJS中的$scope.$apply()或者$scope.$digest(),我们很可能会遇到类似下面的错误,虽然这个错误没有太大影响,但是在日志中看起来还是很不爽的,日志中记录的异常或者错误,就应该是需要关注和解决的问题,否则就没有必要出现在日志中了. Error: [$rootScope:inprog] $apply already

  • Mybatis报错: org.apache.ibatis.exceptions.PersistenceException解决办法

    Mybatis报错: org.apache.ibatis.exceptions.PersistenceException解决办法 一.问题描述 写好配置文件用JUnit进行测试,一运行就报错: org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: Error instantiat

  • bootstrap datetimepicker 日期插件在火狐下出现一条报错信息的原因分析及解决办法

    日期插件 bootstrap-datetimepicker 在火狐下出现一条报错信息:TypeError: (intermediate value).toString(-).split(-)[1] is undefined 这条错误必然出现,难道没有在 Firefox 下进行测试. 在 Firefox 下查看项目 demo (http://www.malot.fr/bootstrap-datetimepicker/demo.php)可以正常运行,但这个 demo.php 使用的是 2013-3-

  • maven package 打包报错 Failed to execute goal的解决

    总结一下maven 打包,项目工程开发工具idea14,使用 JDK 1.8 版本 1.打包前需要先将idea关掉,不然会导致mvn clean的时候,部分文件删除不掉,mvn package的时候,也会丢失文件. 2.mvn package打包报错:[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.6.1:clean (default-clean) on project 解决办法: 1. p

  • Unity报错InvalidOperationException: out of sync的解决

    Unity 报错 之 InvalidOperationException: out of sync 报错原文: InvalidOperationException: out of sync System.Collections.Generic.Dictionary2+Enumerator[System.Int32,UnityEngine.Transform].VerifyState () (at /Users/builduser/buildslave/mono/build/mcs/class/c

  • vue3.0报错Cannot find module ‘worker_threads‘的解决办法

     记录一下vue3.0的第一次尝试,启动项目的时候报错Cannot find module 'worker_threads',查了一下发现是因为个人电脑node版本太低,查看了一下版本 node -v v11.2.0 然后升级一下自己的node版本再执行启动命令就OK了 npm install -g n (mac记得加sudo) n latest 总结:需要把node.js升级到版本12以上,就可以解决vue3.0报错Cannot find module 'worker_threads'的问题了

  • Windows环境下npm install 报错: operation not permitted, rename的解决方法

    前言 最近发现了一个问题,运行 npm install 命令安装依赖包,在 Mac 上的 Vagrant 装的虚拟机上没问题,在阿里云 CentOS 上也没问题,但是在 Windows 环境同样是 Vagrant 装的环境相同的虚拟机上就是不成功,报错如下: npm ERR! Error: EPERM: operation not permitted, rename '/usr/share/nginx/html/tanteng.me/node_modules/duplexify' -> '/us

  • sql2000报错Successfully re-opened the local eventlog解决方法

    报错1:Unable to read local eventlog (reason: 事件日志文件已在读取间更改. 报错2:Successfully re-opened the local eventlog - NOTE: Some events may have been missed. 微软解释: http://support.microsoft.com/default.aspx?scid=kb;en-us;811484 解决办法: 如果要防止错误日志, 中出现这些消息可以使用跟踪标志 25

  • asp在iis7报错行号不准问题的解决方法

    在Win7中做ASP开发,发现了一个非常蛋疼的问题.出现错误的时候,行号不准,很难快读定位到出问题的代码(在Win2003的IIS6就没有问题).命名代码仅有几十行,报错的行号确到了几千行(应该IIS7运行时把 asp 所有include的代码给合并到了一个文件),如图: 经过查看IIS7中的ASP配置,发现 有个 计算行号的选项,设置为true就可以了.(注意:点击右侧的应用后,虽然提示生效,但是实际没有生效.必须用 iisreset 重启IIS后才可以生效)

随机推荐