我无法在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的新手。感谢。
答案 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();