0
我通過ApplicationRunner通過基於Spring Security/JPA的身份驗證將管理員/測試用戶添加到我的Spring Boot應用程序中。Spring Security編程授權
在此之前,我有一個data.sql文件,但我需要支持多個數據庫,所以我一直在尋找一個便攜式解決方案。
我有一個春天JPA的數據存儲庫,爲用戶和簡單地添加我的用戶像這樣:
@Component
public class MyRunner implements ApplicationRunner {
private UserRepository userRepository;
@Autowired
public MyRunner(UserRepository userRepository) {
this.userRepository = userRepository;
}
/* (non-Javadoc)
* @see org.springframework.boot.ApplicationRunner#run(org.springframework.boot.ApplicationArguments)
*/
@Override
public void run(ApplicationArguments args) throws Exception {
User admin = new User("admin", "admin", Roles.ROLE_ADMIN);
userRepository.saveAndFlush(admin);
}
}
這工作得很好。但我激活春季全局方法的安全性,以確保UserRepository,它通過REST也暴露:
@PreAuthorize("hasRole('ROLE_ADMIN')")
@Override
<S extends User> S save(S user);
但後來添加用戶失敗了,因爲我沒有被授權。我嘗試這個技巧:
@Override
public void run(ApplicationArguments args) throws Exception {
User admin = new User("admin", "admin", Roles.ROLE_ADMIN);
Authentication auth = new UsernamePasswordAuthenticationToken(admin, null,
AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
SecurityContextHolder.getContext().setAuthentication(auth);
userRepository.saveAndFlush(admin);
SecurityContextHolder.clearContext();
}
用戶被添加,但身份驗證的Web應用程序本身現在徹底打破......
我只得到AuthenticationCredentialsNotFoundException
o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=Mon Dec 05 19:12:10 CET 2016, principal=<unknown>, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException, message=An Authentication object was not found in the SecurityContext}]
雖然說實話,我對這個「解決方案」並不滿意。這會產生大量新的antMatchers,其中包含所有異常情況等。 –