首页 > 其他分享 >token认证过滤器代码实现与配置认证过滤器

token认证过滤器代码实现与配置认证过滤器

时间:2023-04-25 14:58:15浏览次数:31  
标签:springframework 认证 token org 过滤器 import security

token认证过滤器代码实现

  认证过滤器

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

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

​     然后封装Authentication对象存入SecurityContextHolder

package com.example.qinghuatokendemo.filter;

import com.example.qinghuatokendemo.Domain.LoginUser;
import com.example.qinghuatokendemo.Utils.JwtUtil;
import com.example.qinghuatokendemo.Utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, 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);
    }
}

配置认证过滤器

 

package com.example.qinghuatokendemo.Config;

import com.example.qinghuatokendemo.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @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();

        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

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

 

 

 

 

 

 

 

 

 

 

 访问localhost:8080/hello

 

标签:springframework,认证,token,org,过滤器,import,security
From: https://www.cnblogs.com/x3449/p/17352195.html

相关文章

  • 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......
  • 大语言模型中的token解释
    在大型语言模型中,"token"通常指的是一个离散的文本单元,它可以是单词、标点符号、数字或其他语言元素,这些元素被用作训练和生成文本的基本单位。在NLP中,通常使用tokenization技术将文本分割成token序列。具体来说,tokenization是将一个连续的文本字符串分割成一个个离散的单词......
  • drf-认证、权限、频率、过滤、排序、分页
    1.认证组件1.1局部认证1.首先写两个接口,一个查询单个一个查询所有,我们利用视图扩展类和视图子类写在一个视图类上:views.py:fromrest_framework.viewsetsimportViewSetMixinfromrest_framework.genericsimportListAPIViewfromrest_framework.mixinsimportRetrieve......
  • 什么是LDAP身份认证?
    轻量级目录访问协议(LDAP)是专为目录服务开发的核心身份认证协议之一。LDAP历来被用作信息数据库,主要存储以下信息:●用户● 关于这些用户的属性● 组成员特权● ……但LDAP认证是什么,它是如何工作的?本文将回答这些问题,并阐述NingDS身份目录云平台是如何将LDAP身份认证作为......
  • gitlab 开发人员更换手机后MFA认证无法登录
    目录gitlab开发人员更换手机后MFA认证无法登录解决方法gitlab开发人员更换手机后MFA认证无法登录开发人员用mfa二次认证登录gitlab,有开发更换手机后,发现登录gitlab时必须输入mfa二次认证解决方法需要找运维管理人员,登录mfa取消二次认证,登录后自己再开启二次认证运维人员以......