Я использую Spring Security с пользовательским поставщиком аутентификации, используя базовую аутентификацию.
Когда я пытаюсь выполнить вызов API GET бэкенда через почтальона, он работает нормально, только когда я вношу изменения в имя пользователя
Вот формулировка проблемы: всякий раз, когда я изменяю имя пользователя, работает только пользовательский провайдер проверки подлинности. как только я добавил правильное имя пользователя и пароль, он работает, но после этого, когда я вношу какие-либо изменения в пароль (указывая неправильный пароль), всегда отображается 200 успешных ответов. Если я вношу изменения в имя пользователя (указываю неправильное имя пользователя), то происходит только вызов пользовательского поставщика аутентификатора и получение ответа 401.
Код Java Spring
@Configuration
@EnableWebSecurity
@ComponentScan("com.authentication.service")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private AuthService authProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception { http
.httpBasic().and().logout().clearAuthentication(true).and() .authorizeRequests()
.antMatchers("/index.html", "/", "/home", "/login", "/assets/**").permitAll()
.anyRequest().authenticated() .and() .csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }
}
@Service
public class AuthService implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication)
throws org.springframework.security.core.AuthenticationException {
String userName = (String) authentication.getPrincipal();
String userPassword = authentication.getCredentials().toString();
if(authenticateUser(userName, userPassword)) {
return new UsernamePasswordAuthenticationToken(userName, userPassword, new ArrayList<>());
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public Boolean authenticateUser(String userName, String userPassword) {
// Using some third party service
// return true if user is authenticated else false
}
}
if(authenticateUser(userName, userPassword)) {
- Вы имеете в видуif(!authenticateUser(userName, userPassword)) {
(обратите внимание на!
)?нет, это не так. Если пользователь аутентифицирован, то только он войдет внутрь, если условие
Возможно, вы захотите создать подкласс
AuthenticationException
вместо возвратаnull
.