我试图完成一些非常简单的事情,我确信一旦得到这个,我就称自己为驴子。但是,以下是我尝试在sudo代码中执行的步骤。
step1
--get username and password from login form
step2
-- send username and password to web service
step3
-- if the return from the service equals "N" show error else if the return from the service equals "Y" then authenticate a user and query database for user roles.
step4
-- if the user role is not allowed to see page show error page else continue to page.
我已经尝试了几个教程,而我只是惨遭失败。我怀疑因为我所看到的所有内容都与配置相关或注释相关,因此我很难理解用户在什么时候进行身份验证。
我已经尝试了
http://o7planning.org/en/10603/spring-mvc-security-and-spring-jdbc-tutorial Spring security access with multiple roles
我最大的问题是上面的第3步。我怎样才能做到这一点?我根本不了解如何对用户进行身份验证,并向该用户添加多个角色以保持在spring的constratint中。
答案 0 :(得分:1)
当您使用Spring-Security时,您可以使用以下结构:
[在我的例子中是基于注释并使用Spring-Boot。]
您需要一个从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);
}
}