Jurdefur
Jurdefur

Reputation: 65

Symfony 2 Custom Security Provider

Is there a way to create a custom security provider without using sessions, using my own database class and getting the user from the database with the email and not without haxing the getUsername returning the email ?

Upvotes: 1

Views: 1261

Answers (1)

ebaranov
ebaranov

Reputation: 585

You can use SecurityBundle for this, for ex. see example below:

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 }

you can use doctrine entity as security provide, the yml scheme of user entity for example:

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

and role entity:

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

and example of 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 }

Upvotes: 2

Related Questions