多个具有不同 UsernamePasswordAuthToken 的 AuthenticationProvider 来验证不同的登录表单,无需回退验证

Pra*_*ngi 4 java spring spring-mvc spring-security jakarta-ee

在使用 spring security 时,我查看了 stackoverflow 中有趣的线程,需要针对不同的身份验证提供者两组用户进行身份验证,例如员工反对LDAP和客户反对DATABASE。Thread 提出了一个公认的解决方案,使用一个单选按钮来区分员工和客户,并具有自定义身份验证过滤器,该过滤器根据用户类型区分登录请求并设置不同的身份验证令牌(customerAuthToken / employeeAuthToken),然后请求进行身份验证。会有两个AuthenticationProvider实现和认证是通过支持令牌完成和决定的。通过这种方式,线程能够提供有趣的解决方案来避免 spring security 默认提供的回退身份验证。

查看线程配置 Spring Security 3.x 以具有多个入口点

由于答案完全在 xml 配置中。我只是想让解决方案在 java 配置中可用。我将在回答中发布该内容。

现在我的问题是随着 spring 版本的发展,除了我的答案之外,是否有可能通过任何新功能/最小配置来具有相同的功能

Pra*_*ngi 6

由于此线程提供了完整的信息,因此我只是发布用于 Java 配置参考的代码。

在这里,我假设以下事情
1. 用户和管理员作为两组用户。
2. 为简单起见,两者都使用内存认证。
- 如果 userType 是 User,则只有用户凭据才有效。
- 如果 userType 是 Admin,则只有 admin 凭证才有效。- 并且应该能够为不同的权限提供相同的应用程序接口。

在此处输入图片说明

和代码
您可以从我的 github 存储库下载工作代码


CustomAuthenticationFilter

@Component
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
    {
        UsernamePasswordAuthenticationToken authToken = null;

        if ("user".equals(request.getParameter("userType"))) 
        {
            authToken = new UserUsernamePasswordAuthenticationToken(request.getParameter("userName"), request.getParameter("password"));
        }
        else 
        {
            authToken = new AdminUsernamePasswordAuthenticationToken(request.getParameter("userName"), request.getParameter("password"));
        }

        setDetails(request, authToken);

        return super.getAuthenticationManager().authenticate(authToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

CustomAuthentictionTokens

public class AdminUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken
{   
    public AdminUsernamePasswordAuthenticationToken(Object principal, Object credentials)
    {
        super(principal, credentials);
    }

    public AdminUsernamePasswordAuthenticationToken(Object principal, Object credentials,
            Collection<? extends GrantedAuthority> authorities)
    {
        super(principal, credentials, authorities);
    }
}

public class UserUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken
{
    public UserUsernamePasswordAuthenticationToken(Object principal, Object credentials)
    {
        super(principal, credentials);
    }

    public UserUsernamePasswordAuthenticationToken(Object principal, Object credentials,
            Collection<? extends GrantedAuthority> authorities)
    {
        super(principal, credentials, authorities);
    }}
Run Code Online (Sandbox Code Playgroud)

CustomAuthentictionProvider - For Admin

@Component
public class AdminCustomAuthenticationProvider implements AuthenticationProvider
{
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (username.equals("admin") && password.equals("admin@123#"))
        {
            List<GrantedAuthority> authorityList = new ArrayList<>();
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
            authorityList.add(authority);

            return new UserUsernamePasswordAuthenticationToken(username, password, authorityList);
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication)
    {
        return authentication.equals(AdminUsernamePasswordAuthenticationToken.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

CustomAuthentictionProvider - For User

@Component
public class UserCustomAuthenticationProvider implements AuthenticationProvider
{
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (username.equals("user") && password.equals("user@123#"))
        {
            List<GrantedAuthority> authorityList = new ArrayList<>();
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
            authorityList.add(authority);

            return new UserUsernamePasswordAuthenticationToken(username, password, authorityList);
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication)
    {
        return authentication.equals(UserUsernamePasswordAuthenticationToken.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

CustomHandlers required for CustomFilter

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler
{
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException
    {
        response.sendRedirect(request.getContextPath() + "/login?error=true");
    }   
}

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException
    {
        HttpSession session = request.getSession();
        if (session != null)
        {
            session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        }
        response.sendRedirect(request.getContextPath() + "/app/user/dashboard");
    }
}
Run Code Online (Sandbox Code Playgroud)

最后 SpringSecurityConfiguration

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 
{
    @Autowired
    DataSource dataSource;

    @Autowired
    private AdminCustomAuthenticationProvider adminCustomAuthenticationProvider;

    @Autowired
    private UserCustomAuthenticationProvider userCustomAuthenticationProvider;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.authenticationProvider(adminCustomAuthenticationProvider);
        auth.authenticationProvider(userCustomAuthenticationProvider);
    }

    @Bean
    public MyAuthenticationFilter myAuthenticationFilter() throws Exception
    {
        MyAuthenticationFilter authenticationFilter = new MyAuthenticationFilter();

        authenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        authenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
        authenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
        authenticationFilter.setAuthenticationManager(authenticationManagerBean());

        return authenticationFilter;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception
    {
        http
        .addFilterBefore(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/resources/**", "/", "/login")
                .permitAll()
            .antMatchers("/config/*", "/app/admin/*")
                .hasRole("ADMIN")
            .antMatchers("/app/user/*")
                .hasAnyRole("ADMIN", "USER")
            .antMatchers("/api/**")
                .hasRole("APIUSER")
        .and().exceptionHandling()
            .accessDeniedPage("/403")
        .and().logout()
            .logoutSuccessHandler(new CustomLogoutSuccessHandler())
            .invalidateHttpSession(true);

        http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它有助于理解在没有回退身份验证的情况下配置多重身份验证。