【问题标题】:Spring Security multiple dao authenticationSpring Security 多道认证
【发布时间】:2015-03-17 04:50:36
【问题描述】:

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

用户只能通过一种方式登录。现在在后端,我想检查用户是否正在登录他的个人帐户或组帐户(唯一用户名)。我想知道如何在 XML 中实现多种 dao 身份验证方法并基于登录进行重定向。这两个模型都实现了 UserDetails 接口。这是security-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
}

GroupMembers 模型:

@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。欢迎任何指点。谢谢。

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    是的,您需要单独的 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。它包含使用不同UserDetailServices 的身份验证,具体取决于提交的登录名。 它还包含重定向到个人或组页面,具体取决于附加到身份验证的特定权限。只需输入mvn tomcat:run 并浏览至http://localhost:8080/sandbox。祝你好运

    【讨论】:

    • 感谢您的回答,我有一个 GroupLoginServiceImpl 已经实现了 loadByUserName(),但是如果您检查主帖子是否有最新错误...非常感谢。
    • @we-are-borg 我不确定,但我没有在您的帖子中看到最新的错误。您是否按照我的建议在安全 xml 中修改了authentication-manager
    • 我在stackoverflow.com/questions/28041310/… 上添加了另一个帖子。我现在正在做你建议的修改。
    • 我试过你的建议,没有用,你能检查一下这个xml是否正确,pastebin.com/GFK3V5Qd ...谢谢
    • authenticationManagerForPersonalauthenticationManagerForGroup 是 bean 类型 ProviderManager。这是错误的。您必须将这些 bean 声明为类型 DaoAuthenticationProvider。请仔细看看我的 spring 安全配置。
    猜你喜欢
    • 2012-08-15
    • 2016-08-11
    • 2015-03-11
    • 2016-11-15
    • 2013-11-03
    • 1970-01-01
    • 2014-02-17
    • 2019-06-18
    • 2013-08-10
    相关资源
    最近更新 更多