Поставщик пользовательской аутентификации Spring Boot с конфигурацией Java не работаетJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Поставщик пользовательской аутентификации Spring Boot с конфигурацией Java не работает

Сообщение Anonymous »

Я пытаюсь настроить веб-приложение на основе REST, в котором интерфейс использует Reactjs, а серверная часть использует Spring Boot. Я также пытаюсь настроить собственный поставщик аутентификации, и именно здесь начинаются мои проблемы. При попытке протестировать вызов API входа в систему CustomAuthenticationProvider никогда не вызывается, а вместо этого используется DaoAuthenticationProvider по умолчанию. Это приводит к тому, что при входе в систему появляется сообщение «Неверные учетные данные».

Я загрузил небольшой пример приложения на github: Spring-boot-auth-demo

Чтобы протестировать API входа в систему, я использую следующий завиток:

Код: Выделить всё

curl -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"admin"}' http://localhost:8080/api/users/login
CustomAuthenticationProvider выполняет простую проверку имени пользователя и пароля и возвращает объект UsernamePasswordAuthenicationToken.

Код: Выделить всё

package no.bluebit.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

private static final Logger logger =     LoggerFactory.getLogger(CustomAuthenticationProvider.class);

public CustomAuthenticationProvider() {
logger.info("*** CustomAuthenticationProvider created");
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

if(authentication.getName().equals("admin")  && authentication.getCredentials().equals("admin")) {
List grantedAuths = new ArrayList();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuths);
} else {
return null;
}

}

@Override
public boolean supports(Class authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}

}
CustomAuthenticationProvider подключается с использованием класса SecurityConfiguration. Просматривая код, я вижу, что CustomAuthenicationProvider отсутствует в списке провайдеров, используемых для аутентификации входящего запроса.

Код: Выделить всё

package no.bluebit.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(this.customAuthenticationProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/users/login").permitAll()    // Permit access for all to login REST service
.antMatchers("/").permitAll()                   // Neccessary to permit access to default document
.anyRequest().authenticated().and()                 // All other requests require authentication
.httpBasic().and()
.logout().and()
.csrf().disable();
}
}
Почему это не работает?

Подробнее здесь: https://stackoverflow.com/questions/367 ... ot-working
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»