Spring Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:


Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:


1. Overview

In this tutorial – we'll replace the Reddit backed OAuth2 authentication process with a simpler, form-based login.

We'll still be able to hook Reddit up to the application after we log in, we'll just not use Reddit to drive our main login flow.

2. Basic User Registration

First, let's replace the old authentication flow.

2.1. The User Entity

We'll make a few changes to the User entity: make the username unique, add a password field (temporary) :

public class User {

    @Column(nullable = false, unique = true)
    private String username;

    private String password;


2.2. Register a New User

Next – let's see how to register a new user in the backend:

@RequestMapping(value = "/user")
public class UserController {

    private UserService service;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public void register(
      @RequestParam("username") String username, 
      @RequestParam("email") String email,
      @RequestParam("password") String password) 
        service.registerNewUser(username, email, password);

Obviously this is a basic create operation for the user – no bells and whistles.

Here's the actual implementation, in the service layer:

public class UserService {
    private UserRepository userRepository;

    private PreferenceRepository preferenceReopsitory;

    private PasswordEncoder passwordEncoder;

    public void registerNewUser(String username, String email, String password) {
        User existingUser = userRepository.findByUsername(username);
        if (existingUser != null) {
            throw new UsernameAlreadyExistsException("Username already exists");
        User user = new User();
        Preference pref = new Preference();

2.3. Dealing With Exceptions

And the simple UserAlreadyExistsException:

public class UsernameAlreadyExistsException extends RuntimeException {

    public UsernameAlreadyExistsException(String message) {
    public UsernameAlreadyExistsException(String message, Throwable cause) {
        super(message, cause);

The exception is dealt with in the main exception handler of the application:

@ExceptionHandler({ UsernameAlreadyExistsException.class })
public ResponseEntity<Object> 
  handleUsernameAlreadyExists(RuntimeException ex, WebRequest request) {
    logger.error("400 Status Code", ex);
    String bodyOfResponse = ex.getLocalizedMessage();
    return new 
      ResponseEntity<Object>(bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST);

2.4. A Simple Register Page

Finally – a simple front-end signup.html:

    <input  id="username"/>
    <input  id="email"/>
    <input type="password" id="password" />
    <button onclick="register()">Sign up</button>

function register(){
    $.post("user/register", {username: $("#username").val(),
      email: $("#email").val(), password: $("#password").val()}, 
      function (data){
        window.location.href= "./";
        alert("Error: "+ error.responseText);

It's worth mentioning again that this isn't a fully mature registration process – just a very quick flow. For a complete registration flow, you can check out the main registration series here on Baeldung.

3. New Login Page

Here is our new and simple login page:

<div th:if="${param.containsKey('error')}">
Invalid username or password
<form method="post" action="j_spring_security_check">
    <input name="username" />
    <input type="password" name="password"/>  
    <button type="submit" >Login</button>
<a href="signup">Sign up</a>

4. Security Configuration

Now – let's take a look at the new security configuration:

@ComponentScan({ "org.baeldung.security" })
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private MyUserDetailsService userDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {

    public PasswordEncoder encoder() { 
        return new BCryptPasswordEncoder(11); 

Most things are pretty straightforward, so we won't go over them in detail here.

And here's the custom UserDetailsService:

public class MyUserDetailsService implements UserDetailsService {

    private UserRepository userRepository;

    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username); 
        if (user == null) { 
            throw new UsernameNotFoundException(username);
        return new UserPrincipal(user);

And here is our custom PrincipalUserPrincipal” that implements UserDetails:

public class UserPrincipal implements UserDetails {

    private User user;

    public UserPrincipal(User user) {
        this.user = user;

    public String getUsername() {
        return user.getUsername();

    public String getPassword() {
        return user.getPassword();

    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));

    public boolean isAccountNonExpired() {
        return true;

    public boolean isAccountNonLocked() {
        return true;

    public boolean isCredentialsNonExpired() {
        return true;

    public boolean isEnabled() {
        return true;

Note: We used our custom PrincipalUserPrincipal” instead of Spring Security default User.

5. Authenticate Reddit

Now that we're no longer relying on Reddit for our authentication flow, we need to enable users to connect their accounts to Reddit after they log in.

First – we need to modify the old Reddit login logic:

public String redditLogin() {
    OAuth2AccessToken token = redditTemplate.getAccessToken();
    service.connectReddit(redditTemplate.needsCaptcha(), token);
    return "redirect:home";

And the actual implementation – the connectReddit() method:

public void connectReddit(boolean needsCaptcha, OAuth2AccessToken token) {
    UserPrincipal userPrincipal = (UserPrincipal) 
    User currentUser = userPrincipal.getUser();

Note how the redditLogin() logic is now used to connect the user's account in our system with his Reddit account by obtaining the user's AccessToken.

As for the frontend – that's quite simple:

<a href="profile" sec:authentication="principal.username">Bob</a></small>
<a th:if="${#authentication.principal.user.accessToken == null}" href="redditLogin" >
    Connect your Account to Reddit

We need to also need to make sure that users do connect their accounts to Reddit before trying to submit posts:

public String showSubmissionForm(Model model) {
    if (getCurrentUser().getAccessToken() == null) {
        model.addAttribute("msg", "Sorry, You did not connect your account to Reddit yet");
        return "submissionResponse";

6. Conclusion

The small reddit app is definitely moving forward.

The old authentication flow – fully backed by Reddit – was causing some problems. So now, we have a clean and simple form-based login while still being able to connect your Reddit API in the back end.

Good stuff.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

REST bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course :

Comments are closed on this article!