首页 > 解决方案 > Spring Security - 如果缺少角色,则阻止登录

问题描述

我有一个使用 LDAP 身份验证对用户进行身份验证的 spring 应用程序,将其与自定义权限填充器结合使用,我可以正确登录到我的应用程序。但是,如果用户没有特定角色,我想阻止他们完全登录。

我试图创建一个登录成功处理程序,它将从Authentication对象中获取角色,setAuthenticated(false)如果它们不满足要求,但这似乎为时已晚,仍然允许用户继续。

我可以创建一个自定义身份验证提供程序,但由于LdapAuthenticationProviderConfigurer它非常有用,如果可能的话我不想这样做。

我目前的安全配置如下:

auth.ldapAuthentication()
        .userSearchBase(ldapBase)
        .userSearchFilter(ldapFilter)
        .ldapAuthoritiesPopulator(new AuthorityPopulator(client))
        .contextSource(contextSource());

我的成功处理程序:

protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    String targetUrl = determineTargetUrl(request, response);
    List<String> roles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
    if(!roles.contains("admin")) {
        authentication.setAuthenticated(false);
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}

标签: javaspringauthenticationspring-securityspring-security-ldap

解决方案


推荐阅读