1、springSecurity升级6.0后登陆访问不存在的接口显示401未授权。没升级之前返回404是正常的。
这是secutity配置,有人知道怎么解决吗。
/**
* spring security配置
*
* @author ruoyi
*/
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
/**
* 自定义用户认证逻辑
*/
@Autowired
private UserDetailsService userDetailsService;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
/**
* 退出处理类
*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
/**
* 跨域过滤器
*/
@Autowired
private CorsFilter corsFilter;
/**
* 允许匿名访问的地址
*/
@Autowired
private PermitAllUrlProperties permitAllUrl;
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
// 注解标记允许匿名访问的url
AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry registry = httpSecurity.authorizeHttpRequests();
permitAllUrl.getUrls().forEach(url -> registry.requestMatchers(url).permitAll());
httpSecurity
// CSRF禁用,因为不使用session
// .csrf().csrfTokenRepository(this.getCsrfTokenRepository()).and()
.csrf().disable()
// 禁用HTTP响应标头
.headers().cacheControl().disable().and()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
// .authorizeRequests()
.authorizeHttpRequests()
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
.requestMatchers("/login", "/register", "/captchaImage", "/guananshun/*").permitAll()
// 静态资源,可匿名访问
.requestMatchers(HttpMethod.GET, "/", "/*.html", "/*/*.html", "/*/*.css", "/*/*.js", "/profile/*").permitAll()
.requestMatchers("/swagger-ui.html", "/swagger-resources/*", "/webjars/*", "/*/api-docs", "/druid/*").permitAll()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
// 添加Logout filter
httpSecurity.logout().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();
}
/**
* 身份认证接口
*/
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
已登陆还是去到这里。
/**
* 认证失败处理类 返回未授权
*
* @author ruoyi
*/
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
@Serial
private static final long serialVersionUID = -8970718410437077606L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException {
int code = HttpStatus.UNAUTHORIZED;
String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
}
}
感觉401返回也没问题,可以根据提示做出调整
问题答案由GPT-4Plus模型(语音)与博主程序员之梦@共同编写:
根据您提供的Spring Security配置信息,出现401未授权的原因可能是:
在Spring Security 5.X版本中,默认情况下认证失败会返回302重定向到登录页面。从6.0版本开始,改为返回401未授权状态码。
解决方法是在SecurityConfig的configure方法中禁用exceptionHandling(),例如:
java
httpSecurity
// 禁用exceptionHandling
// .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
...
解决方法是在commence方法中返回其他状态码,例如:
例如:
java
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
throws IOException {
response.sendRedirect("/login"); //302重定向到登录页
}
解决方法是检查SecurityConfig中的URL匹配规则,确保所有的匿名访问路径都添加了.permitAll()。
这种情况需要查看授权相关的代码,确定接口是否应该需要认证,以及认证失败的原因。
总之,出现401未授权响应的原因主要在Spring Security的配置上
在 Spring Security 6.0 中,默认情况下,对于不存在的 URL,会返回 401 未授权错误,而不是之前的 404 错误。这是因为 Spring Security 6.0 中添加了一个新特性,用于更好地处理权限校验。如果您想要恢复之前的行为,即对不存在的 URL 返回 404 错误,可以将 httpSecurity.httpBasic().disable(); 添加到 SecurityConfig 类的 configure(HttpSecurity httpSecurity) 方法中,如下所示:
@Bean
public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// ...
.httpBasic().disable() // 禁用 httpBasic 认证
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// ...
}
这样配置后,如果您访问一个不存在的 URL,就会返回 404 错误,而不是 401 错误了。同时,如果您使用了其他的认证方式,例如 JWT,也可以将相应的认证方式禁用,以达到恢复之前行为的目的。