top of page

Spring Security - JWT Authentication - Series 2

  • Writer: Anand Nerurkar
    Anand Nerurkar
  • Apr 11, 2022
  • 2 min read


Let us add database integration to take user from database and create token to access api endpoints. We will make use of H2 DB that come with spring boot.


Prerequisite Knowledge

Spring Boot

Java 8

Maven

H2 DB

Spring Security

Eclipse IDE


1. Add below dependency in pom.xml


<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>


<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>


2. update main class to populate user into db with below method.


@PostConstruct

public void initUsers() {

List<User> users = Stream.of(

new User(102, "andy", "password", "andyn@gmail.com"),

new User(103, "pandy", "pass1", "pandy@gmail.com"),

new User(104, "sandy", "pass2", "sandy@gmail.com")

).collect(Collectors.toList());

repository.saveAll(users);

}


3. Create User entity with id, username, password and email attribute, define getter & setter for the same.


------User.java-----------

/**

*

*/

package com.techbytes.jwtdemo.model;


import javax.persistence.Entity;

import javax.persistence.Id;


/**

* @author andyn

*

*/

@Entity

public class User {

@Id

private int id;

private String userName;

private String password;

private String email;

public User(int id, String userName, String password, String email) {

super();

this.id = id;

this.userName = userName;

this.password = password;

this.email = email;

}



/**

* @return the id

*/

public int getId() {

return id;

}



/**

* @param id the id to set

*/

public void setId(int id) {

this.id = id;

}



/**

* @return the userName

*/

public String getUserName() {

return userName;

}



/**

* @param userName the userName to set

*/

public void setUserName(String userName) {

this.userName = userName;

}



/**

* @return the password

*/

public String getPassword() {

return password;

}



/**

* @param password the password to set

*/

public void setPassword(String password) {

this.password = password;

}



/**

* @return the email

*/

public String getEmail() {

return email;

}



/**

* @param email the email to set

*/

public void setEmail(String email) {

this.email = email;

}



/**

*

*/

public User() {

// TODO Auto-generated constructor stub

}


}


4. Define UserRepository as below


/**

*

*/

package com.techbytes.jwtdemo.repository;


import org.springframework.data.jpa.repository.JpaRepository;


import com.techbytes.jwtdemo.model.User;


/**

* @author andyn

*

*/

public interface UserRepository extends JpaRepository<User, Integer> {

User findByUserName(String username);

}


5. Update UserService with JPA to fetch the user from DB and populate spring userdetails object and return the same.


@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

// TODO Auto-generated method stub

/*

* logic to get the user from database

* User user=userRepository.findByUsername(username);

* return spring user as below with username,password and granted authority

* return new User(user.getUsername(),user.getPassword(),new ArrayList<T>());

*/

/*

* currently we are hardcoding the user as below

*/

//return new User("admin","password",new ArrayList());

com.techbytes.jwtdemo.model.User user=repository.findByUserName(username);

return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), new ArrayList<>());

}


6. Update application.properties file with below entry


spring.h2.console.enabled=true

spring.datasource.url=jdbc:h2:mem:cr

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

spring.jpa.show-sql=true

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

spring.jpa.hibernate.ddl-auto=update


7. Build and Run the application , test the /api/authenticate endpoint with user credential from DB.

ree

test /api/sample endpoint with above token and see response

ree









 
 
 

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
  • Facebook
  • Twitter
  • LinkedIn

©2024 by AeeroTech. Proudly created with Wix.com

bottom of page