2016-11-10 63 views
0

我正在使用Spring Security,HTML和thymeleaf,并且我将检索登录失败的用户。登录有两步:第一步检查用户和密码是否正确进入LDAP,第二步检查用户是否具有到数据库中的角色。只有两者都通过,用户才能通过身份验证。现在我想登录失败的用户进入我的注册页面(预编译输入字段)。注册页面是accessDeniedPage。这是验证:春季安全:如何检索用户名到accessDeniedPage?

public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
      Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
      String name = authentication.getName(); 
      String password = authentication.getCredentials().toString(); 
      if (name == null || name.isEmpty() || password == null || password.isEmpty()) 
       return null; 
      boolean isFind = ldapServices.ldapSearch(name, password);       
      if (isFind){ 
       com.domain.User user = userServices.getByUsersEnabled(name); 
       if (user!=null){ 
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole().getRole())); 
       } 
       return new UsernamePasswordAuthenticationToken(user, password, authorities); 
      }   
      else return null; 
     } 

和重定向是:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    List<Role> roles=roleServices.getRoles(); 
    //Retrieve array of roles(only string field without id) 
    String[] rolesArray = new String[roles.size()]; 
    int i=0; 
    for (Role role:roles){ 
     rolesArray[i++] = role.getRole(); 
    } 

    http 
    .authorizeRequests() //Authorize Request Configuration 
    //the "/register" path are accepted without login 
    .antMatchers("/registration/**").authenticated() 
    //all the path need authentication 
    .anyRequest().hasAnyRole(rolesArray)//.authenticated() 
    .and()//Login Form configuration for all others 
    .formLogin() 
    .loginPage("/login") 
    .permitAll() 
    .and() 
    //redirect on page "registration" if user doens't exist in DART database 
    .exceptionHandling().accessDeniedPage("/registration") 
    .and() 
    .logout() 
    .logoutSuccessUrl("/login?logout") 
    .deleteCookies("JSESSIONID", "JSESSIONID") 
    .invalidateHttpSession(true) 
    .permitAll(); 
} 

如果我在/登记控制器添加主要为null。为什么? 主体为null,可能在验证方法中有错误。此外,由于我的注册Web服务未通过身份验证,因此我可能遇到安全问题,而他们应该无任何身份验证 登录失败的用户是否有可能进入注册页面? 感谢

+0

在我看来,你最后一个问题的答案是肯定的。默认情况下,如果有任何用户登录,并且该用户没有访问任何页面,则可以从Principal获得用户的信息。 –

+0

主体返回null,我也尝试过使用@AuthenticationPrincipal用户用户,并在HTML代码中使用sec:authentication =“principal.username”,全部为空 – luca

+0

我从您的安全conf中了解到,如果任何注册用户想要打开注册页面你想显示你没有访问此页面。这是真的吗? –

回答

0

我已经改变了此行到身份验证方法:因为他根本不存在到数据库中,以便查询返回空对象,而不是我要创建只有一个用户

return new UsernamePasswordAuthenticationToken(user==null?new User(name,null,false):user, password, authorities); 

用户为空用户名。