首页 > 基础资料 博客日记

若依 3.8.3升级SpringBoot 3.1.2 + JDK 17

2024-09-13 10:00:07基础资料围观110

本篇文章分享若依 3.8.3升级SpringBoot 3.1.2 + JDK 17,对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识

前言:目前jdk已经发行到23了,长期支持版的jdk17也变得越来越广泛,所以就在就想着给自己的博客也升个级,自己的博客系统是用若依3.8.3开发的,所以以下代码仅针对若依3.8.3修改,仅供参考。

 1.将jdk和SpringBoot的依赖版本换掉

原来的配置:

 <properties>
        <springBoot.version>2.5.14</springBoot.version>
        <ruoyi.version>3.8.3</ruoyi.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
        <druid.version>1.2.11</druid.version>
        <bitwalker.version>1.21</bitwalker.version>
        <swagger.version>3.0.0</swagger.version>
        <kaptcha.version>2.3.2</kaptcha.version>
        <mybatis-spring-boot.version>2.2.2</mybatis-spring-boot.version>
        <pagehelper.boot.version>1.4.3</pagehelper.boot.version>
        <fastjson.version>2.0.11</fastjson.version>
        <oshi.version>6.2.2</oshi.version>
        <commons.io.version>2.11.0</commons.io.version>
        <commons.fileupload.version>1.4</commons.fileupload.version>
        <commons.collections.version>3.2.2</commons.collections.version>
        <poi.version>4.1.2</poi.version>
        <velocity.version>2.3</velocity.version>
        <jwt.version>0.9.1</jwt.version>
</properties>

修改后的配置:

<properties>
        <springBoot.version>3.1.2</springBoot.version>
        <ruoyi.version>3.8.3</ruoyi.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>17</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
        <druid.version>1.2.16</druid.version>
        <bitwalker.version>1.21</bitwalker.version>
        <swagger.version>3.0.0</swagger.version>
        <kaptcha.version>2.3.2</kaptcha.version>
        <mybatis-spring-boot.version>3.0.3</mybatis-spring-boot.version>
        <pagehelper.boot.version>1.4.3</pagehelper.boot.version>
        <fastjson.version>2.0.11</fastjson.version>
        <oshi.version>6.2.2</oshi.version>
        <commons.io.version>2.11.0</commons.io.version>
        <commons.fileupload.version>1.4</commons.fileupload.version>
        <commons.collections.version>3.2.2</commons.collections.version>
        <poi.version>4.1.2</poi.version>
        <velocity.version>2.3</velocity.version>
        <jwt.version>0.9.1</jwt.version>
</properties>

2.更新依赖

如果开发工具使用的是IEDA,可以快速将Java EE替换为
Jakarta EE

3.重写SecurityConfig

下面到了最重要的环节,由于SrpingSecurity 6.1.2移除了WebSecurityConfigurerAdapter,导致原来的SecurityConfig无法使用,需要自己注册一个SecurityFilterChain 的Bean,其他大同小异,对于一些过期或者移除的方法,进行针对性的修改,由于新版传url必须指定是AntPathRequestMatcher()或者MvcRequestMatcher(),如果不指定,会出现以下报错

Caused by: java.lang.IllegalArgumentException: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).
	at org.springframework.util.Assert.isTrue(Assert.java:122)
	at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:204)
	at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:248)
	at com.ruoyi.framework.config.SecurityConfig.lambda$filterChain$4(SecurityConfig.java:97)
	... 37 common frames omitted

所以在又封装了一个方法来塞入AntPathRequestMatcher()。改造后的代码如下所示:


import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;


/**
 * spring security配置
 *
 * @author ruoyi
 */
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
@Configuration
public class SecurityConfig
{
    /**
     * 自定义用户认证逻辑
     */
    @Resource
    private UserDetailsService userDetailsService;

    /**
     * 认证失败处理类
     */
    @Resource
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 退出处理类
     */
    @Resource
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Resource
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * 跨域过滤器
     */
    @Resource
    private CorsFilter corsFilter;

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // CSRF禁用,因为不使用session
                .csrf(AbstractHttpConfigurer::disable)
                // 禁用HTTP响应标头
                .headers(conf -> conf.cacheControl(HeadersConfigurer.CacheControlConfig::disable))
                // 认证失败处理类
                .exceptionHandling(conf -> conf.authenticationEntryPoint(unauthorizedHandler))
                // 基于token,所以不需要session
                .sessionManagement(conf -> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 过滤请求
                .authorizeRequests(conf ->
                    // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                {
                    try {
                        conf.requestMatchers(toAntMatcher("/login","/register","/captchaImage")).anonymous()
//                        // 静态资源,可匿名访问
                        .requestMatchers(toAntMatcher(HttpMethod.GET, "/", "/*.html", "/*/*.html", "/*/*.css", "/*/*.js", "/profile/*")).permitAll()
                        .requestMatchers(toAntMatcher("/swagger-ui.html", "/swagger-resources/*", "/webjars/*", "/*/api-docs")).permitAll()
                        // 除上面外的所有请求全部需要鉴权认证
                        .anyRequest().authenticated()
                                .and().headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
        // 添加Logout filter
        httpSecurity.logout(conf -> conf.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler));
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);

        return httpSecurity.build();
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
//    @Bean
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}
    /**
     * 将原来的ulr字符串转为AntPathRequestMatcher
     * @param str url链接
     * @return AntPathRequestMatcher[]
     */
    private AntPathRequestMatcher[] toAntMatcher(String...str) {
        List<AntPathRequestMatcher> list = new ArrayList<>();
        for (String item : str) {
            list.add(AntPathRequestMatcher.antMatcher(item));
        }
        return list.toArray(new AntPathRequestMatcher[0]);
    }

    /**
     * 将原来的ulr字符串转为AntPathRequestMatcher
     * @param method
     * @param str url链接
     * @return AntPathRequestMatcher[]
     */
    private AntPathRequestMatcher[] toAntMatcher(HttpMethod method,String...str) {
        List<AntPathRequestMatcher> list = new ArrayList<>();
        for (String item : str) {
            list.add(AntPathRequestMatcher.antMatcher(method,item));
        }
        return list.toArray(new AntPathRequestMatcher[0]);
    }

代码放在了Gitee:blog-demo: 使用若依搭建的博客后台系统,还在努力完善中 ,如果对你有帮助,希望可以得到一颗鼓励的小星星


文章来源:https://blog.csdn.net/liuzhexian/article/details/137905473
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云