Spring Не определен bean-компонент типа AuthenticationManagerBuilderJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Spring Не определен bean-компонент типа AuthenticationManagerBuilder

Сообщение Anonymous »

Недавно в моем Spring REST API я столкнулся со странным исключением. Spring сообщает мне, что он не находит ни одного bean-компонента типа org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder

Это не так не появлялся каждый раз, и первое исправление заключалось в том, чтобы перезапустить IntelliJ IDEA на несколько минут, и тогда все заработало бы нормально.

Но теперь из-за этого он не развертывается на моем удаленном сервере Tomcat, и я не могу понять, что с ним делать.

Сообщение об ошибке:

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

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method authenticationManager in eu.side.thot.Application required a bean of type 'org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder' in your configuration.

Process finished with exit code 1
Вот моя конфигурация

Application.java

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

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}

public static void main(String[] args){
SpringApplication.run(Application.class, args);
}

@Autowired
private CustomUserDetailsService userDetailsService;

/**
* Set AuthenticationManager his UserDetailsService and PasswordEncoder so he can authenticate an user with a given username/password
* */
@Autowired
public void authenticationManager(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(userDetailsService).passwordEncoder(new MD5PasswordEncoder());
}
}
И файл AuthorizationServerConfig.java

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

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private Logger log = Logger.getLogger(AuthorizationServerConfig.class);

private static final int FIVE_HOURS_IN_S = 5*3600;
private static final int MONTH_IN_S = 31*24*3600;

private final AuthenticationManager authenticationManager;

@Autowired
public AuthorizationServerConfig(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

@Override
public void configure(AuthorizationServerSecurityConfigurer serverSecurityConfigurer){
serverSecurityConfigurer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
clients.inMemory().withClient("{client}")
.authorizedGrantTypes("client-credentials", "password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT")
.scopes("read", "write", "trust")
.resourceIds("oauth2resource")
.accessTokenValiditySeconds(FIVE_HOURS_IN_S)
.secret("{secret}").refreshTokenValiditySeconds(MONTH_IN_S);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints){
endpoints.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.exceptionTranslator(loggingExceptionTranslator());
}

@Bean
public WebResponseExceptionTranslator loggingExceptionTranslator() {
return new DefaultWebResponseExceptionTranslator() {
@Override
public ResponseEntity translate(Exception e) throws Exception {
// This is the line that prints the stack trace to the log.  You can customise this to format the trace etc if you like
e.printStackTrace();

// Carry on handling the exception
ResponseEntity responseEntity = super.translate(e);
HttpHeaders headers = new HttpHeaders();
headers.setAll(responseEntity.getHeaders().toSingleValueMap());
OAuth2Exception excBody = responseEntity.getBody();
return new ResponseEntity(excBody, headers, responseEntity.getStatusCode());
}
};
}

}
Спасибо за помощь.

ОБНОВЛЕНИЕ. Мой API работает, я ничего не менял... Если у кого-нибудь есть идеи, откуда может возникнуть проблема, мне бы хотелось услышать об этом, чтобы лучше понять весну :)

Подробнее здесь: https://stackoverflow.com/questions/495 ... gerbuilder
Ответить

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

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

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

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

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