Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Security

Security Fundamentals and Access Rules

Secure a Micronaut app: the micronaut-security module, @Secured and SecurityRule, role checks, intercept-url-map, anonymous access and a runnable rule-engine stand-in.

Security answers two questions about every request. Authentication: who are you? Authorization: are you allowed to do this? Micronaut Security is a module that handles both with a small set of building blocks, so you declare policy instead of scattering if (user.isAdmin()) checks through your code.

The real module is not available here, so its code is read-only. The runnable examples are Java stand-ins for the decision logic (path rules, roles, first match wins), which is the part worth understanding deeply.

Adding the module

Add the dependency and, importantly, turn on an authentication mechanism in configuration. Without one, the module secures every endpoint but nobody can log in.

GROOVY
annotationProcessor("io.micronaut.security:micronaut-security-annotations")
implementation("io.micronaut.security:micronaut-security")
YAML
micronaut:
  security:
    enabled: true
    authentication: bearer     # or: cookie, session, idtoken

By default, once the module is on the classpath, everything is denied unless a rule allows it. That secure-by-default behaviour is deliberate.

The request pipeline

For each HTTP request a security filter does roughly this:

  1. A token reader extracts credentials (for example the Authorization header).
  2. A token validator turns them into an Authentication (a username plus attributes and roles), or rejects them.
  3. Security rules decide whether this authentication may reach this route.
  4. If a rule allows it, the controller runs; otherwise you get 401 (not authenticated) or 403 (authenticated but forbidden).

Two questions, two status codes

401 Unauthorized We do not know who you are.
403 Forbidden We know you, and the answer is no.

Using the right one helps clients react correctly.

1 / 2

@Secured

The easiest way to state a rule is on the controller or method:

Java
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;

@Controller("/notes")
@Secured(SecurityRule.IS_AUTHENTICATED)           // any logged-in user
class NoteController {

    @Get
    List<Note> list() { /* ... */ }

    @Post
    @Secured("ROLE_EDITOR")                       // only users that have this role
    Note create(@Body NewNote body) { /* ... */ }

    @Get("/public-count")
    @Secured(SecurityRule.IS_ANONYMOUS)           // anyone, even without login
    int count() { /* ... */ }
}

SecurityRule provides three built-in expressions: IS_ANONYMOUS, IS_AUTHENTICATED and DENY_ALL. Any other string is treated as a role name. A method annotation overrides the class annotation, so the most specific rule wins. Prefer the ROLE_ prefix convention for clarity.

Knowing who is calling

Controller methods can receive the current Authentication or a standard java.security.Principal:

Java
@Get("/me")
Map<String, Object> me(Authentication authentication) {
    return Map.of("name", authentication.getName(),
                  "roles", authentication.getRoles());
}

A Principal parameter is null for anonymous callers, so use Authentication together with IS_AUTHENTICATED when the user must exist.

Rules in configuration

Annotations live next to the code. For cross-cutting policy you can also list URL patterns in the configuration, which is handy for static content and health checks:

YAML
micronaut:
  security:
    intercept-url-map:
      - pattern: /health
        access:
          - isAnonymous()
      - pattern: /admin/**
        access:
          - ROLE_ADMIN
      - pattern: /**
        http-method: GET
        access:
          - isAuthenticated()

Patterns are matched in order and the first match wins, so put specific patterns before general ones. Annotation-based rules and the URL map can coexist: all applicable rules are consulted, and a "rejected" verdict from any of them blocks the request, while "unknown" lets the next rule decide.

Try it: a rule engine

This stand-in imitates how rules produce verdicts: ALLOWED, REJECTED or UNKNOWN, with the first non-UNKNOWN answer winning.

Java First matching rule wins

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.

Try it: roles with annotations

Real Micronaut reads @Secured metadata. This stand-in does the same with a runtime annotation on methods, where a method annotation overrides the class one.

Java @Secured on methods

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.

Practical advice

  • Keep the secure-by-default behaviour; open endpoints explicitly with IS_ANONYMOUS.
  • Never trust a role sent by the client. Roles must come from a validated token or your user store.
  • Serve everything over HTTPS in production, and redirect plain HTTP at the load balancer.
  • Keep secrets (signing keys, client secrets) in environment variables, as in Configuration Files and Environments.
  • Log authentication failures without logging the credentials.
  • Remember CORS and CSRF: a token in an Authorization header is not sent automatically by browsers, so it avoids CSRF; a session cookie needs CSRF protection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default behaviour once Micronaut Security is on the classpath?

    The module is secure by default; open routes must be marked explicitly.
  2. 2. A logged-in user without the required role calls an endpoint. What status is correct?

    403 Forbidden means the user is known but not allowed. 401 means unauthenticated.
  3. 3. Which is NOT a built-in SecurityRule expression?

    Roles are plain strings you define, such as ROLE_ADMIN. IS_ADMIN is not built in.
  4. 4. In intercept-url-map, what decides between two matching patterns?

    Patterns are tried in order, so specific ones must come before general ones.

Summary

  • Authentication identifies the caller; authorization decides what they may do.
  • Micronaut Security denies everything by default; @Secured and intercept-url-map open routes deliberately.
  • IS_ANONYMOUS, IS_AUTHENTICATED and role strings are the building blocks; the method annotation beats the class annotation.
  • Respond with 401 for unknown users and 403 for known but forbidden ones.

Next: Authentication Providers