我正在尝试完成一些简单的事情,我敢肯定,一旦得到这个,我就会称自己为驴。但是,这是我想在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://www.ekiras.com/2016/04/authenticate-user-with-custom-user-details-service-inservice-in-spring-security.html
http://o7planning.org/en/10603/spring-mvc-security-and-spring-spring-jdbc-tutorial带有多个角色的春季安全访问
我最大的问题是上面的步骤3。我怎样才能做到这一点?我根本不明白如何验证用户并向该用户添加多个角色,以留在春季的约束中。
当您使用弹簧安全时,您可以使用此结构:
[就我而言,是基于注释的弹簧靴。]
您将需要一个从WebSecurityConfigurerAdapter延伸的应用程序等级
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,这是弹簧安全类,需要覆盖方法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);
}
}