繁体   English   中英

错误403-使用Spring Security拒绝访问-ManyToMany注释问题?

[英]Error 403 - Access denied using Spring security - ManyToMany annotation issue?

我无法弄清楚我在做什么错。 我正在尝试访问/user/test.jsp页面,但出现了403访问被拒绝的错误。

我猜问题出在UserEntity类中的ManyToMany注释中。 我已尽力尝试了一切,但仍未能成功解决。

经过进一步研究,似乎没有从数据库中加载user_security_role。

我知道是这样,因为Assembler类的buildUserFromUserEntity中的以下代码部分返回一个空的SecurityRoleCollection:

for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {
    authorities.add(new GrantedAuthorityImpl(role.getName()));
}

这是我用于表的SQL(来自教程):

CREATE TABLE IF NOT EXISTS security_role (

    `id` INT(11) NOT NULL AUTO_INCREMENT ,

    `name` VARCHAR(50) NULL DEFAULT NULL ,

    PRIMARY KEY (`id`) )

    ENGINE = InnoDB

    AUTO_INCREMENT = 4

    DEFAULT CHARACTER SET = latin1;


CREATE TABLE IF NOT EXISTS user (

    `id` INT(11) NOT NULL AUTO_INCREMENT ,

    `first_name` VARCHAR(45) NULL DEFAULT NULL ,

    `family_name` VARCHAR(45) NULL DEFAULT NULL ,

    `dob` DATE NULL DEFAULT NULL ,

    `password` VARCHAR(45) NOT NULL ,

    `username` VARCHAR(45) NOT NULL ,

    `confirm_password` VARCHAR(45) NOT NULL ,

    `active` TINYINT(1) NOT NULL ,

    PRIMARY KEY (`id`) ,

    UNIQUE INDEX `username` (`username` ASC) )

    ENGINE = InnoDB

    AUTO_INCREMENT = 9

    DEFAULT CHARACTER SET = latin1;


CREATE TABLE IF NOT EXISTS user_security_role (

    `user_id` INT(11) NOT NULL ,

    `security_role_id` INT(11) NOT NULL ,

    PRIMARY KEY (`user_id`, `security_role_id`) ,

    INDEX `security_role_id` (`security_role_id` ASC) ,

    CONSTRAINT `user_security_role_ibfk_1`

    FOREIGN KEY (`user_id` )

    REFERENCES `user` (`id` ),

    CONSTRAINT `user_security_role_ibfk_2`

    FOREIGN KEY (`security_role_id` )

    REFERENCES `security_role` (`id` ))

    ENGINE = InnoDB

    DEFAULT CHARACTER SET = latin1;

这是我无法工作的棘手部分:为私有Set securityRoleCollection配置的注释; 属性不会从数据库加载数据,我无法弄清楚我在做什么错。

public class UserEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "family_name")
    private String familyName;

    @Column(name = "dob")
    @Temporal(TemporalType.DATE)
    private Date dob;

    @Basic(optional = false)
    @Column(name = "password")
    private String password;

    @Basic(optional = false)
    @Column(name = "username")
    private String username;

    @Basic(optional = false)
    @Column(name = "confirm_password")
    private String confirmPassword;

    @Basic(optional = false)
    @Column(name = "active")
    private boolean active;

    @JoinTable(name = "user_security_role", joinColumns = {

    @JoinColumn(name = "user_id", referencedColumnName = "id") }, inverseJoinColumns = {

    @JoinColumn(name = "security_role_id", referencedColumnName = "id") })
    @ManyToMany
    private Set<SecurityRoleEntity> securityRoleCollection;

    public UserEntity() {

    }

这是我的UserEntityDAOImpl类:

public class UserEntityDAOImpl implements UserEntityDAO {

    public UserEntity findByName(String username) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        UserEntity user = null;
        try {
            transaction = session.beginTransaction();
            user = (UserEntity)session.createQuery("select u from UserEntity u where u.username = '"
                    + username + "'").uniqueResult();

            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return user;
    }

这是SecurityRoleEntity类:

@Entity
@Table(name = "security_role", catalog = "userauth", schema = "")
@NamedQueries({

        @NamedQuery(name = "SecurityRoleEntity.findAll", query = "SELECT s FROM SecurityRoleEntity s"),

        @NamedQuery(name = "SecurityRoleEntity.findById", query = "SELECT s FROM SecurityRoleEntity s WHERE s.id = :id"),

        @NamedQuery(name = "SecurityRoleEntity.findByName", query = "SELECT s FROM SecurityRoleEntity s WHERE s.name = :name") })
public class SecurityRoleEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

    @ManyToMany(mappedBy = "securityRoleCollection", fetch = FetchType.EAGER)
    private List<UserEntity> userCollection;

    public SecurityRoleEntity() {

    }

        getters and setters...

这是汇编程序类:

@Service("assembler")
public class Assembler {

    @Transactional(readOnly = true)
    User buildUserFromUserEntity(UserEntity userEntity) {

        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        boolean enabled = userEntity.getActive();
        boolean accountNonExpired = userEntity.getActive();
        boolean credentialsNonExpired = userEntity.getActive();
        boolean accountNonLocked = userEntity.getActive();

        Collection<GrantedAuthorityImpl> authorities = new ArrayList<GrantedAuthorityImpl>();

        for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {
            authorities.add(new GrantedAuthorityImpl(role.getName()));
        }

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

        return user;

    }

}

这是我的spring-security.xml的内容:

<beans:bean id="userDetailsService" class="service.UserDetailsServiceImpl">
</beans:bean>

<beans:bean id="assembler" class="service.Assembler">
</beans:bean>

<!-- <context:component-scan base-package="org.intan.pedigree" /> -->

<http auto-config='true'>
    <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
    <intercept-url pattern="/user/**" access="ROLE_User" />
    <!-- <security:intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" 
        /> -->
</http>

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

<beans:bean id="authenticationManager"
    class="org.springframework.security.authentication.ProviderManager">
    <beans:property name="providers">
        <beans:list>
            <beans:ref local="daoAuthenticationProvider" />
        </beans:list>
    </beans:property>
</beans:bean>

<authentication-manager>
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder hash="plaintext" />
    </authentication-provider>
</authentication-manager>

这是UserDetailsS​​erviceImpl:

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserEntityDAO dao;

    @Autowired
    private Assembler assembler;

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username)

    throws UsernameNotFoundException, DataAccessException {

        UserDetails userDetails = null;

        UserEntity userEntity = dao.findByName(username);

        if (userEntity == null)

            throw new UsernameNotFoundException("user not found");

        return assembler.buildUserFromUserEntity(userEntity);

    }

}

这是我要访问的页面的控制器:

public class HowDoesItWorkController implements Controller {

protected final Log logger = LogFactory.getLog(getClass());

@PreAuthorize("hasRole('ROLE_User')")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("returning contact view");
    return new ModelAndView("/explain");
}

}

我一直在关注此教程: http : //giannisapi.wordpress.com/2011/09/21/spring-3-spring-security-implementing-custom-userdetails-with-hibernate/

其中说要插入这些角色:

insert into security_role(name) values ("ROLE_admin");

insert into security_role(name) values ("ROLE_User");

我认为插入数据库中的角色名称应该与配置文件中配置的角色名称相同,因此我将xml文件中的角色名称更改为适合数据库中的角色名称,但是它没有任何改变。

数据库中的所有其他数据似乎都很好。

我还验证了我尝试访问的页面在/ user中,并且确实是这种情况。

调用UserEntityDAO时不会获取您的UserEntity的securityRoleCollection。 findByName()。 您要么需要实现DAO,以便它执行联接获取查询(可能更高效),要么简单的解决方法是添加:

@ManyToMany(fetch = FetchType.EAGER)
private Set<SecurityRoleEntity> securityRoleCollection

我认为这不是您唯一的问题。 您仍然需要确保所有角色名称都相等-上面的代码当前具有:

ROLE_REGISTERED_USER
ROLE_User

它们必须相同(除非SecurityRoleEntity类在两者之间映射?)

我已经能够解决问题。 这是我的错误,我没有在hibernate.cfg.xml文件下使用好的数据库。

此处配置的数据库正在引用另一个数据库,在该数据库中我也有3个表,但是由于它们为空,因此休眠请求未选择任何角色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM