Spring 针对客户和员工的安全用户身份验证

Spring Security user authentication against customers and employee

我是 Spring 安全方面的新手。我有一个包含两种不同类型实体的 Spring 启动应用程序。客户和员工。在员工中,我有普通员工、管理员和超级用户。由于我使用的是 JPA,每个实体都有自己的 repository。如何使用 loadUserByUsername 为我的 UserDetailsService 建模,因为这是针对许多存储库进行验证的常用方法。围绕我的实体建模是否缺少任何东西?

附加信息:

在我的设计中,我有两个实体。 CustomerEmployeeEmployee 将具有 NORMALADMINSUPER_USER 等角色。客户是一个不同的实体。

是否会有两个 UserDetailsService 和两个 AuthenticationProvider,每个都指向自己的 table(客户和员工)?

"Will there be two UserDetailsService and two AuthenticationProvider each pointing to its own table (Customer and Employee)?" .....答案是肯定的

Springsecurity有filter,UsernamePasswordAuthenticationFilter(查看filter的名称)可以根据输入类型具体实现。

我做了同样的事情,但使用了不同的身份验证机制。 但根据您的要求,有可能是您要找的。

由于您的要求是拥有多个身份验证入口点,因此它不像 Atul 的回答那么简单。

你需要的是

  1. 您需要在登录时区分客户和员工。(首选方式单选按钮)

  2. 您需要实施您的自定义身份验证过滤器,即实施 UsernamePasswordAuthenticationFilter 而不是 spring-安全提供默认值 .formLogin()

  3. 创建两个UsernamePasswordAuthenticationToken作为EmployeeUsernamePasswordAuthenticationTokenCustomerUsernamePasswordAuthenticationToken

  4. 在您的自定义过滤器中从请求中获取 userType 并根据 userType 将 authToken 设置为 empAuthToken 或 customerAuthToken 以区分所需的身份验证提供程序。

  5. Create AuthenticationProvider as EmployeeCustomAuthenticationProvider and CustomerCustomAuthenticationProvider where each AuthenticationProvider should be override supports method where AuthenticationProvider supports specific token customerAuthToken or employeeAuthToken.

  6. 覆盖身份验证方法,其中身份验证方法已通过身份验证参数传递,您可以从中获取用户名和密码,您可以将其传递给任何自定义服务以对用户进行身份验证并授予用户所需的权限.

在实施您的 CustomAuthenticationFilter 时,还需要提供您的自定义 authenticationSuccessHandler 和 AuthenticationFailureHandlers。

如果您无误地实施了以上所有内容,则可以避免 spring-security 在配置了两个 customAuthenticationProvider 时默认提供的后备身份验证。

有关使用 java 配置实现多个身份验证入口点的更多详细信息,请参阅下面给出的答案

你也可以download working code from my github repository