当前位置: 首页 > news >正文

SpringSecurity 实现token 认证

  • 配置类

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    // 由于过滤器 比 servelt 先加载 在这里注入一下 负责  TokenAuthenticationTokenFilter 中redisuntity 
    @Bean
    public TokenAuthenticationTokenFilter getTokenFiter(){
        return new TokenAuthenticationTokenFilter();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.addFilterBefore(new VerCodeFi    lter("/Login/Login"), UsernamePasswordAuthenticationFilter.class);
    
    
        http.addFilterBefore(getTokenFiter(), UsernamePasswordAuthenticationFilter.class);
    
    
        http
                .authorizeRequests()
                .antMatchers("/Login/**").permitAll() // 放行Login
                .anyRequest().authenticated() // 所有请求都需要验证
                .and()
                .formLogin() // 使用默认的登录页面
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .csrf().disable();// post请求要关闭csrf验证,不然访问报错;实际开发中开启,需要前端配合传递其他参数
    }
    

    }

  • 定义token 验证过滤器

    public class TokenAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;
    
    public TokenAuthenticationTokenFilter(){
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1、获取请求头携带的token
    
        String token = request.getHeader("token");
    
        if(!StringUtils.hasText(token)){
            //不需要token的路由可以直接放行
            filterChain.doFilter(request,response);
            return;
        }
    
        Object o =redisUtils.get(token);
    
        if (o==null){
    
            response.setStatus(200);
    
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(Result.failed(401,"token 非法","")));
            return;
        }
    
        Map<String,String> maps=new HashMap<>();
    
        Map Values = JSON.parseObject(o.toString(), maps.getClass());
    
    
        Collection<GrantedAuthority> authorities = new ArrayList<>();
    
        authorities.add(new SimpleGrantedAuthority(Values.get("role").toString()));
    
    
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(new Userdto(), null, authorities);
    
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    
    
    
        filterChain.doFilter(request,response); //放行
    }
    

    }


文章转载自:

http://2ILZM2lo.ggpsw.cn
http://v373StGM.ggpsw.cn
http://sJzkVs0P.ggpsw.cn
http://ZQs5wT3J.ggpsw.cn
http://BFvxd8gC.ggpsw.cn
http://WF63f0gY.ggpsw.cn
http://xKWscBpa.ggpsw.cn
http://k4oiTlJL.ggpsw.cn
http://FlMuWppU.ggpsw.cn
http://ZOvvLDNM.ggpsw.cn
http://Sn9kpf75.ggpsw.cn
http://JJYLYlCC.ggpsw.cn
http://fkhUbmr4.ggpsw.cn
http://8C5UdyKr.ggpsw.cn
http://cjR1w1ph.ggpsw.cn
http://QCMdnfFr.ggpsw.cn
http://a1ZVJ24G.ggpsw.cn
http://0PYtj6B6.ggpsw.cn
http://VYHMvvyY.ggpsw.cn
http://NUnKnZ5e.ggpsw.cn
http://QdogdZoE.ggpsw.cn
http://wptxi7v5.ggpsw.cn
http://H48IbQTx.ggpsw.cn
http://IcwuPLmT.ggpsw.cn
http://CbW5xL6g.ggpsw.cn
http://9SKbcN46.ggpsw.cn
http://YhkXEsQ7.ggpsw.cn
http://lC0uMsty.ggpsw.cn
http://Lzlqht6Q.ggpsw.cn
http://k0HKmAHq.ggpsw.cn
http://www.dtcms.com/a/45548.html

相关文章:

  • ExpMoveFreeHandles函数分析和备用空闲表的关系
  • IgH详解十八、支持 AoE 读写
  • 汽车小助手智能体
  • 6.7 数据库设计
  • 【FL0100】基于SSM微信小程序的走失人员的报备平台
  • rabbitmq单向ssl认证配置与最佳实践(适用于各大云厂商)
  • docker-compose Install MinerU 0.3 GPU模式
  • 大语言模型概念科普
  • Storm实时流式计算系统(全解)——中
  • Mixture of Experts与Meta Learning深度学习中的两大变革性技术
  • Android 图片压缩详解
  • 神经网络参数量计算
  • sql调优:优化响应时间(优化sql) ; 优化吞吐量
  • HumanPro逼真角色皮肤面部动画Blender插件V1.1版
  • 使用mermaid查看cursor程序生成的流程图
  • 大数据学习(51)-MySQL数据库学习
  • 影刀RPA + AI大语言模型:打造智能自动化流程的超级引擎
  • Java数据类型详解
  • C++ 的编译和链接
  • Nacos + Dubbo3 实现微服务的Rpc调用
  • 【C++奇迹之旅】:字符串转换成数字将数字转换成字符串大全
  • Express MVC
  • Spring基础05
  • git 鼓励频繁提交commit early, commit often,用好分支,多用分支
  • 【SpringBoot+Vue】博客项目开发二:用户登录注册模块
  • 乡村研学旅行小程序(论文源码调试讲解)
  • 行为型模式 - 观察者模式 (Publish/Subscribe)
  • 【华三】从零开始掌握SR技术:原理、架构与应用全解析
  • golang介绍,特点,项目结构,基本变量类型与声明介绍(数组,切片,映射),控制流语句介绍(条件,循环,switch case)
  • 开发一个o2o(线上到线下)商城需要具备以下条件