SpringBoot项目访问任意接口出现401错误的解决方案

当我们使用SpringBoot项目访问任意接口时出现401错误,可能是因为项目的权限配置问题导致的。下面是解决它的完整攻略:

1.检查接口权限

首先我们需要检查接口权限,确定是否已经在项目中配置了相应的权限。我们可以通过查看Spring Security配置文件(一般为SecurityConfig.java)的代码或者在SpringBoot Admin管理后台中查看项目的接口权限配置。

如果确实存在接口权限,我们需要检查用户是否拥有该权限。可以在SecurityConfig.java文件中找到所有对应权限的用户,并检查他们的信息是否正确。

另外,如果我们已经确定了接口并检查了用户权限,还是无法访问接口,可能是因为我们没有正确配置Spring Security,需要进行如下操作:

2.添加Spring Security配置

在项目中添加Spring Security配置文件SecurityConfig.java,包括安全配置、认证方式、权限配置等,示例代码如下:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;

    @Autowired
    private RestAuthorizationFailureHandler restAccessDeniedHandler;

    @Autowired
    private RestLogoutSuccessHandler restLogoutSuccessHandler;

    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/api/**").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .accessDeniedHandler(restAccessDeniedHandler)
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .successHandler(restAuthenticationSuccessHandler)
                .failureHandler(restAuthenticationFailureHandler)
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(restLogoutSuccessHandler)
                .permitAll()
                .and()
                .headers()
                .frameOptions().disable()
                .and()
                .addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

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

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        config.setAllowCredentials(true);
        config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
        return new RestfulAccessDeniedHandler();
    }

    @Bean
    public RestLogoutSuccessHandler restLogoutSuccessHandler() {
        return new RestLogoutSuccessHandler();
    }

    @Bean
    public RestAuthenticationSuccessHandler restAuthenticationSuccessHandler() {
        return new RestAuthenticationSuccessHandler();
    }

    @Bean
    public RestAuthenticationFailureHandler restAuthenticationFailureHandler() {
        return new RestAuthenticationFailureHandler();
    }

    @Bean
    public RestAuthorizationFailureHandler restAuthorizationFailureHandler() {
        return new RestAuthorizationFailureHandler();
    }

    @Bean
    public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
        return new RestAuthenticationEntryPoint();
    }

    @Bean
    public RestAuthorizationEntryPoint restAuthorizationEntryPoint() {
        return new RestAuthorizationEntryPoint();
    }

    @Bean
    public RestAccessDeniedHandler restAccessDeniedHandler() {
        return new RestAccessDeniedHandler();
    }

    @Bean
    public CustomUserDetailsService userDetailsService() {
        return new CustomUserDetailsService();
    }

}

3.添加用户

在数据库中添加用户,可通过Mybatis等持久化框架或者使用Spring Security提供的内存方式进行添加。

在授权中,用户可以拥有多个角色,可以使用以下函数向数据库中添加具有user和admin角色的用户:

INSERT INTO `user` (`id`, `username`, `password`, `nickname`, `gender`, `status`, `phone`, `email`, `birthday`, `address`, `avatar`, `remark`, `create_time`, `update_time`) VALUES (1, 'user', '$2a$10$LcwB/9Mt4ymfY/XrIufkjuAaLCVtuWs0aunsKsrMZSHw/LsZEhF9u', '正常用户', 'male', 'enable', '13988888888', 'test@qq.com', NULL, '北京市', NULL, NULL, '2020-12-09 11:57:40', '2020-12-09 11:57:40');
INSERT INTO `user_role` (`id`, `user_id`, `role_id`) VALUES (5, 1, 1);

INSERT INTO `user` (`id`, `username`, `password`, `nickname`, `gender`, `status`, `phone`, `email`, `birthday`, `address`, `avatar`, `remark`, `create_time`, `update_time`) VALUES (2, 'admin', '$2a$10$hSjVNKNnEn6WrW5Vr5hdpuN9fCJaZQJvzN5G2Jlg1aRO4EvjM1M6G', '管理员', 'male', 'enable', '17888888888', 'test@qq.com', NULL, '北京市', NULL, NULL, '2020-12-09 11:57:40', '2020-12-09 11:57:40');
INSERT INTO `user_role` (`id`, `user_id`, `role_id`) VALUES (6, 2, 2);

总结

通过以上步骤我们可以解决SpringBoot项目访问任意接口出现401错误的问题,分别为检查接口权限和添加Spring Security配置两大部分,核心是在SecurityConfig.java中实现了认证和授权,以及用户添加等相关内容。

另外,对于程序员而言,熟练掌握Spring Security框架,并在其中添加自定义的授权方式和安全配置可以有效提升应用程序的安全性。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot项目访问任意接口出现401错误的解决方案 - Python技术站

(0)
上一篇 2023年5月20日
下一篇 2023年5月20日

相关文章

  • Java日常练习题,每天进步一点点(60)

    首先,这是一篇Java日常练习题的攻略,包含了60个练习题目,帮助学习Java的人每天进步一点点。本文分为如下部分: 攻略简介 练习题目列表 示例说明 攻略简介 这篇攻略共包含了60个Java练习题目,力求帮助Java学习者过好编程的每一天。每个练习题目的描述都很清晰明了,题目中包含了需要完成的任务,做完题目后会有详细的答案和代码解释。通过这些练习题目的完成…

    Java 2023年5月23日
    00
  • Java使用MyBatis框架分页的5种方式

    下面就来详细讲解“Java使用MyBatis框架分页的5种方式”的完整攻略。 1、MyBatis的分页插件 MyBatis作为一款优秀的ORM框架,提供了一个非常方便的分页插件——PageHelper,只需在查询前进行设置即可。以下是使用PageHelper的示例: int pageNum = 1; //当前页码 int pageSize = 10; //每…

    Java 2023年5月20日
    00
  • Mybatis实现动态SQL编写详细代码示例

    针对”Mybatis实现动态SQL编写详细代码示例”这个话题,我为您提供以下完整攻略。 前言 在Mybatis中,动态SQL是非常强大和常用的功能。通过动态SQL可以根据输入参数的不同来生成不同的SQL语句,从而实现更加灵活的数据查询和操作。Mybatis提供了多种动态SQL的方式,如if/where/set/foreach等。本文将详细介绍Mybatis实…

    Java 2023年5月19日
    00
  • 在JSP中如何实现MD5加密的方法

    在JSP中实现MD5加密有多种方法,其中最为常见的是使用Java的MessageDigest类。下面是实现MD5加密的完整攻略。 步骤一:引入MessageDigest类 Java的MessageDigest类是用于生成消息摘要的工具类。为了在JSP中使用它,我们需要在JSP页面中导入java.security.MessageDigest类。 <%@ …

    Java 2023年6月15日
    00
  • Java实现中国象棋游戏

    Java实现中国象棋游戏攻略 1. 概述 本攻略主要介绍如何使用Java语言实现中国象棋游戏。将分为以下几个部分: 实现界面和交互 实现棋局数据和规则 实现人机交互功能 2. 实现界面和交互 实现游戏界面和交互模块可以使用Swing/AWT的图形界面库,实现如下功能: 显示当前棋局 实现棋子移动交互 实现游戏结束时弹出对话框 下面是一个简单的Swing界面实…

    Java 2023年5月19日
    00
  • Spring操作JdbcTemplate数据库的方法学习

    Spring操作JdbcTemplate数据库的方法学习 什么是JdbcTemplate? JdbcTemplate是Spring框架中的一个类,它对JDBC(Java Database Connectivity) API进行了封装,使得我们在操作数据库时可以更加简单和高效。它这么做的目的是为了提高开发效率和灵活性。 JdbcTemplate提供了许多简便的…

    Java 2023年5月20日
    00
  • 超详细讲解SpringBoot参数校验实例

    标题:超详细讲解SpringBoot参数校验实例 简介 SpringBoot是一款非常流行的开源Java框架,它提供了方便的依赖注入、自动配置和可扩展性。在使用SpringBoot开发Web应用时,我们不可避免地需要对用户传入的参数进行校验,本文将详细讲解如何使用SpringBoot进行参数校验。 步骤 1. 添加依赖 要使用SpringBoot参数校验,我…

    Java 2023年5月20日
    00
  • java开发 线上问题排查命令详解

    Java开发 线上问题排查命令详解 在Java应用线上运行过程中可能会遇到各种问题,例如应用启动失败、性能瓶颈等等。本文将介绍一些常用的Java开发线上问题排查命令,帮助开发人员更快速、准确地定位问题。 查看应用状态 jps jps命令用于列出Java应用进程的PID(进程ID)和名称,可用于检查应用是否正常启动并在运行。 jps 输出示例: 1234 Ap…

    Java 2023年5月27日
    00
合作推广
合作推广
分享本页
返回顶部