Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 66 ยท Projects

Project: Blog with Users and Roles

Build a blog API with Spring Boot: registration with hashed passwords, HTTP Basic login, roles, ownership checks with method security and security tests.

A blog is a good security exercise because the rules are easy to say and easy to get wrong. Anyone may read published posts. Only signed-in users may write. A user may edit and delete their own posts, but not other people's. An administrator may moderate everything. Most real-world breaches in this area are not exotic: they are a missing ownership check on one endpoint.

In this project you build that API with Spring Security: user registration with hashed passwords, login, roles, and ownership checks enforced with method security. Spring Boot and a database cannot run on this site, so the real code is read-only. Two runnable stand-ins model the interesting parts in plain Java: an authorization policy that you can query like a matrix, and a registration and login flow with real PBKDF2 password hashing and HTTP Basic decoding. The background is in Spring Security Fundamentals and Spring Security; the layering of the app follows Project: Todo REST API.

The rules

Who may do what

Anonymous Reads published posts. Nothing else.
User Creates posts. Edits and deletes their own.
Admin Moderates any post, drafts included.

Roles say what you are. Ownership says what is yours.

1 / 2

Entities and registration

Two entities: users with a role, and posts that belong to one author. The table is called app_user because user is a reserved word in several databases:

Java
@Entity
@Table(name = "app_user")
public class AppUser {

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

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

    @Column(nullable = false)
    private String passwordHash;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

    protected AppUser() {
    }

    public AppUser(String username, String passwordHash, Role role) {
        this.username = username;
        this.passwordHash = passwordHash;
        this.role = role;
    }

    // getters omitted
}

public enum Role {
    USER, ADMIN
}

@Entity
public class Post {

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

    @Column(nullable = false, length = 200)
    private String title;

    @Column(nullable = false, length = 20000)
    private String body;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private AppUser author;

    private boolean published;

    // constructor and getters omitted
}

Registration takes a username and a password. The request is validated, the password is hashed, and the role is always USER:

Java
public record RegisterRequest(
    @Pattern(regexp = "[a-z0-9_]{3,30}") String username,
    @Size(min = 10, max = 72) String password) {
}

@Service
public class AccountService {

    private final AppUserRepository users;
    private final PasswordEncoder encoder;

    public AccountService(AppUserRepository users, PasswordEncoder encoder) {
        this.users = users;
        this.encoder = encoder;
    }

    @Transactional
    public void register(RegisterRequest request) {
        if (users.existsByUsername(request.username())) {
            throw new UsernameTakenException(request.username());
        }
        users.save(new AppUser(request.username(), encoder.encode(request.password()), Role.USER));
    }
}

Three points are easy to overlook. The role is never read from the request, otherwise anyone could register as an admin (this class of bug is called mass assignment); administrators are created by a seed script or migration. The password limit of 72 matches the BCrypt algorithm that Spring Security uses by default, which only processes the first 72 bytes of a password. And the password is hashed with a salted, deliberately slow algorithm, never stored as text, never encrypted, never logged.

The next stand-in runs the whole flow with a real slow hash, PBKDF2 from the JDK, standing in for BCrypt. It also decodes an HTTP Basic Authorization header the way the framework does, and it treats unknown users and wrong passwords identically.

Java Registration and login with hashed passwords

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each stored value contains a fresh random salt, so alice and bob, who chose the same password, get different values. Two different failure cases (wrong password, unknown user) produce one identical answer, so an attacker cannot use the login to discover which usernames exist. Spring Security does both for you: DaoAuthenticationProvider hides "user not found" behind "Bad credentials" and performs a dummy password check.

Login and the security configuration

For an API used by scripts and other services, HTTP Basic is the simplest login: the client sends Authorization: Basic ... with every request. (Browser apps use form login or tokens, and stateless APIs often use JWT; see JWT and OAuth 2 Resource Server.) Spring needs two things: a way to load users, and the filter chain.

Java
@Service
class DatabaseUserDetailsService implements UserDetailsService {

    private final AppUserRepository users;

    DatabaseUserDetailsService(AppUserRepository users) {
        this.users = users;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        AppUser user = users.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("Bad credentials"));
        return User.withUsername(user.getUsername())
            .password(user.getPasswordHash())
            .roles(user.getRole().name())
            .build();
    }
}
Java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.POST, "/api/auth/register").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

Disabling CSRF protection is only acceptable here because the clients are not browsers that keep credentials and send them automatically. If browsers use the API, keep CSRF on and read CSRF, CORS and Secure Defaults. The delegating encoder stores hashes with an prefix such as , so you can move to a stronger algorithm later without locking out existing users.

The URL rules are intentionally coarse: they decide who may reach an endpoint. The decision "may this user change this post?" needs the post, so it belongs in the method rules.

flowchart TD
    A["Request"] --> B{"Credentials sent?"}
    B -- no --> C{"Does the URL need a login?"}
    C -- yes --> X["401 Unauthorized"]
    C -- no --> E["Controller"]
    B -- yes --> D{"Password correct?"}
    D -- no --> X
    D -- yes --> E
    E --> F{"Method rule allows it?"}
    F -- no --> Y["403 Forbidden, or 401 if anonymous"]
    F -- yes --> G["Service runs"]

Authentication (who are you?) is checked first, authorization (may you?) second.

Ownership checks with method security

@EnableMethodSecurity activates annotations such as @PreAuthorize on beans. Spring wraps the bean in a proxy that evaluates the expression before the method runs, using the same proxy mechanism as @Transactional:

Java
@Service
@Transactional(readOnly = true)
public class PostService {

    private final PostRepository posts;
    private final AppUserRepository users;

    public PostService(PostRepository posts, AppUserRepository users) {
        this.posts = posts;
        this.users = users;
    }

    @PreAuthorize("isAuthenticated()")
    @Transactional
    public PostView create(String username, NewPost request) {
        AppUser author = users.findByUsername(username).orElseThrow();
        return PostView.from(posts.save(new Post(request.title(), request.body(), author, request.published())));
    }

    @PostAuthorize("returnObject.published() or hasRole('ADMIN') or returnObject.author() == authentication.name")
    public PostView get(long id) {
        return PostView.from(posts.findById(id).orElseThrow(() -> new PostNotFoundException(id)));
    }

    @PreAuthorize("hasRole('ADMIN') or @postPolicy.isOwner(#id, authentication)")
    @Transactional
    public PostView update(long id, NewPost request) {
        Post post = posts.findById(id).orElseThrow(() -> new PostNotFoundException(id));
        post.change(request.title(), request.body(), request.published());
        return PostView.from(post);
    }

    @PreAuthorize("hasRole('ADMIN') or @postPolicy.isOwner(#id, authentication)")
    @Transactional
    public void delete(long id) {
        posts.deleteById(id);
    }

    public Page<PostView> listPublished(Pageable pageable) {
        return posts.findByPublishedTrue(pageable).map(PostView::from);
    }
}
Java
@Component("postPolicy")
class PostPolicy {

    private final PostRepository posts;

    PostPolicy(PostRepository posts) {
        this.posts = posts;
    }

    boolean isOwner(long postId, Authentication authentication) {
        return posts.findAuthorUsernameById(postId)
            .map(owner -> owner.equals(authentication.getName()))
            .orElse(true);   // no such post: let the service answer 404
    }
}

Read the expressions as sentences: "an admin, or the owner of this post, may update". #id refers to the method parameter, authentication to the current user, and @postPolicy to the bean of that name. @PostAuthorize runs after the method and sees returnObject, which suits reads where the decision depends on the loaded data, such as a draft that only its author or an admin may see. The orElse(true) in the policy looks surprising but is deliberate: for a post that does not exist there is nothing to protect, so the method runs and throws the usual 404.

Two pitfalls. A call from one method of the bean to another (this.update(...)) does not go through the proxy, so the annotation is skipped; see the self-invocation warning in Transactions with @Transactional. And the list endpoint must never rely on filtering after the fact: findByPublishedTrue selects only published rows, so a draft cannot leak through paging or counts.

Now the authorization policy itself, as plain Java you can run. Each rule is a small predicate, and or(...) composes them just like the or in the expressions. The program asks every actor to try every action and prints the HTTP status Spring would return: 200 when allowed, 401 when an anonymous caller is refused, 403 when a signed-in caller is refused.

Java An authorization matrix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the matrix column by column: anonymous callers get 401 for everything except published posts, bob is stopped with 403 from touching alice's posts, and the admin passes everywhere. A table like this is a handy review tool, and your real tests should check the same cells.

The controller

The controller stays thin. It passes the logged-in name to the service and leaves the decisions to the rules above:

Java
@RestController
@RequestMapping("/api")
class BlogController {

    private final AccountService accounts;
    private final PostService posts;

    BlogController(AccountService accounts, PostService posts) {
        this.accounts = accounts;
        this.posts = posts;
    }

    @PostMapping("/auth/register")
    @ResponseStatus(HttpStatus.CREATED)
    void register(@Valid @RequestBody RegisterRequest request) {
        accounts.register(request);
    }

    @GetMapping("/posts")
    Page<PostView> list(@PageableDefault(size = 20) Pageable pageable) {
        return posts.listPublished(pageable);
    }

    @GetMapping("/posts/{id}")
    PostView get(@PathVariable long id) {
        return posts.get(id);
    }

    @PostMapping("/posts")
    @ResponseStatus(HttpStatus.CREATED)
    PostView create(@Valid @RequestBody NewPost request, Authentication authentication) {
        return posts.create(authentication.getName(), request);
    }

    @PutMapping("/posts/{id}")
    PostView update(@PathVariable long id, @Valid @RequestBody NewPost request) {
        return posts.update(id, request);
    }

    @DeleteMapping("/posts/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable long id) {
        posts.delete(id);
    }
}

An AccessDeniedException thrown by the method rules becomes 403 through Spring Security's own handling, and you can add a custom handler to return a problem detail, as in Error Handling and Problem Details. Some teams return 404 instead of 403 for other users' drafts, so that the existence of a draft is not revealed; decide this once and apply it everywhere.

Testing security

Security tests prove that the rules hold today and keep holding after refactoring. A web slice test imports the security configuration and acts as different users:

Java
@WebMvcTest(BlogController.class)
@Import(SecurityConfig.class)
class BlogSecurityTest {

    @Autowired
    MockMvcTester mvc;

    @MockitoBean
    PostService posts;

    @MockitoBean
    AccountService accounts;

    @MockitoBean
    DatabaseUserDetailsService userDetails;

    @Test
    void anonymousCannotCreatePosts() {
        assertThat(mvc.post().uri("/api/posts")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"title\":\"Hi\",\"body\":\"Text\",\"published\":true}"))
            .hasStatus(HttpStatus.UNAUTHORIZED);
    }

    @Test
    @WithMockUser(username = "alice", roles = "USER")
    void signedInUserCanCreatePosts() {
        when(posts.create(eq("alice"), any())).thenReturn(new PostView(1, "Hi", "Text", "alice", true));

        assertThat(mvc.post().uri("/api/posts")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"title\":\"Hi\",\"body\":\"Text\",\"published\":true}"))
            .hasStatus(HttpStatus.CREATED);
    }
}

Because the ownership rules live on the service, test them there with a full application context and a mock user, since a mocked service has no rules to check:

Java
@SpringBootTest
@Transactional
class PostServiceSecurityTest {

    @Autowired
    PostService posts;

    @Autowired
    AppUserRepository users;

    @Test
    @WithMockUser(username = "bob", roles = "USER")
    void userCannotUpdateSomeoneElsesPost() {
        long id = seedPostOwnedBy("alice");

        assertThatThrownBy(() -> posts.update(id, new NewPost("Hijacked", "text", true)))
            .isInstanceOf(AccessDeniedException.class);
    }

    @Test
    @WithMockUser(username = "root", roles = "ADMIN")
    void adminCanDeleteAnyPost() {
        long id = seedPostOwnedBy("alice");

        assertThatCode(() -> posts.delete(id)).doesNotThrowAnyException();
    }
}

Write one test per cell of the matrix that matters, in particular the denials. A rule that is never tested to deny is a rule you only hope works. More on the annotations used here is in Testing Controllers with MockMvc.

Ideas for extending it

  • Add comments with the same ownership rules: authors edit their own, post authors and admins can delete any comment on their posts.
  • Add an EDITOR role that may publish drafts but not delete posts.
  • Replace HTTP Basic with a login endpoint that returns a short-lived JWT.
  • Add a login rate limiter like the one in Project: URL Shortener Service.
  • Add an audit table that records who changed or deleted which post.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does registration ignore any role sent by the client and always create a USER?

    Accepting a role from the request is a mass-assignment vulnerability. Privileged accounts must be created through trusted channels such as a seed script.
  2. 2. Which statement about @PreAuthorize("hasRole('ADMIN') or @postPolicy.isOwner(#id, authentication)") is correct?

    The expression runs before the method, #id refers to the parameter, and @postPolicy is a bean that decides ownership.
  3. 3. A signed-in user without permission calls an endpoint guarded by a method rule. Which status does Spring Security produce?

    401 means "I do not know who you are", 403 means "I know who you are and you may not do this". An anonymous caller would get 401.
  4. 4. Why should login answer the same way for an unknown user and a wrong password?

    A uniform "Bad credentials" message (and similar timing) prevents username enumeration.
  5. 5. Why would a method-security annotation on a method have no effect when another method of the same bean calls it directly?

    Method security is applied by a proxy. A direct call inside the same object never passes through it, which is the same self-invocation limit as with @Transactional.

Summary

  • Hash passwords with a slow, salted algorithm (BCrypt via the delegating encoder); never store, log or return them, and never accept a role from a request.
  • HTTP Basic plus a UserDetailsService gives a simple stateless login; return identical answers for unknown users and wrong passwords.
  • Use URL rules for coarse access and method security (@PreAuthorize, @PostAuthorize) for ownership: "admin or owner".
  • 401 means not authenticated, 403 means not allowed; list queries must filter in the database.
  • Method security works through proxies, so avoid self-invocation.
  • Test every rule, especially denials, at the service level, and the HTTP behavior in a web slice.

Next: Project: Bookstore Orders Service.