Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support application roles per endpoint #20

Closed
rbygrave opened this issue Jun 1, 2021 · 0 comments
Closed

Support application roles per endpoint #20

rbygrave opened this issue Jun 1, 2021 · 0 comments
Assignees
Milestone

Comments

@rbygrave
Copy link
Contributor

rbygrave commented Jun 1, 2021

1. Create an app specific enum that implements Role

import io.avaje.jex.Role;

/**
 * Create an App specific enum that implements Role.
 */
public enum AppRoles implements Role {
  ADMIN,
  USER
}

2. Create an Roles enum that uses the app specific enum (for use with avaje-http controllers)

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Create an app specific Role annotation that uses the
 * app specific role enum.
 */
@Target(value={METHOD, TYPE})
@Retention(value=RUNTIME)
public @interface Roles {

  /**
   * Specify the permitted roles (using app specific enum).
   */
  AppRoles[] value() default {};
}

3. Use the Role enum on endpoints that we want the user roles check

      .routing(routing -> routing
        .get(ctx -> ctx.text("get"))
        .get("/multi", ctx -> ... ).withRoles(AppRoles.ADMIN, AppRoles.USER)
        .get("/user", ctx -> ... ).withRoles(AppRoles.USER)
      );

4. Implement and register the AccessManager

.accessManager((handler, ctx, permittedRoles) -> {
        final String role = ctx.queryParam("role");
        if (role == null || !permittedRoles.contains(AppRoles.valueOf(role))) {
          ctx.status(401).text("Unauthorized");
        } else {
          ctx.attribute("authBy", role);
          handler.handle(ctx);
        }
      })
@rbygrave rbygrave added this to the 1.5 milestone Jun 1, 2021
@rbygrave rbygrave self-assigned this Jun 1, 2021
@rbygrave rbygrave closed this as completed Jun 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant