Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting dropwizard admin page

Tags:

dropwizard

How to authenticate Dropwizard admin portal, so as to restrict normal users from accessing it? Please help

like image 497
Sandy T Avatar asked Oct 20 '12 11:10

Sandy T


2 Answers

In your config, you can set adminUsername and adminPassword under http like so:

http:
  adminUsername: user1234
  adminPassword: pass5678
like image 100
Michael Fairley Avatar answered Oct 24 '22 04:10

Michael Fairley


Newer Jetty versions do not have MappedLoginService, so @Kamil's answer no longer works. I have modified their answer to get it working as of Dropwizard 1.2.2:

public class AdminConstraintSecurityHandler extends ConstraintSecurityHandler {

    private static final String ADMIN_ROLE = "admin";

    public AdminConstraintSecurityHandler(final String userName, final String password) {
        final Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, ADMIN_ROLE);
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[]{ADMIN_ROLE});
        final ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
        setAuthenticator(new BasicAuthenticator());
        addConstraintMapping(cm);
        setLoginService(new AdminLoginService(userName, password));
    }

    public class AdminLoginService extends AbstractLoginService {

        private final UserPrincipal adminPrincipal;
        private final String adminUserName;

        public AdminLoginService(final String userName, final String password) {
            this.adminUserName = Objects.requireNonNull(userName);
            this.adminPrincipal = new UserPrincipal(userName, new Password(Objects.requireNonNull(password)));
        }


        @Override
        protected String[] loadRoleInfo(final UserPrincipal principal) {
            if (adminUserName.equals(principal.getName())) {
                return new String[]{ADMIN_ROLE};
            }
            return new String[0];
        }

        @Override
        protected UserPrincipal loadUserInfo(final String userName) {
            return adminUserName.equals(userName) ? adminPrincipal : null;
        }
    }
}
like image 31
spinlok Avatar answered Oct 24 '22 03:10

spinlok