How to authenticate Dropwizard admin portal, so as to restrict normal users from accessing it? Please help
In your config, you can set adminUsername and adminPassword under http like so:
http:
  adminUsername: user1234
  adminPassword: pass5678
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;
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With