我在现有的Web应用程序中添加了spring security(方法级安全性)。
1)SecurityConfig类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@ComponentScan(basePackages = "com.freelance.impl")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationServiceImpl authenticationService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authenticationService);
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("CONFIGURE HTTP SECURITY");
http
.authorizeRequests()
.antMatchers("/user/**").permitAll()
.anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(authenticationService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
}
2)UserDetailsService实现类
@Service
public class AuthenticationServiceImpl implements UserDetailsService {
@Autowired
private UserRespository userRepository;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
boolean userStatus = false;
UserEntity userEntity = userRepository.findByUserName(userName);
if(userEntity.getStatus().equals(Status.Active))
userStatus = true;
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(userEntity.getRole().toString()));
org.springframework.security.core.userdetails.User userDetails =
new org.springframework.security.core.userdetails.User(userName, userEntity.getPassword(), userStatus, true, true, true, authorities);
return userDetails;
}
}
3)控制器类
@RestController
public class AccountRestController {
@Autowired
private AccountService accountService;
@PreAuthorize("hasAnyRole('ADMINISTRATOR')")
@RequestMapping(value= "/acc/create", method=RequestMethod.POST)
public HotelDTO createHotel(@RequestBody AccountDTO accDTO) throws Exception{
return accountService.create(accDTO);
}
4)Spring安全依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
应用程序在没有弹簧安全性的情况下正常工作。
但是在添加spring安全配置类之后,应用程序启动失败
我将战争部署到tomcat服务器时得到以下错误。
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
log4j:WARN No appenders could be found for logger (com.webadvisors.config.AppConfig).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Jan 16, 2017 7:48:17 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
Jan 16, 2017 7:48:17 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/services] startup failed due to previous errors
5)容器日志文件 - localhost.log
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountRestController' defined in file [E:\DEV\apache-tomcat-7.0.72\webapps\services\WEB-INF\classes\com\freelance\controller\AccountRestController.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: An AuthenticationManager is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
我无法解决错误,因为我没有在控制台中看到任何异常/错误跟踪。
1)导致此问题的安全配置出了什么问题 2)为什么服务器控制台上没有显示异常跟踪?如何捕获完整的异常跟踪?