Spring Security自定义认证登录请求返回404求助
解决Spring Security内置登录API 404问题
你的问题核心是没有启用Spring Security的登录处理机制,默认情况下Spring不会自动注册/login的POST处理端点,需要显式配置对应的认证过滤器(比如表单登录或HTTP Basic)。以下是具体解决方案:
1. 配置表单登录处理端点
修改SecurityFilterChain配置,添加formLogin()并指定登录处理路径为/login,让Spring Security自动处理该路径的POST请求:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeHttpRequests(auth -> auth .requestMatchers("/login").permitAll() .anyRequest().authenticated()) // 启用表单登录,指定POST登录请求的处理路径 .formLogin(form -> form .loginProcessingUrl("/login") .permitAll()); return http.build(); }
loginProcessingUrl("/login")是关键:它告诉Spring Security将该路径作为登录请求入口,自动处理用户名密码的校验逻辑,无需手动编写Controller。
2. 修正AuthenticationProvider的supports方法
你的VeireAuthenticationProvider的supports方法返回true过于宽泛,可能导致Spring Security将其用于所有类型的认证请求,建议精准匹配UsernamePasswordAuthenticationToken:
@Override public boolean supports(Class<?> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); }
3. 完善CustomUserDetails的权限配置
当前CustomUserDetails未设置权限(authorities),登录成功后可能导致后续接口访问被拒绝,需补充权限设置:
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AccountResponse accountResponse = this.userService.getAccount(username); CustomUserDetails userDetails = new CustomUserDetails(); userDetails.setUsername(accountResponse.getAccountId()); // 添加默认权限,或从业务逻辑中获取实际权限 userDetails.setAuthorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); return userDetails; }
完成以上配置后,向http://localhost:8080/context-path/login发送携带username和password参数的POST请求(表单格式更贴合默认配置),即可正常触发Spring Security的认证流程。
内容的提问来源于stack exchange,提问作者higz555
相关产品推荐
相关产品推荐

