老唐手把手教你配置security,并增加JWT校验(copy就用)。

本文手把手教你如何在Spring Boot应用中配置Security并结合JWT进行权限校验。从导入Security库开始,详细讲解配置文件设置,接着介绍JWT的引入和配置,包括无权限访问类、认证失败处理类的定义,以及SpringContextHolder的使用。最后,提供JWT工具类JWTHelper和JwtTokenUtils的实现,并展示简单实践。
摘要由CSDN通过智能技术生成

1.首先配置security

1.1导入security的jar包

  <!--security 框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

1.2配置security配置文件(直接上代码)


/**
 * Spring Security配置类
 *
 * @author zhuhuix
 * @date 2020-03-25
 */

/**
 * SpringSecurity的关键配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   

    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final JwtTokenUtils jwtTokenUtils;
    @Autowired
    private YxsPubOrderMaintenanceService yxsPubOrderMaintenanceService;

    public WebSecurityConfig(JwtAccessDeniedHandler jwtAccessDeniedHandler, JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtTokenUtils jwtTokenUtils,YxsPubOrderMaintenanceService yxsPubOrderMaintenanceService) {
   

        this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
        this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
        this.jwtTokenUtils = jwtTokenUtils;
        this. yxsPubOrderMaintenanceService=yxsPubOrderMaintenanceService;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
   

        httpSecurity
                // 禁用 CSRF
                .csrf().disable()

                // 授权异常
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)

                // 防止iframe 造成跨域
                .and()
                .headers()
                .frameOptions()
                .disable()

                // 不创建会话
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                .and()
                .authorizeRequests()

                // 放行静态资源
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/**/*.jpeg",
                        "/**/*.png",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/webSocket/**",
                        "/yxs/**"
                ).permitAll()

                // 放行swagger
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/*/api-docs").permitAll()
                // 放行文件访问
                .antMatchers("/file/**").permitAll()
                //对外 API
                .antMatchers("/pub/**").permitAll()
                .antMatchers("/gft/**").permitAll()

                // 放行druid
                .antMatchers("/druid/**").permitAll()

                // 放行OPTIONS请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                //允许匿名及登录用户访问
                .antMatchers("/api/auth/**", "/error/**").permitAll()
                //手机登录放行
                .antMatchers("/**").permitAll()
                // 所有请求都需要认证
                .anyRequest().authenticated();

        // 禁用缓存
        httpSecurity.headers().cacheControl();

        // 添加JWT filter
        httpSecurity
                .apply(new TokenConfigurer(jwtTokenUtils));

    }


    public class TokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
   

        private final JwtTokenUtils jwtTokenUtils;

        public TokenConfigurer(JwtTokenUtils jwtTokenUtils) {
   

            this.jwtTokenUtils = jwtTokenUtils;
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
   
            JwtAuthenticationTokenFilter customFilter = new JwtAuthenticationTokenFilter(jwtTokenUtils,yxsPubOrderMaintenanceService);
            http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
        }

    }

}

2.JWT配置

2.1导入JWT包

        <!-- jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值