如何在Spring Security OAuth2中获取经过身份验证的用户详细信息

时间:2017-08-29 04:52:58

标签: spring spring-boot spring-security spring-data-rest spring-security-oauth2

我无法在Spring Security OAuth2中提取当前登录的用户。我的目标是在触发ClientSuggestion实体上的create事件时提取用户并将其持久保存到数据库中。

Employee.java

@Entity
@Table(name = "er_employee")
public class Employee implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "username", unique = true)
    @NotNull
    @Size(max = 10)
    private String username;

    @Column(name = "password_hash")
    @NotNull
    @Size(min = 8, max = 512)
    private String password;


    @Column(name = "email_verification_token")
    @Size(max = 512)
    private String emailVerificationToken;

    @Column(name = "password_reset_token")
    @Size(max = 512)
    private String passwordResetToken;

    @Column(name = "active")
    @NotNull
    private boolean active;

    @Column(name = "is_deleted")
    @NotNull
    private boolean deleted;

    @Column(name = "date_of_creation")
    @Temporal(TemporalType.TIMESTAMP)
    @NotNull
    private Date dateOfCreation;

    @OneToMany(mappedBy = "employee")
    private List<ClientSuggestion> clientSuggestions;


    //Constructors
    //Getters ans setters
}

ClientSuggestion.java

@Entity
@Table(name = "er_suggestion")
public class ClientSuggestion implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "content", unique = true)
    @NotNull
    @Size(max = 200)
    private String suggestion;

    @ManyToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    //Constructors
    //Getters ans setters
}

EmployeeRepository.java

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

ClientSuggestionRepository .java

public interface ClientSuggestionRepository extends CrudRepository<ClientSuggestion, Long> {
}

事件处理程序

@Component
@RepositoryEventHandler(ClientSuggestion.class)
public class ClientSuggestionEventHandler {
    Employee employee= (Employee ) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    @HandleBeforeCreate
    public void handleClientSuggestionBeforeCreate(ClientSuggestion cs) {
       cs.setDeleted(false);
       cs.setActive(true);
       cs.setPasswordResetToken(Encryptor.generateHash(cs.getPassword, 512));
       cs.setEmployee(employee);
    }
}

bean,ClientSuggestionEventHandler,在配置类中注册。当我尝试运行该项目时,抛出NullPointerException异常。我希望了解如何获得当前记录的员工。 我是Spring Security OAuth2的新手。感谢。

1 个答案:

答案 0 :(得分:1)

Employee.java实施org.springframework.security.core.userdetails.UserDetails

<强> Employee.java

@Entity
@Table(name = "er_employee")
public class Employee implements Serializable, UserDetails {

然后使用Employee employee= (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();