How to secure REST with Spring Security

Setting up authentication and access control in Spring Security is painstaking, but you can draw on very powerful capabilities. Here’s how to get started.

1 2 Page 2
Page 2 of 2

The verify method also relies heavily on JJWT to validate the authenticity of the token. The beauty here is that the server itself has signed the JWT with a secret key, and uses the same key to validate it. In a production app, a more robust key would be used.

UserService.java and UserServiceImpl.java

Circle back to TokenAuthenticationService for a moment, and recall that it also makes use of the UserService interface, which is implemented by UserServiceImpl. This is a fake user service that would use a data access layer to handle persistence and querying of user info. In this case, a test user is hard-coded in the class as seen in Listing 8.

Listing 8. UserServiceImpl

@Service
final class UserServiceImpl implements UserService {

  Map<String, User> users = new HashMap<>()
  {{
       put("Matt", new User("0","matt","idg"));
  }};

  @Override
  public User save(final User user) {
    return users.put(user.getId(), user);
  }

  @Override
  public Optional<User> find(final String id) {
    return ofNullable(users.get(id));
  }

  @Override
  public Optional<User> findByUsername(final String username) {
    return users
      .values()
      .stream()
      .filter(u -> Objects.equals(username, u.getUsername()))
      .findFirst();
  }
}

UserController.java

We’ve just about completed the whole auth lifecycle. The last class to consider is UserController, which handles the log-in request from the front end. It also would handle the sign-up flow when adding new users.

Listing 9. UserController

The controller grabs the username and password and delegates to the UserAuthenticationService.login() method, which you've seen earlier.

Secure with Spring

Although setting up auth in Spring Security is painstaking, you can draw on very powerful capabilities. This article is intended to give you a grasp of the essential elements and how they interact.

For further information, two good resources are “Spring Security with Token Based Authentication” and “Securing a REST API with Spring Security.” 

Copyright © 2021 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2
How to choose a low-code development platform