实体UserInfo和AuthInfo分开的结构

时间:2018-12-27 23:47:00

标签: rest spring-boot

为了管理多个登录解决方案,例如:用户名/密码,Facebook身份验证等。我在Spring启动项目中将Account(用户信息)和LocalAuth(Username / password)分离为2个表。 但是现在我需要为所有控制器添加安全控制,以仅允许用户本人获取他的信息。我必须将Rest API更改为以下格式:     @GetMapping(“ / {用户名} /借款”)     @PreAuthorize(“ authentication.name.equals(#username)”)     上市 ... 因此,我必须使用存储在LocalAuth实体中的用户名来获取帐户。

这是用户表:

android.intent.category.INFO

身份验证表:

@Entity
@Table(name = "account")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Account implements UserDetails, Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDate birthDate;

@Email(message = "The email format is not good")
@Size(max=50)
@Column(nullable = true, length = 50, unique = true)
private String email;

@OneToOne(mappedBy = "account")
private LocalAuth localAuth;

@OneToMany(mappedBy = "borrower", cascade = CascadeType.ALL)
@JsonIgnore
private List<Borrowing> borrowings = new ArrayList<>(); 
// getter/setter and constructor
}

在我的AccountService中:

@Entity
public class LocalAuth {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@NotEmpty(message = "The username can not be empty")
@Size(min=3, max=50)
@Column(nullable = false, length = 50, unique = true)
private String username;

@NotEmpty(message = "The password can not be empty")
@Size(max=100)
private String password;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createDateTime;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastEditDateTime;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "account_id")
@JsonIgnore
private Account account;
}

新控制器:

public List<Borrowing> getUserBorrowings(String username){
LocalAuth localAuth = localAuthRepository.findByUsername(username);
if(localAuth != null && localAuth.getAccount() != null) {
        return localAuth.getAccount().getBorrowings();
    }
    throw new NotFoundException(username);
}

当我调用此方法时,我得到了一个空的借贷清单

但是当我使用帐户ID来获取帐户,然后在不使用LocalAuth的情况下获取借用列表时,它就可以工作。例如:“

@GetMapping("/{username}/borrowings")
@PreAuthorize("authentication.name.equals(#username)")
public ResponseEntity<Response> getBorrowings(@PathVariable("username") String username){
    List<Borrowing> borrowings = accountService.getUserBorrowings(username);
    return ResponseEntity.ok().body(new Response(true, "OK", borrowings, borrowings.size()));
}

这是我的问题:

  1. 是因为延迟加载导致第一个解决方案无法工作?我无法使用LocalAuth来获取帐户,然后无法检索借用清单?

  2. 将用户身份验证信息和用户信息分开是个好主意吗?

  3. 我必须使用@JsonIgnoreProperties({“ hibernateLazyInitializer”,“ handler”})来避免一些可为空的错误,如何解决该问题?

谢谢。

0 个答案:

没有答案