fb10
fb10

Reputation: 3

How to get current user id in spring?

I have a spring boot app with spring security:

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

and i've the folowwing user entity:

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

//permission //gets and sets `

I want to get the user ID logged in, for this I have tried as follows:

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

But i only get the user name. If someone can help me I would appreciate it.

Upvotes: 0

Views: 2648

Answers (2)

someone
someone

Reputation: 70

In your entity class

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

this means , your id is your private key and it is going to be generated in your database. You will save an entity and you will get the entity with your id.

What i recommend is use JpaRepository. You need to add a dependency in pom.xml

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

And you want to create a Repository interface.

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

In your controller.class ; inject your service and go to its methods. Inject repository in your service.

In your service method you can use

Entiy entity = repository.findById(id);

and its good to go.

Upvotes: 0

Marcin Kunert
Marcin Kunert

Reputation: 6285

Query the database to get the id. If you are using Spring Data, create a method in repository:

User findByName(String name);

And use it:

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

Upvotes: 1

Related Questions