首页 > 其他分享 >P.19-token认证过滤器代码实现、P.20-配置认证过滤器、P.21-退出登录

P.19-token认证过滤器代码实现、P.20-配置认证过滤器、P.21-退出登录

时间:2023-04-26 09:45:30浏览次数:31  
标签:P.20 userid 认证 token logout loginUser 过滤器 public

P.19-token认证过滤器代码实现

  自定义一个过滤器,这个过滤器会去获取请求头中的token,对token进行解析取出其中的userid。

  使用userid去redis中获取对应的LoginUser对象。

  然后封装Authentication对象存入SecurityContextHolder

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}

P.20-配置认证过滤器

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //创建BCryptPasswordEncoder注入容器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

P.21-退出登录

在LoginController下创建

 @PostMapping("/user/logout")//推出
    public ResponseResult  logout(){
        return loginServcie.logout();
    }

 并实现logout方法

ResponseResult logout();//推出

 在LoginServcieImpl中进行实现该方法

@Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        //删除Redis中的值
        redisCache.deleteObject("login" + userid);
        return new ResponseResult(200,"注销成功");
    }

 

标签:P.20,userid,认证,token,logout,loginUser,过滤器,public
From: https://www.cnblogs.com/agzq/p/17354707.html

相关文章

  • JWT 实现登录认证 + Token 自动续期方案 转载
    过去这段时间主要负责了项目中的用户管理模块,用户管理模块会涉及到加密及认证流程,加密已经在前面的文章中介绍了。今天就来讲讲认证功能的技术选型及实现。技术上没啥难度当然也没啥挑战,但是对一个原先没写过认证功能的菜鸡甜来说也是一种锻炼吧。技术选型要实现认证功能,很容易......
  • SpringBoot 使用 Sa-Token 完成权限认证
    一、设计思路所谓权限认证,核心逻辑就是判断一个账号是否拥有指定权限:有,就让你通过。没有?那么禁止访问!深入到底层数据中,就是每个账号都会拥有一个权限码集合,框架来校验这个集合中是否包含指定的权限码。例如:当前账号拥有权限码集合["user-add","user-delete","user-get"]......
  • token认证过滤器代码实现与配置认证过滤器
    token认证过滤器代码实现认证过滤器​我们需要自定义一个过滤器,这个过滤器会去获取请求头中的token,对token进行解析取出其中的userid。​使用userid去redis中获取对应的LoginUser对象。​然后封装Authentication对象存入SecurityContextHolder......
  • Adobe国际认证证书有必要考吗?
    Adobe公司作为全球领先的数字媒体和数字营销软件解决方案提供商之一。其产品包括Photoshop、Illustrator、InDesign、Dreamweaver等软件被广泛应用于设计、出版、网站开发、视频制作等领域。为了帮助用户更好地使用这些软件,Adobe推出了Adobe国际认证证书,以证明用户在相关领域具备专......
  • 蓝牙认证
    蓝牙认证1. 蓝牙SIG认证:蓝牙SIG认证是蓝牙技术联盟(Bluetooth SIG)进行的认证,用于验证产品的互操作性、符合性和稳定性等,通常是指蓝牙设备的基本认证。2. FCC认证:美国联邦通信委员会(FCC)对所有发射的电子产品进行认证。蓝牙设备也需要通过FCC认证,以确保其符合美国法规并不会对其他......
  • Servlet添加自定义的过滤器没有效果?
    在学习HttpServlet的时候有个自定义过滤器的定义类,我们想让特定url走过滤器。publicclassMyFilterimplementsFilter{privateFilterConfigconfig;publicvoidinit(FilterConfigconfig)throwsServletException{this.config=config;}publi......
  • SpringSecurity从入门到精通:认证配置详解&权限系统的作用
    认证配置详解Configpackagecom.sangeng.config;importcom.sangeng.filter.JwtAuthenticationTokenFilter;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.ann......
  • 每日一练 | 华为认证真题练习Day31
    1.如图所示,网络管理员在SWA与SWB上创建VLAN2,并将两台交换机上连接主机的端口配置为Access端口,划入VLAN2。将SA的G0/0/1与SWB的G0/0/2配置为Trunk端口,允许所有VLAN通过。则要实现两台主机间能够正常通信,还需要?A.在SWC上创建VLAN2即可B.配置SWC上的G0/0/1为trunk端口且允许VLAN2......
  • P.-7如何查看具体的过滤器、P.-8认证流程图讲解
    P.-7如何查看具体的过滤器​我们可以通过Debug查看当前系统中SpringSecurity过滤器链中有哪些过滤器及它们的顺序。P.-8认证流程图讲解(了解即可)概念速查:Authentication接口:它的实现类,表示当前访问系统的用户,封装了用户相关信息。Authenticat......
  • drf-认证、权限、频率、过滤、排序、分页
    1.认证组件1.1局部认证1.首先写两个接口,一个查询单个一个查询所有,我们利用视图扩展类和视图子类写在一个视图类上:views.py:fromrest_framework.viewsetsimportViewSetMixinfromrest_framework.genericsimportListAPIViewfromrest_framework.mixinsimportRetrieve......