Spring Security 为什么我在尝试身份验证时收到Forbidden 403?

q0qdq0h2  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(122)

我正在尝试验证用户身份,但我得到了禁止的响应。

CustomUserDetailService.java

public class CustomUserDetails实现UserDetails {

private String id;
private String username;
private String password;
private List<GrantedAuthority> authorities;

public CustomUserDetails(User user) {
    this.id = user.getId();
    this.username = user.getUsername();
    this.password = user.getPassword();
    this.authorities = Arrays.stream(user.getRole().split(","))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
}

@Override
public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return username;
}

@Override
public boolean isAccountNonExpired() {
    return false;
}

@Override
public boolean isAccountNonLocked() {
    return false;
}

@Override
public boolean isCredentialsNonExpired() {
    return false;
}

@Override
public boolean isEnabled() {
    return false;
}

字符串
}

UserDetailService.java

@Service
@RequiredArgsConstructor
@Log4j2
public class UserDetailsServiceImpl implements UserDetailsService {

    private final AuthenticationDao authenticationDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = Optional.ofNullable(authenticationDao.getUserByUsername(username));

        if(user.isPresent()) {
            CustomUserDetails customUserDetails =  new CustomUserDetails(user.get());
            return customUserDetails;
        }else {
            throw new BadCredentialsException(Util.CANNOT_FIND_USER_BY_USERNAME);
        }
    }
}

使用用户名查询用户

@Override
    public User getUserByUsername(String username) {
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM user WHERE username = ?",
                    new Object[]{username}, new BeanPropertyRowMapper<>(User.class));
        } catch (EmptyResultDataAccessException exception) {
            log.error("Cannot find user by username: {}", username);
            return null;
        }
    }

SecurityConfig.java

package com.treeleaf.auth.config;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
@Log4j2
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        log.info("Security Filter chain....");
        http.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(configurationSource()));
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        return http.build();
    }

    @Bean
    public CorsConfigurationSource configurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(false);
        configuration.setAllowedHeaders(List.of("*"));
        configuration.addExposedHeader("Content-Disposition");
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return new ProviderManager(authenticationProvider);
    }

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

服务认证

@Override
    public AuthResponse authenticate(AuthRequest authRequest) {
        System.out.println(authRequest.toString());
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
        );
        String token = generateToken(authentication);
        return new AuthResponse(token);
    }


我正在尝试验证用户身份。请求没有问题,它击中了服务层,但问题出现在尝试进行身份验证时。谁来帮帮我!

9nvpjoqh

9nvpjoqh1#

我解决了这个问题。问题出在www.example.com上CustomUserDetailService.java,我为isNonExpired、isNonLocked和isEnabled返回了false。

相关问题