當你使用Spring的安全,你可以用這個結構:
[我這種情況是基於註解與Spring的引導。]
您將需要從WebSecurityConfigurerAdapter
延伸的ApplicationSecurity類
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailSecurityService userDetailSecurityService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/static").permitAll().anyRequest()
.fullyAuthenticated();
http
.csrf().disable()
.formLogin().loginPage("/login").failureUrl("/login?error=1")
.permitAll().defaultSuccessUrl("/")
.successHandler(
new NoRedirectSavedRequestAwareAuthenticationSuccessHandler())
.and()
.sessionManagement()
.sessionAuthenticationErrorUrl("/notauthorized")
.invalidSessionUrl("/notauthorized")
.and()
.logout()
.deleteCookies("JSESSIONID", "SESSION")
.permitAll();
}
//If you want to add some encoder method to store your passwords
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailSecurityService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder(){
return new MD5PasswordEncoder();
}
private class NoRedirectSavedRequestAwareAuthenticationSuccessHandler extends
SimpleUrlAuthenticationSuccessHandler {
final Integer SESSION_TIMEOUT_IN_SECONDS = 30 * 60; /** 30 min */
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
request.getSession().setMaxInactiveInterval(SESSION_TIMEOUT_IN_SECONDS);
response.sendRedirect("/");
}
}
}
你的類UserDetailsSecurityService一定要實現的UserDetailsService,這是一個Spring Security類,需要覆蓋的方法loadUserByUsername()
@Service
public class UserDetailSecurityService implements UserDetailsService{
@Autowired
UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*Here in your case would call your WebService and check if the result is Y/N and return the UserDetails object with all roles, etc
If the user is not valid you could throw an exception
*/
return userService.findByUsername(username);
}
}
您的Web服務只返回Y和N的成功和失敗嗎?如果是的話,那麼很難推斷出你想返回給客戶端的錯誤,比如用戶不存在,用戶憑證無效或者用戶在數據庫中不活躍,理想情況下,Web服務應該返回適當的響應以及用戶數據(至少是角色)這樣你就不需要再次查詢數據庫來獲取角色。 – Apollo
感謝阿波羅的迴應。如果服務響應等於「n」,則返回「錯誤的用戶名/密碼」錯誤。所以我真正的問題在上面的第3步。我認爲,但我不確定,是否需要以某種方式使用用戶詳細信息服務,但我不確定自己在做什麼。 – Miguel
@Miguel,但你使用彈簧安全嗎?因爲如果你正在使用它,你不需要web服務,你必須添加你的UserDetailsService的實現 – cralfaro