Spring 安全多重dao认证

Spring Security multiple dao authentication

我正在开发一个 Spring-MVC 项目,我有两种登录模式,一种用于单人登录,另一种用于群组登录。单人或个人登录现在可以使用,但我想实现群组功能。由于group的数据库模型不同,我在另一个数据库中实现了table。

用户只有一种登录方式。现在在后端,我想检查用户是否正在登录他的个人帐户或组帐户(唯一用户名)。我想知道如何在 XML 中实现多个 dao 身份验证方法并根据登录进行重定向。这两个模型都实现了 UserDetails 接口。这里是安全-context.xml

    <security:http create-session="ifRequired" use-expressions="true" auto-config="true" disable-url-rewriting="true">
        <security:form-login login-page="/" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout logout-success-url="/" delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>

<security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>

人物模型:

@Entity
@Table(name="person")
public class Person implements UserDetails{
   @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;
// Other stuff
}

群组成员模型:

@Entity
@Table(name="groupaccount")
public class GroupMembers implements UserDetails {

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_GROUP");

    @Id
    @Column(name="memberid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "groupmembers_seq_gen")
    @SequenceGenerator(name = "groupmembers_seq_gen",sequenceName = "groupmembers_seq")
    private Long groupId;
//other stuff
}

登录服务实现:

@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
        Person person = personDAO.findPersonByUsername(username.toLowerCase());
            if(person == null) { throw new UsernameNotFoundException("Wrong username or password");} //Never specify which one was it exactly
        return assembler.buildUserFromUserEntity(person);
    }
}

汇编程序:

@Service("assembler")
public class Assembler {
    @Transactional(readOnly = true)
    User buildUserFromUserEntity(Person userEntity){
        String username = userEntity.getUsername().toLowerCase();
        String password = userEntity.getPassword();

        // Long id = userEntity.getId();
        boolean enabled = userEntity.isEnabled();
        boolean accountNonExpired = userEntity.isAccountNonExpired();
        boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
        boolean accountNonLocked = userEntity.isAccountNonLocked();

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        User user = new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
        return  user;
        }
}

我还需要一个 LoginServiceImpl 和汇编程序吗?如何在 security-application-context.xml 中为多个 dao 入口点定义 bean。欢迎任何指点。谢谢。

是的,您需要单独的 LoginServiceImplAssembler,因为您正在使用不同的 Entity 类 用户和组进行两种身份验证。

更重要的是,您需要不同的 AuthenticationProviderUserDetailsService 用于用户和组登录:

<security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="userLoginAuthenticationProvider" />
        <security:authentication-provider ref="groupLoginAuthenticationProvider" />
</security:authentication-manager>

<!-- user login -->
<beans:bean id="userLoginAuthenticationProvider"
        class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
        <beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>

<!-- group login -->
<beans:bean id="groupLoginAuthenticationProvider"
        class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="GroupLoginServiceImpl"/>
       <beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>

您必须实施 GroupLoginServiceImpl 在您的组存储库上调用存储库方法。

请看一下这个demo project。根据提交的登录名,它包含具有不同 UserDetailService 的身份验证。 它还包含重定向到个人或组页面,具体取决于附加到身份验证的特定权限。只需键入 mvn tomcat:run 并浏览至 http://localhost:8080/sandbox。祝你好运