Symfony 2自定义安全提供程序

时间:2011-06-22 09:53:00

标签: php symfony

有没有办法在不使用会话的情况下创建自定义安全提供程序,使用我自己的数据库类并使用电子邮件从数据库中获取用户,而不是不通过getUsername返回电子邮件?

1 个答案:

答案 0 :(得分:2)

您可以使用SecurityBundle,例如。见下面的例子:

security.yml

encoders:
        MyComapnyMysuperBundle\Entity\User:
            algorithm: sha512
            encode-as-base64: true
            iterations: 10

    providers:
        main:
            entity: { class: MyComapnyMysuperBundle:User, property: username }

    firewalls:
        main:
            pattern: /.*
            form_login:
                check_path: /login_check
                login_path: /login
            logout: true
            security: true
            anonymous: true

    access_control:
        - { path: /admin/.*, role: ROLE_ADMIN }
        - { path: /.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

您可以使用doctrine实体作为安全性提供,例如用户实体的yml方案:

User.orm.yml

MyComapny\MysuperBundle\Entity\User:
    type: entity
    table: user
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        username:
            type: string
            length: 255
        password:
            type: string
            length: 255
        first_name:
            type: string
            length: 255
        last_name:
            type: string
            length: 255
        email:
            type: string
            length: 255
        created_at:
            type: datetime
        salt:
            type: string
            length: 255
    manyToMany:
        userRoles:
            targetEntity: Role
            joinTable:
                name: user_role
                joinColumns:
                    user_id:
                        referencedColumnName: id
                inverseJoinColumns:
                    role_id:
                        referencedColumnName: id

和角色实体:

Role.orm.yml

MyComapny\MysuperBundle\Entity\Role:
    type: entity
    table: role
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        name:
            type: string
            length: 255
        created_at:
            type: datetime

和routing.yml的例子

login:
    pattern:  /login
    defaults: { _controller: MyComapnyMysuperBundle:Security:login }

login_check:
    pattern:  /login_check

logout:
    pattern:  /logout

eTracker_home:
    pattern:  /admin/{name}
    defaults: { _controller: MyComapnyMysuperBundle:Admin:index }