带有数据库的SpringSecurity在vaadin maven项目中

时间:2016-03-07 15:53:40

标签: spring postgresql vaadin

我有一个vaadin maven项目,我整合了spring security,所以我能够看到spring security的默认登录形式。 现在我想从postgres数据库中获取用户可以帮助我吗?你有任何tuto或书籍吗?

1 个答案:

答案 0 :(得分:0)

作为Spring Boot Application + SpringSecurity + Vaadin4Spring#Hibernate的示例(尊重RolandKrügers示例),您必须在application.properties中定义以下属性:

# DATASOURCE
spring.datasource.url=jdbc:postgresql://localhost/myDB
spring.datasource.username=myuser
spring.datasource.password=mypwd
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.xa.data-source-class-name=org.postgresql.xa.PGXADataSource
spring.datasource.pinGlobalTxToPhysicalConnection="true"

# one transaction manager via view
spring.jpa.open-in-view=true
# for mapping models and attributes to table names and column names
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jta.default-transaction-timeout=2000

在app中使用application.properties将以下注释添加到主类:

@PropertySources({
    @PropertySource({"classpath:application.properties"})
})

现在,用户的实体可能如下所示:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
@Table(name = "USER")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;

    @Column(name = "LAST_NAME", nullable = false)
    private String lastName;

    @Column(name = "FIRST_NAME", nullable = false)
    private String firstName;

    @Column(name = "LOGGED_IN")
    private boolean loggedIn;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public boolean isLoggedIn() {
        return loggedIn;
    }

    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }
}

之后你必须为Hibernate定义一个存储库接口:

/**
*Spring auto repository for database access of User objects.
**/
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findOneByName(String userName);
}

现在,您可以在登录方法中执行类似的操作:

...
vaadinSecurity.login(userName.getValue(), passwordField.getValue());
Optional<User> ouser = userRepository.findOneByName(userName);
if (ouser.isPresent()) {
    User user = ouser.get();
    user.setLoggedIn(true);
}
...