Quick and Dirty way to add User authentication in Spring Boot Back-end

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
@Document
public class User {

@Id
private String id;

private String username;

private String email;

private int role;

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;

public User() {
}

public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.role = 0;
this.password = password;
}

... getters, setters, toString
}
@Repository
public interface UserRepository extends MongoRepository<User, String> {
Optional<User> findUserByUsername(String username);
Optional<User> findUserByEmail(String email);
}
@Service
public class UserService {

@Value("${SECRET_KEY}")
private String secret;
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;

/**
* Constructor
*/
@Autowired
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}

/**
* User registration
*/
public String createUser(User user) {
if(userRepository.findUserByEmail(user.getEmail()).isPresent())
throw new IllegalStateException("email taken");
if(userRepository.findUserByUsername(user.getUsername()).isPresent())
throw new IllegalStateException("username taken");

user.setPassword(passwordEncoder.encode(user.getPassword()));

userRepository.save(user);
return "success";
}

/**
* User Login
*/
public String loginUser(User requestUser) {
User user = userRepository.findUserByUsername(requestUser.getUsername()).orElseThrow(() -> new IllegalStateException("User with that username does not exist"));

if(passwordEncoder.matches(requestUser.getPassword(), user.getPassword())) {
return Jwts.builder()
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 1800000))
.signWith(SignatureAlgorithm.HS256, secret.getBytes(StandardCharsets.UTF_8))
.compact();
} else {
throw new IllegalStateException("invalid password");
}
}

/**
* Returns username if jwt is valid
*/
public String validateUser(String jwt) {
Claims claims = Jwts.parser()
.setSigningKey(secret.getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(jwt).getBody();

return claims.getSubject();
}
}
public String createUser(User user) {
if(userRepository.findUserByEmail(user.getEmail()).isPresent())
throw new IllegalStateException("email taken");
if(userRepository.findUserByUsername(user.getUsername()).isPresent())
throw new IllegalStateException("username taken");

user.setPassword(passwordEncoder.encode(user.getPassword()));

userRepository.save(user);
return "success";
}
public String loginUser(User requestUser) {
User user = userRepository.findUserByUsername(requestUser.getUsername()).orElseThrow(() -> new IllegalStateException("User with that username does not exist"));

if(passwordEncoder.matches(requestUser.getPassword(), user.getPassword())) {
return Jwts.builder()
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 1800000))
.signWith(SignatureAlgorithm.HS256, secret.getBytes(StandardCharsets.UTF_8))
.compact();
} else {
throw new IllegalStateException("invalid password");
}
}
public String validateUser(String jwt) {
Claims claims = Jwts.parser()
.setSigningKey(secret.getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(jwt).getBody();

return claims.getSubject();
}
@RestController
@RequestMapping(path = "/api/v1/users")
public class UserController {

private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}

@PostMapping("/register")
public String createUser(@RequestBody User user) {
return userService.createUser(user);
}

@PostMapping("/login")
public String loginUser(@RequestBody User user) {
return userService.loginUser(user);
}

@GetMapping("/validate")
public String validateUser(@RequestHeader("Bearer") String jwt) {
return userService.validateUser(jwt);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yo Han Joo

Yo Han Joo

I am a student at KTH, Computer Engineering