【问题标题】:How to get current user id in spring?如何在春季获取当前用户ID?
【发布时间】:2020-10-30 10:55:45
【问题描述】:

我有一个带有 spring security 的 spring boot 应用:

<spring-security-oauth2.version>2.2.1.RELEASE</spring-security-oauth2.version>
<spring-security-jwt.version>1.0.9.RELEASE</spring-security-jwt.version>

我有以下用户实体:

`@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String name;
@NotNull
private String email;
@NotNull
private String pass;

//权限 //获取和设置 `

我想获取登录的用户 ID,为此我尝试如下:

@GetMapping("/userId")
@ResponseBody
public String currentUserName(Authentication authentication) {
    return authentication.getName();
}

但我只得到用户名。如果有人可以帮助我,我将不胜感激。

【问题讨论】:

标签: spring-boot spring-security


【解决方案1】:

查询数据库以获取 id。如果您使用的是 Spring Data,请在存储库中创建一个方法:

User findByName(String name);

并使用它:

Long id = userRepository.findByName(authentication.getName()).getId();

【讨论】:

  • 这样可以到达!问题是如果您有两个同名的用户。
  • 使列名唯一或使用电子邮件来区分用户。
【解决方案2】:

在你的实体类中

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

这意味着,您的 id 是您的私钥,它将在您的数据库中生成。您将保存一个实体,您将获得具有您的 ID 的实体。

我推荐的是使用 JpaRepository。您需要在 pom.xml 中添加一个依赖项

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.3.0.RELEASE</version>
</dependency>

并且你想创建一个 Repository 接口。

public interface RepositoryName extends JpaRepository<Entity, String> {}

在你的 controller.class 中;注入您的服务并转到其方法。在您的服务中注入存储库。

在你的服务方法中你可以使用

Entiy entity = repository.findById(id);

一切顺利。

【讨论】:

  • 我正在使用 JPA。我不想按 ID 查找用户(如 JPA 查询)。为了访问应用程序,必须登录,我想知道登录用户的 ID 是什么。
  • 好的。为了用户登录,用户必须在您的数据库中。用户名是否唯一?它必须是因为用户将使用它登录。然后您可以使用用户名访问 userId。如果这不是你想要的,我会去写一个模拟代码来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
相关资源
最近更新 更多