当我们使用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技术站