Spring Security:如何检索accessDeniedPage的用户名?

时间:2016-11-10 07:57:17

标签: java html spring spring-security thymeleaf

我正在使用Spring Security,HTML和thymeleaf,我会检索登录失败的用户。登录有两个步骤:第一步检查用户和密码是否正确进入LDAP,第二步检查用户是否有角色进入数据库。只有两者都通过,才会对用户进行身份验证。现在我想进入我的注册页面登录失败的用户(预编译输入字段)。注册页面是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();
}

如果我在我的/ registration控制器中添加Principal,则为null。为什么? Principal为null,在authenticate方法中可能出错。此外,我可能遇到安全问题,因为我的注册Web服务未经过身份验证,而应该在没有任何角色的情况下进行身份验证 是否有可能进入注册页面的用户登录失败? 感谢

1 个答案:

答案 0 :(得分:0)

我已将此行更改为身份验证方法:

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

用户为空,因为他不存在于数据库中,因此查询返回null对象,而我必须创建一个只有用户名的用户。