bounty将在5天后过期。回答此问题可获得+50声望奖励。S. Cannon希望引起更多人对此问题的关注:这阻碍了我的申请工作,而且我在网上没有找到任何有用的信息。我真的需要有人来审查这个问题。
我安装了一个springboot应用程序,并尝试设置基本的用户登录。根据我的研究,拥有@Configuration和@EnableWebSecurity标记足以提醒Spring您的类覆盖了它的配置(使用@Bean方法返回SecurityFilterChain)。但是,当运行应用程序时,它仍然使用DefaultSecurityFilterChain,并希望我使用“user”和自动生成的密码登录,该密码被转储到控制台中。我不确定在让Spring识别我的SecurityConfig方面我错过了什么。但是,在运行时我没有收到任何System.out/log.info消息(除了主方法的Hello World),并且它不能识别来自UserDetailsService的用户。
安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private ArchlandsUserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
System.out.println("In securityFilterChain");
http
.csrf().disable()
.authorizeHttpRequests((requests) -> requests
.requestMatchers("archlands/api/**").hasRole("USER")
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/login").permitAll()
)
.logout((logout) -> logout.permitAll())
.authenticationProvider(authenticationProvider());
return http.build();
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
return authenticationProvider;
}
}
用户详细信息服务
@RequiredArgsConstructor
@Service
@Slf4j
public class ArchlandsUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) {
String cleanedUsername = ArchlandsInputSanitizer.clean(username);
log.info("User " + cleanedUsername + " is attempting to access the Archlands.");
System.out.println("User " + cleanedUsername + " is attempting to access the Archlands.");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
UserDto user = userService.findById(cleanedUsername);
if (user == null) {
log.error("No user exists with user id: " + cleanedUsername);
throw new UsernameNotFoundException("No user exists with user id: " + cleanedUsername);
}
if (user.getStatus().equals("Active")) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
}
for (int i = 0; i < user.getRoles().length; i++) {
if (user.getRoles()[i].equals(Role.DM_ROLE)) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_DM"));
}
}
log.info("User: " + cleanedUsername + " has authorities: " + grantedAuthorities.toString());
return new User(user.getId(), user.getPassword(), grantedAuthorities);
}
}
控制台输出x1c 0d1x
1条答案
按热度按时间fnvucqvd1#
您可以在@Configuration注解之上的SecurityConfig类中添加@Order(SecurityProperties.BASIC_AUTH_ORDER)注解。这样,您的安全配置将变得比默认配置更高的优先级。另外,您可以考虑在ArchlandsUserDetailsService中添加@Bean注解,以确保它已正确注册。