You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zeppelin.apache.org by jo...@apache.org on 2018/12/04 01:59:53 UTC

[2/2] zeppelin git commit: ZEPPELIN-3892 Make SecurityUtils as a service

ZEPPELIN-3892 Make SecurityUtils as a service

### What is this PR for?
Making SecurityService more configurable. Currently, SecurityUtils consists of static methods, and which means it's not extendable and pluggable. It would be better if users could implement new security features easily.

### What type of PR is it?
[Refactoring]

### Todos
* [x] - Introduce `SecurityService` as an interface to support security features
* [x] - Move `SecurityUtils` to `ShiroSecurityService` as an implementation of `SecurityService`

### What is the Jira issue?
* https://issues.apache.org/jira/browse/ZEPPELIN-3892

### How should this be tested?
* This is a refactoring. It should pass all of the current tests

### Screenshots (if appropriate)

### Questions:
* Does the licenses files need update? No
* Is there breaking changes for older versions? No
* Does this needs documentation? No

Author: Jongyoul Lee <jo...@gmail.com>

Closes #3246 from jongyoul/ZEPPELIN-3892 and squashes the following commits:

70cfb04d5 [Jongyoul Lee] Fix injection information
dab7e64a8 [Jongyoul Lee] Extract two more methods to the interface
74d5d6533 [Jongyoul Lee] Change ShiroSecurityService to SecurityService
ca72b2040 [Jongyoul Lee] Add license
f253cf498 [Jongyoul Lee] Move validation logic for shiro to ShiroSecurityService
37a00d080 [Jongyoul Lee] Add licenses
c5022b2cc [Jongyoul Lee] Introduce an interface of SecurityService to handle issues of securities Change SecurityUtils to ShiroSecurityService Introduce NoSecurityService to divide to handle without shiro configuration


Project: http://git-wip-us.apache.org/repos/asf/zeppelin/repo
Commit: http://git-wip-us.apache.org/repos/asf/zeppelin/commit/354b06f7
Tree: http://git-wip-us.apache.org/repos/asf/zeppelin/tree/354b06f7
Diff: http://git-wip-us.apache.org/repos/asf/zeppelin/diff/354b06f7

Branch: refs/heads/master
Commit: 354b06f7342746ce50cffa5dc886512bfc908922
Parents: f43ba28
Author: Jongyoul Lee <jo...@gmail.com>
Authored: Mon Dec 3 23:36:34 2018 +0900
Committer: Jongyoul Lee <jo...@apache.org>
Committed: Tue Dec 4 10:59:44 2018 +0900

----------------------------------------------------------------------
 .../realm/jwt/KnoxAuthenticationFilter.java     |  46 +-
 .../apache/zeppelin/rest/AbstractRestApi.java   |  21 +-
 .../zeppelin/rest/ConfigurationsRestApi.java    |   5 +-
 .../apache/zeppelin/rest/CredentialRestApi.java |  14 +-
 .../zeppelin/rest/InterpreterRestApi.java       |   7 +-
 .../org/apache/zeppelin/rest/LoginRestApi.java  |  65 ++-
 .../zeppelin/rest/NotebookRepoRestApi.java      |  19 +-
 .../apache/zeppelin/rest/NotebookRestApi.java   | 103 ++--
 .../apache/zeppelin/rest/SecurityRestApi.java   |  61 +--
 .../org/apache/zeppelin/server/CorsFilter.java  |  13 +-
 .../apache/zeppelin/server/ZeppelinServer.java  |  35 +-
 .../zeppelin/service/NoSecurityService.java     |  59 +++
 .../zeppelin/service/SecurityService.java       |  37 ++
 .../zeppelin/service/ShiroSecurityService.java  | 456 ++++++++++++++++++
 .../apache/zeppelin/socket/NotebookServer.java  |   4 +-
 .../org/apache/zeppelin/utils/CorsUtils.java    |  44 ++
 .../apache/zeppelin/utils/SecurityUtils.java    | 474 -------------------
 .../zeppelin/rest/CredentialsRestApiTest.java   |   6 +-
 .../zeppelin/security/SecurityUtilsTest.java    | 165 -------
 .../service/ShiroSecurityServiceTest.java       | 107 +++++
 .../apache/zeppelin/utils/CorsUtilsTest.java    |  95 ++++
 21 files changed, 1001 insertions(+), 835 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxAuthenticationFilter.java b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxAuthenticationFilter.java
index eccf6de..fe312b2 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxAuthenticationFilter.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/realm/jwt/KnoxAuthenticationFilter.java
@@ -16,41 +16,46 @@
  */
 package org.apache.zeppelin.realm.jwt;
 
+import java.util.Collection;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import org.apache.shiro.realm.Realm;
+import org.apache.shiro.util.ThreadContext;
 import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
+import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
 import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-
-import org.apache.zeppelin.utils.SecurityUtils;
-
-/**
- * Created for org.apache.zeppelin.server.
- */
+/** Created for org.apache.zeppelin.server. */
 public class KnoxAuthenticationFilter extends FormAuthenticationFilter {
   private static final Logger LOGGER = LoggerFactory.getLogger(KnoxAuthenticationFilter.class);
 
-  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response,
-          Object mappedValue) {
-    //Check with existing shiro authentication logic
-    //https://github.com/apache/shiro/blob/shiro-root-1.3.2/web/src/main/java/org/apache/shiro/
+  protected boolean isAccessAllowed(
+      ServletRequest request, ServletResponse response, Object mappedValue) {
+    // Check with existing shiro authentication logic
+    // https://github.com/apache/shiro/blob/shiro-root-1.3.2/web/src/main/java/org/apache/shiro/
     // web/filter/authc/AuthenticatingFilter.java#L123-L124
-    Boolean accessAllowed = super.isAccessAllowed(request, response, mappedValue) ||
-            !isLoginRequest(request, response) && isPermissive(mappedValue);
+    boolean accessAllowed =
+        super.isAccessAllowed(request, response, mappedValue)
+            || !isLoginRequest(request, response) && isPermissive(mappedValue);
 
     if (accessAllowed) {
       accessAllowed = false;
       KnoxJwtRealm knoxJwtRealm = null;
-      for (Object realm : SecurityUtils.getRealmsList()) {
+      // TODO(jl): Is this logic really useful?
+      DefaultWebSecurityManager defaultWebSecurityManager;
+      String key = ThreadContext.SECURITY_MANAGER_KEY;
+      defaultWebSecurityManager = (DefaultWebSecurityManager) ThreadContext.get(key);
+      Collection<Realm> realms = defaultWebSecurityManager.getRealms();
+      for (Object realm : realms) {
         if (realm instanceof KnoxJwtRealm) {
           knoxJwtRealm = (KnoxJwtRealm) realm;
           break;
         }
       }
-      if (knoxJwtRealm != null) {
+      if (null != knoxJwtRealm) {
         for (Cookie cookie : ((ShiroHttpServletRequest) request).getCookies()) {
           if (cookie.getName().equals(knoxJwtRealm.getCookieName())) {
             if (knoxJwtRealm.validateToken(cookie.getValue())) {
@@ -60,9 +65,10 @@ public class KnoxAuthenticationFilter extends FormAuthenticationFilter {
           }
         }
       } else {
-        LOGGER.error("Looks like this filter is enabled without enabling KnoxJwtRealm, please refer"
-            + " to https://zeppelin.apache.org/docs/latest/security/shiroauthentication.html"
-            + "#knox-sso");
+        LOGGER.error(
+            "Looks like this filter is enabled without enabling KnoxJwtRealm, please refer"
+                + " to https://zeppelin.apache.org/docs/latest/security/shiroauthentication.html"
+                + "#knox-sso");
       }
     }
     return accessAllowed;

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/AbstractRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/AbstractRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/AbstractRestApi.java
index f4406a2..1729be8 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/AbstractRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/AbstractRestApi.java
@@ -18,22 +18,27 @@
 package org.apache.zeppelin.rest;
 
 import com.google.common.collect.Sets;
+import java.io.IOException;
+import java.util.Set;
+import javax.ws.rs.WebApplicationException;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.service.ServiceContext;
 import org.apache.zeppelin.service.SimpleServiceCallback;
 import org.apache.zeppelin.user.AuthenticationInfo;
-import org.apache.zeppelin.utils.SecurityUtils;
-
-import javax.ws.rs.WebApplicationException;
-import java.io.IOException;
-import java.util.Set;
 
 public class AbstractRestApi {
 
+  protected SecurityService securityService;
+
+  protected AbstractRestApi(SecurityService securityService) {
+    this.securityService = securityService;
+  }
+
   protected ServiceContext getServiceContext() {
-    AuthenticationInfo authInfo = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo authInfo = new AuthenticationInfo(securityService.getPrincipal());
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     return new ServiceContext(authInfo, userAndRoles);
   }
 

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ConfigurationsRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ConfigurationsRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ConfigurationsRestApi.java
index 24b9ce9..140fdf7 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ConfigurationsRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ConfigurationsRestApi.java
@@ -28,6 +28,7 @@ import javax.ws.rs.core.Response.Status;
 import org.apache.zeppelin.annotation.ZeppelinApi;
 import org.apache.zeppelin.server.JsonResponse;
 import org.apache.zeppelin.service.ConfigurationService;
+import org.apache.zeppelin.service.SecurityService;
 
 /** Configurations Rest API Endpoint. */
 @Path("/configurations")
@@ -37,7 +38,9 @@ public class ConfigurationsRestApi extends AbstractRestApi {
   private ConfigurationService configurationService;
 
   @Inject
-  public ConfigurationsRestApi(ConfigurationService configurationService) {
+  public ConfigurationsRestApi(
+      SecurityService securityService, ConfigurationService configurationService) {
+    super(securityService);
     this.configurationService = configurationService;
   }
 

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java
index 372666e..b433572 100755
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java
@@ -32,10 +32,10 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 import org.apache.zeppelin.server.JsonResponse;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.user.Credentials;
 import org.apache.zeppelin.user.UserCredentials;
 import org.apache.zeppelin.user.UsernamePassword;
-import org.apache.zeppelin.utils.SecurityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -45,11 +45,13 @@ import org.slf4j.LoggerFactory;
 public class CredentialRestApi {
   Logger logger = LoggerFactory.getLogger(CredentialRestApi.class);
   private Credentials credentials;
+  private SecurityService securityService;
   private Gson gson = new Gson();
 
   @Inject
-  public CredentialRestApi(Credentials credentials) {
+  public CredentialRestApi(Credentials credentials, SecurityService securityService) {
     this.credentials = credentials;
+    this.securityService = securityService;
   }
 
   /**
@@ -74,7 +76,7 @@ public class CredentialRestApi {
       return new JsonResponse(Status.BAD_REQUEST).build();
     }
 
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     logger.info("Update credentials for user {} entity {}", user, entity);
     UserCredentials uc = credentials.getUserCredentials(user);
     uc.putUsernamePassword(entity, new UsernamePassword(username, password));
@@ -90,7 +92,7 @@ public class CredentialRestApi {
    */
   @GET
   public Response getCredentials() throws IllegalArgumentException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     logger.info("getCredentials credentials for user {} ", user);
     UserCredentials uc = credentials.getUserCredentials(user);
     return new JsonResponse<>(Status.OK, uc).build();
@@ -105,7 +107,7 @@ public class CredentialRestApi {
    */
   @DELETE
   public Response removeCredentials() throws IOException, IllegalArgumentException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     logger.info("removeCredentials credentials for user {} ", user);
     UserCredentials uc = credentials.removeUserCredentials(user);
     if (uc == null) {
@@ -126,7 +128,7 @@ public class CredentialRestApi {
   @Path("{entity}")
   public Response removeCredentialEntity(@PathParam("entity") String entity)
       throws IOException, IllegalArgumentException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     logger.info("removeCredentialEntity for user {} entity {}", user, entity);
     if (!credentials.removeCredentialEntity(user, entity)) {
       return new JsonResponse(Status.NOT_FOUND).build();

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/InterpreterRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/InterpreterRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/InterpreterRestApi.java
index abf7de8..d885114 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/InterpreterRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/InterpreterRestApi.java
@@ -34,10 +34,10 @@ import org.apache.zeppelin.rest.message.RestartInterpreterRequest;
 import org.apache.zeppelin.rest.message.UpdateInterpreterSettingRequest;
 import org.apache.zeppelin.server.JsonResponse;
 import org.apache.zeppelin.service.InterpreterService;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.service.ServiceContext;
 import org.apache.zeppelin.service.SimpleServiceCallback;
 import org.apache.zeppelin.socket.NotebookServer;
-import org.apache.zeppelin.utils.SecurityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonatype.aether.repository.RemoteRepository;
@@ -65,15 +65,18 @@ public class InterpreterRestApi {
 
   private static final Logger logger = LoggerFactory.getLogger(InterpreterRestApi.class);
 
+  private final SecurityService securityService;
   private final InterpreterService interpreterService;
   private final InterpreterSettingManager interpreterSettingManager;
   private final NotebookServer notebookServer;
 
   @Inject
   public InterpreterRestApi(
+      SecurityService securityService,
       InterpreterService interpreterService,
       InterpreterSettingManager interpreterSettingManager,
       NotebookServer notebookWsServer) {
+    this.securityService = securityService;
     this.interpreterService = interpreterService;
     this.interpreterSettingManager = interpreterSettingManager;
     this.notebookServer = notebookWsServer;
@@ -195,7 +198,7 @@ public class InterpreterRestApi {
       if (null == noteId) {
         interpreterSettingManager.close(settingId);
       } else {
-        interpreterSettingManager.restart(settingId, noteId, SecurityUtils.getPrincipal());
+        interpreterSettingManager.restart(settingId, noteId, securityService.getPrincipal());
       }
 
     } catch (InterpreterException e) {

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java
index f13c222..1f11d3e 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java
@@ -17,27 +17,13 @@
 package org.apache.zeppelin.rest;
 
 import com.google.gson.Gson;
-import javax.inject.Inject;
-import org.apache.shiro.authc.AuthenticationException;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.authc.IncorrectCredentialsException;
-import org.apache.shiro.authc.LockedAccountException;
-import org.apache.shiro.authc.UnknownAccountException;
-import org.apache.shiro.authc.UsernamePasswordToken;
-import org.apache.shiro.realm.Realm;
-import org.apache.shiro.subject.Subject;
-import org.apache.zeppelin.conf.ZeppelinConfiguration;
-import org.apache.zeppelin.notebook.Notebook;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import java.text.ParseException;
 import java.util.Collection;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
-
+import java.util.Set;
+import javax.inject.Inject;
 import javax.ws.rs.FormParam;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
@@ -48,14 +34,22 @@ import javax.ws.rs.core.Cookie;
 import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
-
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.realm.Realm;
+import org.apache.shiro.subject.Subject;
 import org.apache.zeppelin.annotation.ZeppelinApi;
+import org.apache.zeppelin.conf.ZeppelinConfiguration;
+import org.apache.zeppelin.notebook.Notebook;
 import org.apache.zeppelin.notebook.NotebookAuthorization;
 import org.apache.zeppelin.realm.jwt.JWTAuthenticationToken;
 import org.apache.zeppelin.realm.jwt.KnoxJwtRealm;
 import org.apache.zeppelin.server.JsonResponse;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.ticket.TicketContainer;
-import org.apache.zeppelin.utils.SecurityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Created for org.apache.zeppelin.rest.message.
@@ -66,10 +60,13 @@ public class LoginRestApi {
   private static final Logger LOG = LoggerFactory.getLogger(LoginRestApi.class);
   private static final Gson gson = new Gson();
   private ZeppelinConfiguration zConf;
+  private SecurityService securityService;
 
   @Inject
-  public LoginRestApi(Notebook notebook) {
+  public LoginRestApi(Notebook notebook,
+      SecurityService securityService) {
     this.zConf = notebook.getConf();
+    this.securityService = securityService;
   }
 
   @GET
@@ -102,7 +99,7 @@ public class LoginRestApi {
   }
 
   private KnoxJwtRealm getJTWRealm() {
-    Collection realmsList = SecurityUtils.getRealmsList();
+    Collection realmsList = securityService.getRealmsList();
     if (realmsList != null) {
       for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
         Realm realm = iterator.next();
@@ -119,7 +116,7 @@ public class LoginRestApi {
   }
 
   private boolean isKnoxSSOEnabled() {
-    Collection realmsList = SecurityUtils.getRealmsList();
+    Collection realmsList = securityService.getRealmsList();
     if (realmsList != null) {
       for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
         Realm realm = iterator.next();
@@ -140,8 +137,8 @@ public class LoginRestApi {
       currentUser.getSession(true);
       currentUser.login(token);
 
-      HashSet<String> roles = SecurityUtils.getAssociatedRoles();
-      String principal = SecurityUtils.getPrincipal();
+      Set<String> roles = securityService.getAssociatedRoles();
+      String principal = securityService.getPrincipal();
       String ticket;
       if ("anonymous".equals(principal)) {
         ticket = "anonymous";
@@ -155,22 +152,16 @@ public class LoginRestApi {
       data.put("ticket", ticket);
 
       response = new JsonResponse(Response.Status.OK, "", data);
-      //if no exception, that's it, we're done!
+      // if no exception, that's it, we're done!
 
-      //set roles for user in NotebookAuthorization module
+      // set roles for user in NotebookAuthorization module
       NotebookAuthorization.getInstance().setRoles(principal, roles);
-    } catch (UnknownAccountException uae) {
-      //username wasn't in the system, show them an error message?
+    } catch (AuthenticationException uae) {
+      // username wasn't in the system, show them an error message?
+      // password didn't match, try again?
+      // account for that username is locked - can't login.  Show them a message?
+      // unexpected condition - error?
       LOG.error("Exception in login: ", uae);
-    } catch (IncorrectCredentialsException ice) {
-      //password didn't match, try again?
-      LOG.error("Exception in login: ", ice);
-    } catch (LockedAccountException lae) {
-      //account for that username is locked - can't login.  Show them a message?
-      LOG.error("Exception in login: ", lae);
-    } catch (AuthenticationException ae) {
-      //unexpected condition - error?
-      LOG.error("Exception in login: ", ae);
     }
     return response;
   }
@@ -246,7 +237,7 @@ public class LoginRestApi {
 
   private void logoutCurrentUser() {
     Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
-    TicketContainer.instance.removeTicket(SecurityUtils.getPrincipal());
+    TicketContainer.instance.removeTicket(securityService.getPrincipal());
     currentUser.getSession().stop();
     currentUser.logout();
   }

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java
index 2615c2f..62f38b9 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java
@@ -22,6 +22,7 @@ import com.google.gson.JsonSyntaxException;
 
 import javax.inject.Inject;
 import org.apache.commons.lang.StringUtils;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.service.ServiceContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -45,7 +46,6 @@ import org.apache.zeppelin.rest.message.NotebookRepoSettingsRequest;
 import org.apache.zeppelin.server.JsonResponse;
 import org.apache.zeppelin.socket.NotebookServer;
 import org.apache.zeppelin.user.AuthenticationInfo;
-import org.apache.zeppelin.utils.SecurityUtils;
 
 /**
  * NoteRepo rest API endpoint.
@@ -58,11 +58,14 @@ public class NotebookRepoRestApi {
 
   private NotebookRepoSync noteRepos;
   private NotebookServer notebookWsServer;
+  private SecurityService securityService;
 
   @Inject
-  public NotebookRepoRestApi(NotebookRepoSync noteRepos, NotebookServer notebookWsServer) {
+  public NotebookRepoRestApi(NotebookRepoSync noteRepos, NotebookServer notebookWsServer,
+      SecurityService securityService) {
     this.noteRepos = noteRepos;
     this.notebookWsServer = notebookWsServer;
+    this.securityService = securityService;
   }
 
   /**
@@ -71,7 +74,7 @@ public class NotebookRepoRestApi {
   @GET
   @ZeppelinApi
   public Response listRepoSettings() {
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     LOG.info("Getting list of NoteRepo with Settings for user {}", subject.getUser());
     List<NotebookRepoWithSettings> settings = noteRepos.getNotebookRepos(subject);
     return new JsonResponse<>(Status.OK, "", settings).build();
@@ -84,7 +87,7 @@ public class NotebookRepoRestApi {
   @Path("reload")
   @ZeppelinApi
   public Response refreshRepo(){
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     LOG.info("Reloading notebook repository for user {}", subject.getUser());
     try {
       notebookWsServer.broadcastReloadedNoteList(null, getServiceContext());
@@ -95,10 +98,10 @@ public class NotebookRepoRestApi {
   }
 
   private ServiceContext getServiceContext() {
-    AuthenticationInfo authInfo = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo authInfo = new AuthenticationInfo(securityService.getPrincipal());
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     return new ServiceContext(authInfo, userAndRoles);
   }
 
@@ -114,7 +117,7 @@ public class NotebookRepoRestApi {
     if (StringUtils.isBlank(payload)) {
       return new JsonResponse<>(Status.NOT_FOUND, "", Collections.emptyMap()).build();
     }
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     NotebookRepoSettingsRequest newSettings;
     try {
       newSettings = NotebookRepoSettingsRequest.fromJson(payload);

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRestApi.java
index 54150de..cd449c5 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRestApi.java
@@ -20,7 +20,24 @@ package org.apache.zeppelin.rest;
 import com.google.common.collect.Sets;
 import com.google.common.reflect.TypeToken;
 import com.google.gson.Gson;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import javax.inject.Inject;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.zeppelin.annotation.ZeppelinApi;
 import org.apache.zeppelin.conf.ZeppelinConfiguration;
@@ -44,32 +61,14 @@ import org.apache.zeppelin.search.SearchService;
 import org.apache.zeppelin.server.JsonResponse;
 import org.apache.zeppelin.service.JobManagerService;
 import org.apache.zeppelin.service.NotebookService;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.service.ServiceContext;
 import org.apache.zeppelin.socket.NotebookServer;
 import org.apache.zeppelin.user.AuthenticationInfo;
-import org.apache.zeppelin.utils.SecurityUtils;
 import org.quartz.CronExpression;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
 /**
  * Rest api endpoint for the notebook.
  */
@@ -86,6 +85,7 @@ public class NotebookRestApi extends AbstractRestApi {
   private NotebookAuthorization notebookAuthorization;
   private NotebookService notebookService;
   private JobManagerService jobManagerService;
+  private SecurityService securityService;
 
   @Inject
   public NotebookRestApi(
@@ -94,7 +94,9 @@ public class NotebookRestApi extends AbstractRestApi {
       NotebookService notebookService,
       SearchService search,
       NotebookAuthorization notebookAuthorization,
-      ZeppelinConfiguration zConf) {
+      ZeppelinConfiguration zConf,
+      SecurityService securityService) {
+    super(securityService);
     this.notebook = notebook;
     this.notebookServer = notebookServer;
     this.notebookService = notebookService;
@@ -102,6 +104,7 @@ public class NotebookRestApi extends AbstractRestApi {
     this.noteSearchService = search;
     this.notebookAuthorization = notebookAuthorization;
     this.zConf = zConf;
+    this.securityService = securityService;
   }
 
   /**
@@ -144,8 +147,8 @@ public class NotebookRestApi extends AbstractRestApi {
    * Check if the current user is not authenticated(anonymous user) or not.
    */
   private void checkIfUserIsAnon(String errorMsg) {
-    boolean isAuthenticated = SecurityUtils.isAuthenticated();
-    if (isAuthenticated && SecurityUtils.getPrincipal().equals("anonymous")) {
+    boolean isAuthenticated = securityService.isAuthenticated();
+    if (isAuthenticated && securityService.getPrincipal().equals("anonymous")) {
       LOG.info("Anonymous user cannot set any permissions for this note.");
       throw new ForbiddenException(errorMsg);
     }
@@ -156,8 +159,8 @@ public class NotebookRestApi extends AbstractRestApi {
    */
   private void checkIfUserIsOwner(String noteId, String errorMsg) {
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     if (!notebookAuthorization.isOwner(userAndRoles, noteId)) {
       throw new ForbiddenException(errorMsg);
     }
@@ -168,8 +171,8 @@ public class NotebookRestApi extends AbstractRestApi {
    */
   private void checkIfUserCanWrite(String noteId, String errorMsg) {
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     if (!notebookAuthorization.hasWriteAuthorization(userAndRoles, noteId)) {
       throw new ForbiddenException(errorMsg);
     }
@@ -180,8 +183,8 @@ public class NotebookRestApi extends AbstractRestApi {
    */
   private void checkIfUserCanRead(String noteId, String errorMsg) {
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     if (!notebookAuthorization.hasReadAuthorization(userAndRoles, noteId)) {
       throw new ForbiddenException(errorMsg);
     }
@@ -192,8 +195,8 @@ public class NotebookRestApi extends AbstractRestApi {
    */
   private void checkIfUserCanRun(String noteId, String errorMsg) {
     Set<String> userAndRoles = Sets.newHashSet();
-    userAndRoles.add(SecurityUtils.getPrincipal());
-    userAndRoles.addAll(SecurityUtils.getAssociatedRoles());
+    userAndRoles.add(securityService.getPrincipal());
+    userAndRoles.addAll(securityService.getAssociatedRoles());
     if (!notebookAuthorization.hasRunAuthorization(userAndRoles, noteId)) {
       throw new ForbiddenException(errorMsg);
     }
@@ -226,8 +229,8 @@ public class NotebookRestApi extends AbstractRestApi {
   @ZeppelinApi
   public Response putNotePermissions(@PathParam("noteId") String noteId, String req)
       throws IOException {
-    String principal = SecurityUtils.getPrincipal();
-    HashSet<String> roles = SecurityUtils.getAssociatedRoles();
+    String principal = securityService.getPrincipal();
+    Set<String> roles = securityService.getAssociatedRoles();
     HashSet<String> userAndRoles = new HashSet<>();
     userAndRoles.add(principal);
     userAndRoles.addAll(roles);
@@ -251,28 +254,28 @@ public class NotebookRestApi extends AbstractRestApi {
     // Set readers, if runners, writers and owners is empty -> set to user requesting the change
     if (readers != null && !readers.isEmpty()) {
       if (runners.isEmpty()) {
-        runners = Sets.newHashSet(SecurityUtils.getPrincipal());
+        runners = Sets.newHashSet(securityService.getPrincipal());
       }
       if (writers.isEmpty()) {
-        writers = Sets.newHashSet(SecurityUtils.getPrincipal());
+        writers = Sets.newHashSet(securityService.getPrincipal());
       }
       if (owners.isEmpty()) {
-        owners = Sets.newHashSet(SecurityUtils.getPrincipal());
+        owners = Sets.newHashSet(securityService.getPrincipal());
       }
     }
     // Set runners, if writers and owners is empty -> set to user requesting the change
     if (runners != null && !runners.isEmpty()) {
       if (writers.isEmpty()) {
-        writers = Sets.newHashSet(SecurityUtils.getPrincipal());
+        writers = Sets.newHashSet(securityService.getPrincipal());
       }
       if (owners.isEmpty()) {
-        owners = Sets.newHashSet(SecurityUtils.getPrincipal());
+        owners = Sets.newHashSet(securityService.getPrincipal());
       }
     }
     // Set writers, if owners is empty -> set to user requesting the change
     if (writers != null && !writers.isEmpty()) {
       if (owners.isEmpty()) {
-        owners = Sets.newHashSet(SecurityUtils.getPrincipal());
+        owners = Sets.newHashSet(securityService.getPrincipal());
       }
     }
 
@@ -283,7 +286,7 @@ public class NotebookRestApi extends AbstractRestApi {
     LOG.debug("After set permissions {} {} {} {}", notebookAuthorization.getOwners(noteId),
         notebookAuthorization.getReaders(noteId), notebookAuthorization.getRunners(noteId),
         notebookAuthorization.getWriters(noteId));
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     notebook.saveNote(note, subject);
     notebookServer.broadcastNote(note);
     notebookServer.broadcastNoteList(subject, userAndRoles);
@@ -349,7 +352,7 @@ public class NotebookRestApi extends AbstractRestApi {
   @POST
   @ZeppelinApi
   public Response createNote(String message) throws IOException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     LOG.info("Create new note by JSON {}", message);
     NewNoteRequest request = NewNoteRequest.fromJson(message);
     Note note = notebookService.createNote(
@@ -357,7 +360,7 @@ public class NotebookRestApi extends AbstractRestApi {
         zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_GROUP_DEFAULT),
         getServiceContext(),
         new RestServiceCallback<>());
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     if (request.getParagraphs() != null) {
       for (NewParagraphRequest paragraphRequest : request.getParagraphs()) {
         Paragraph p = note.addNewParagraph(subject);
@@ -412,7 +415,7 @@ public class NotebookRestApi extends AbstractRestApi {
     if (request != null) {
       newNoteName = request.getName();
     }
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
     Note newNote = notebookService.cloneNote(noteId, newNoteName, getServiceContext(),
         new RestServiceCallback<Note>(){
           @Override
@@ -466,7 +469,7 @@ public class NotebookRestApi extends AbstractRestApi {
   @ZeppelinApi
   public Response insertParagraph(@PathParam("noteId") String noteId, String message)
       throws IOException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     LOG.info("insert paragraph {} {}", noteId, message);
 
     Note note = notebook.getNote(noteId);
@@ -523,7 +526,7 @@ public class NotebookRestApi extends AbstractRestApi {
   public Response updateParagraph(@PathParam("noteId") String noteId,
                                   @PathParam("paragraphId") String paragraphId,
                                   String message) throws IOException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     LOG.info("{} will update paragraph {} {}", user, noteId, paragraphId);
 
     Note note = notebook.getNote(noteId);
@@ -551,7 +554,7 @@ public class NotebookRestApi extends AbstractRestApi {
   public Response updateParagraphConfig(@PathParam("noteId") String noteId,
                                         @PathParam("paragraphId") String paragraphId,
                                         String message) throws IOException {
-    String user = SecurityUtils.getPrincipal();
+    String user = securityService.getPrincipal();
     LOG.info("{} will update paragraph config {} {}", user, noteId, paragraphId);
 
     Note note = notebook.getNote(noteId);
@@ -652,8 +655,8 @@ public class NotebookRestApi extends AbstractRestApi {
     boolean blocking = waitToFinish == null || waitToFinish;
     LOG.info("run note jobs {} waitToFinish: {}", noteId, blocking);
     Note note = notebook.getNote(noteId);
-    AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
-    subject.setRoles(new LinkedList<>(SecurityUtils.getAssociatedRoles()));
+    AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
+    subject.setRoles(new LinkedList<>(securityService.getAssociatedRoles()));
     checkIfNoteIsNotNull(note);
     checkIfUserCanRun(noteId, "Insufficient privileges you cannot run job for this note");
 
@@ -980,8 +983,8 @@ public class NotebookRestApi extends AbstractRestApi {
   @ZeppelinApi
   public Response search(@QueryParam("q") String queryTerm) {
     LOG.info("Searching notes for: {}", queryTerm);
-    String principal = SecurityUtils.getPrincipal();
-    HashSet<String> roles = SecurityUtils.getAssociatedRoles();
+    String principal = securityService.getPrincipal();
+    Set<String> roles = securityService.getAssociatedRoles();
     HashSet<String> userAndRoles = new HashSet<>();
     userAndRoles.add(principal);
     userAndRoles.addAll(roles);
@@ -1011,7 +1014,7 @@ public class NotebookRestApi extends AbstractRestApi {
       Map<String, Object> paramsForUpdating = request.getParams();
       if (paramsForUpdating != null) {
         paragraph.settings.getParams().putAll(paramsForUpdating);
-        AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
+        AuthenticationInfo subject = new AuthenticationInfo(securityService.getPrincipal());
         notebook.saveNote(note, subject);
       }
     }

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java
index 45b76fa..d6cee2e 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java
@@ -17,28 +17,27 @@
 package org.apache.zeppelin.rest;
 
 import com.google.gson.Gson;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.zeppelin.annotation.ZeppelinApi;
 import org.apache.zeppelin.conf.ZeppelinConfiguration;
 import org.apache.zeppelin.server.JsonResponse;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.ticket.TicketContainer;
-import org.apache.zeppelin.utils.SecurityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
 /**
  * Zeppelin security rest api endpoint.
  */
@@ -48,6 +47,13 @@ public class SecurityRestApi {
   private static final Logger LOG = LoggerFactory.getLogger(SecurityRestApi.class);
   private static final Gson gson = new Gson();
 
+  private final SecurityService securityService;
+
+  @Inject
+  public SecurityRestApi(SecurityService securityService) {
+    this.securityService = securityService;
+  }
+
   /**
    * Get ticket
    * Returns username & ticket
@@ -61,8 +67,8 @@ public class SecurityRestApi {
   @ZeppelinApi
   public Response ticket() {
     ZeppelinConfiguration conf = ZeppelinConfiguration.create();
-    String principal = SecurityUtils.getPrincipal();
-    HashSet<String> roles = SecurityUtils.getAssociatedRoles();
+    String principal = securityService.getPrincipal();
+    Set<String> roles = securityService.getAssociatedRoles();
     JsonResponse response;
     // ticket set to anonymous for anonymous user. Simplify testing.
     String ticket;
@@ -94,24 +100,23 @@ public class SecurityRestApi {
   public Response getUserList(@PathParam("searchText") final String searchText) {
 
     final int numUsersToFetch = 5;
-    List<String> usersList = SecurityUtils.getMatchedUsers(searchText, numUsersToFetch);
-    List<String> rolesList = SecurityUtils.getMatchedRoles();
+    List<String> usersList = securityService.getMatchedUsers(searchText, numUsersToFetch);
+    List<String> rolesList = securityService.getMatchedRoles();
 
     List<String> autoSuggestUserList = new ArrayList<>();
     List<String> autoSuggestRoleList = new ArrayList<>();
     Collections.sort(usersList);
     Collections.sort(rolesList);
-    Collections.sort(usersList, new Comparator<String>() {
-      @Override
-      public int compare(String o1, String o2) {
-        if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
+    Collections.sort(
+        usersList,
+        (o1, o2) -> {
+          if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
+            return 0;
+          } else if (o1.matches(searchText + "(.*)")) {
+            return -1;
+          }
           return 0;
-        } else if (o1.matches(searchText + "(.*)")) {
-          return -1;
-        }
-        return 0;
-      }
-    });
+        });
     int maxLength = 0;
     for (String user : usersList) {
       if (StringUtils.containsIgnoreCase(user, searchText)) {

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java b/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java
index efbd8c5..67ada6a 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java
@@ -16,12 +16,8 @@
  */
 package org.apache.zeppelin.server;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import java.io.IOException;
 import java.net.URISyntaxException;
-
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
@@ -30,9 +26,10 @@ import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-
 import org.apache.zeppelin.conf.ZeppelinConfiguration;
-import org.apache.zeppelin.utils.SecurityUtils;
+import org.apache.zeppelin.utils.CorsUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Cors filter.
@@ -47,7 +44,7 @@ public class CorsFilter implements Filter {
     String origin = "";
 
     try {
-      if (SecurityUtils.isValidOrigin(sourceHost, ZeppelinConfiguration.create())) {
+      if (CorsUtils.isValidOrigin(sourceHost, ZeppelinConfiguration.create())) {
         origin = sourceHost;
       }
     } catch (URISyntaxException e) {
@@ -85,5 +82,5 @@ public class CorsFilter implements Filter {
   public void destroy() {}
 
   @Override
-  public void init(FilterConfig filterConfig) throws ServletException {}
+  public void init(FilterConfig filterConfig) {}
 }

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/server/ZeppelinServer.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/server/ZeppelinServer.java b/zeppelin-server/src/main/java/org/apache/zeppelin/server/ZeppelinServer.java
index 9c680ba..e5724f8 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/server/ZeppelinServer.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/server/ZeppelinServer.java
@@ -55,10 +55,12 @@ import org.apache.zeppelin.search.SearchService;
 import org.apache.zeppelin.service.AdminService;
 import org.apache.zeppelin.service.ConfigurationService;
 import org.apache.zeppelin.service.InterpreterService;
+import org.apache.zeppelin.service.NoSecurityService;
 import org.apache.zeppelin.service.NotebookService;
+import org.apache.zeppelin.service.SecurityService;
 import org.apache.zeppelin.socket.NotebookServer;
 import org.apache.zeppelin.user.Credentials;
-import org.apache.zeppelin.utils.SecurityUtils;
+import org.apache.zeppelin.service.ShiroSecurityService;
 import org.eclipse.jetty.http.HttpVersion;
 import org.eclipse.jetty.server.HttpConfiguration;
 import org.eclipse.jetty.server.HttpConnectionFactory;
@@ -102,29 +104,6 @@ public class ZeppelinServer extends ResourceConfig {
   @Inject
   public ZeppelinServer(ServiceLocator serviceLocator) throws Exception {
     ZeppelinConfiguration conf = ZeppelinConfiguration.create();
-    if (conf.getShiroPath().length() > 0) {
-      try {
-        Collection<Realm> realms =
-            ((DefaultWebSecurityManager) org.apache.shiro.SecurityUtils.getSecurityManager())
-                .getRealms();
-        if (realms.size() > 1) {
-          Boolean isIniRealmEnabled = false;
-          for (Object realm : realms) {
-            if (realm instanceof IniRealm && ((IniRealm) realm).getIni().get("users") != null) {
-              isIniRealmEnabled = true;
-              break;
-            }
-          }
-          if (isIniRealmEnabled) {
-            throw new Exception(
-                "IniRealm/password based auth mechanisms should be exclusive. "
-                    + "Consider removing [users] block from shiro.ini");
-          }
-        }
-      } catch (UnavailableSecurityManagerException e) {
-        LOG.error("Failed to initialise shiro configuraion", e);
-      }
-    }
 
     InterpreterOutput.limit = conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT);
 
@@ -242,6 +221,13 @@ public class ZeppelinServer extends ResourceConfig {
             bind(notebookAuthorization).to(NotebookAuthorization.class).in(Singleton.class);
             bind(ConfigurationService.class).to(ConfigurationService.class).in(Immediate.class);
             bind(NotebookService.class).to(NotebookService.class).in(Immediate.class);
+            // TODO(jl): Will make it more beautiful
+            if (!StringUtils.isBlank(conf.getShiroPath())) {
+              bind(ShiroSecurityService.class).to(SecurityService.class).in(Singleton.class);
+            } else {
+              // TODO(jl): Will be added more type
+              bind(NoSecurityService.class).to(SecurityService.class).in(Singleton.class);
+            }
           }
         });
     packages("org.apache.zeppelin.rest");
@@ -417,7 +403,6 @@ public class ZeppelinServer extends ResourceConfig {
     String shiroIniPath = conf.getShiroPath();
     if (!StringUtils.isBlank(shiroIniPath)) {
       webapp.setInitParameter("shiroConfigLocations", new File(shiroIniPath).toURI().toString());
-      SecurityUtils.setIsEnabled(true);
       webapp
           .addFilter(ShiroFilter.class, "/api/*", EnumSet.allOf(DispatcherType.class))
           .setInitParameter("staticSecurityManagerEnabled", "true");

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/service/NoSecurityService.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/NoSecurityService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NoSecurityService.java
new file mode 100644
index 0000000..ab8d4c3
--- /dev/null
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/NoSecurityService.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zeppelin.service;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+public class NoSecurityService implements SecurityService {
+  private final String ANONYMOUS = "anonymous";
+
+  @Override
+  public String getPrincipal() {
+    return ANONYMOUS;
+  }
+
+  @Override
+  public Set<String> getAssociatedRoles() {
+    return Sets.newHashSet();
+  }
+
+  @Override
+  public Collection getRealmsList() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  public boolean isAuthenticated() {
+    return false;
+  }
+
+  @Override
+  public List<String> getMatchedUsers(String searchText, int numUsersToFetch) {
+    return Lists.newArrayList();
+  }
+
+  @Override
+  public List<String> getMatchedRoles() {
+    return Lists.newArrayList();
+  }
+}

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/service/SecurityService.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/SecurityService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/SecurityService.java
new file mode 100644
index 0000000..0f6ab95
--- /dev/null
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/SecurityService.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.zeppelin.service;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+public interface SecurityService {
+
+  String getPrincipal();
+
+  Set<String> getAssociatedRoles();
+
+  Collection getRealmsList();
+
+  boolean isAuthenticated();
+
+  List<String> getMatchedUsers(String searchText, int numUsersToFetch);
+
+  List<String> getMatchedRoles();
+}

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/service/ShiroSecurityService.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/service/ShiroSecurityService.java b/zeppelin-server/src/main/java/org/apache/zeppelin/service/ShiroSecurityService.java
new file mode 100644
index 0000000..ac8f721
--- /dev/null
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/service/ShiroSecurityService.java
@@ -0,0 +1,456 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.zeppelin.service;
+
+import com.google.common.collect.Lists;
+import java.security.Principal;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.LdapContext;
+import javax.sql.DataSource;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.shiro.UnavailableSecurityManagerException;
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.realm.Realm;
+import org.apache.shiro.realm.jdbc.JdbcRealm;
+import org.apache.shiro.realm.ldap.JndiLdapContextFactory;
+import org.apache.shiro.realm.ldap.JndiLdapRealm;
+import org.apache.shiro.realm.text.IniRealm;
+import org.apache.shiro.subject.SimplePrincipalCollection;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.JdbcUtils;
+import org.apache.shiro.util.ThreadContext;
+import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
+import org.apache.zeppelin.conf.ZeppelinConfiguration;
+import org.apache.zeppelin.realm.ActiveDirectoryGroupRealm;
+import org.apache.zeppelin.realm.LdapRealm;
+import org.apache.zeppelin.server.ZeppelinServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Tools for securing Zeppelin. */
+public class ShiroSecurityService implements SecurityService {
+
+  private final Logger LOGGER = LoggerFactory.getLogger(ShiroSecurityService.class);
+
+  @Inject
+  public ShiroSecurityService(ZeppelinConfiguration zeppelinConfiguration) throws Exception {
+    if (zeppelinConfiguration.getShiroPath().length() > 0) {
+      try {
+        Collection<Realm> realms =
+            ((DefaultWebSecurityManager) org.apache.shiro.SecurityUtils.getSecurityManager())
+                .getRealms();
+        if (realms.size() > 1) {
+          Boolean isIniRealmEnabled = false;
+          for (Object realm : realms) {
+            if (realm instanceof IniRealm && ((IniRealm) realm).getIni().get("users") != null) {
+              isIniRealmEnabled = true;
+              break;
+            }
+          }
+          if (isIniRealmEnabled) {
+            throw new Exception(
+                "IniRealm/password based auth mechanisms should be exclusive. "
+                    + "Consider removing [users] block from shiro.ini");
+          }
+        }
+      } catch (UnavailableSecurityManagerException e) {
+        LOGGER.error("Failed to initialise shiro configuraion", e);
+      }
+    }
+  }
+
+  /**
+   * Return the authenticated user if any otherwise returns "anonymous".
+   *
+   * @return shiro principal
+   */
+  @Override
+  public String getPrincipal() {
+    Subject subject = org.apache.shiro.SecurityUtils.getSubject();
+
+    String principal;
+    if (subject.isAuthenticated()) {
+      principal = extractPrincipal(subject);
+      if (ZeppelinServer.notebook.getConf().isUsernameForceLowerCase()) {
+        LOGGER.debug(
+            "Converting principal name " + principal + " to lower case:" + principal.toLowerCase());
+        principal = principal.toLowerCase();
+      }
+    } else {
+      // TODO(jl): Could be better to occur error?
+      principal = "anonymous";
+    }
+    return principal;
+  }
+
+  private String extractPrincipal(Subject subject) {
+    String principal;
+    Object principalObject = subject.getPrincipal();
+    if (principalObject instanceof Principal) {
+      principal = ((Principal) principalObject).getName();
+    } else {
+      principal = String.valueOf(principalObject);
+    }
+    return principal;
+  }
+
+  @Override
+  public Collection getRealmsList() {
+    DefaultWebSecurityManager defaultWebSecurityManager;
+    String key = ThreadContext.SECURITY_MANAGER_KEY;
+    defaultWebSecurityManager = (DefaultWebSecurityManager) ThreadContext.get(key);
+    return defaultWebSecurityManager.getRealms();
+  }
+
+  /** Checked if shiro enabled or not. */
+  @Override
+  public boolean isAuthenticated() {
+    return org.apache.shiro.SecurityUtils.getSubject().isAuthenticated();
+  }
+
+  /**
+   * Get candidated users based on searchText
+   *
+   * @param searchText
+   * @param numUsersToFetch
+   * @return
+   */
+  @Override
+  public List<String> getMatchedUsers(String searchText, int numUsersToFetch) {
+    List<String> usersList = new ArrayList<>();
+    try {
+      Collection<Realm> realmsList = (Collection<Realm>) getRealmsList();
+      if (realmsList != null) {
+        for (Realm realm : realmsList) {
+          String name = realm.getClass().getName();
+          LOGGER.debug("RealmClass.getName: " + name);
+          if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
+            usersList.addAll(getUserList((IniRealm) realm));
+          } else if (name.equals("org.apache.zeppelin.realm.LdapGroupRealm")) {
+            usersList.addAll(getUserList((JndiLdapRealm) realm, searchText, numUsersToFetch));
+          } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
+            usersList.addAll(getUserList((LdapRealm) realm, searchText, numUsersToFetch));
+          } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
+            usersList.addAll(
+                getUserList((ActiveDirectoryGroupRealm) realm, searchText, numUsersToFetch));
+          } else if (name.equals("org.apache.shiro.realm.jdbc.JdbcRealm")) {
+            usersList.addAll(getUserList((JdbcRealm) realm));
+          }
+        }
+      }
+    } catch (Exception e) {
+      LOGGER.error("Exception in retrieving Users from realms ", e);
+    }
+    return usersList;
+  }
+
+  /**
+   * Get matched roles.
+   *
+   * @return
+   */
+  @Override
+  public List<String> getMatchedRoles() {
+    List<String> rolesList = new ArrayList<>();
+    try {
+      Collection realmsList = getRealmsList();
+      if (realmsList != null) {
+        for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
+          Realm realm = iterator.next();
+          String name = realm.getClass().getName();
+          LOGGER.debug("RealmClass.getName: " + name);
+          if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
+            rolesList.addAll(getRolesList((IniRealm) realm));
+          } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
+            rolesList.addAll(getRolesList((LdapRealm) realm));
+          }
+        }
+      }
+    } catch (Exception e) {
+      LOGGER.error("Exception in retrieving Users from realms ", e);
+    }
+    return rolesList;
+  }
+
+  /**
+   * Return the roles associated with the authenticated user if any otherwise returns empty set.
+   * TODO(prasadwagle) Find correct way to get user roles (see SHIRO-492)
+   *
+   * @return shiro roles
+   */
+  @Override
+  public Set<String> getAssociatedRoles() {
+    Subject subject = org.apache.shiro.SecurityUtils.getSubject();
+    HashSet<String> roles = new HashSet<>();
+    Map allRoles = null;
+
+    if (subject.isAuthenticated()) {
+      Collection realmsList = getRealmsList();
+      for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
+        Realm realm = iterator.next();
+        String name = realm.getClass().getName();
+        if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
+          allRoles = ((IniRealm) realm).getIni().get("roles");
+          break;
+        } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
+          try {
+            AuthorizationInfo auth =
+                ((LdapRealm) realm)
+                    .queryForAuthorizationInfo(
+                        new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()),
+                        ((LdapRealm) realm).getContextFactory());
+            if (auth != null) {
+              roles = new HashSet<>(auth.getRoles());
+            }
+          } catch (NamingException e) {
+            LOGGER.error("Can't fetch roles", e);
+          }
+          break;
+        } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
+          allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles();
+          break;
+        }
+      }
+      if (allRoles != null) {
+        Iterator it = allRoles.entrySet().iterator();
+        while (it.hasNext()) {
+          Map.Entry pair = (Map.Entry) it.next();
+          if (subject.hasRole((String) pair.getKey())) {
+            roles.add((String) pair.getKey());
+          }
+        }
+      }
+    }
+    return roles;
+  }
+
+  /** Function to extract users from shiro.ini. */
+  private List<String> getUserList(IniRealm r) {
+    List<String> userList = new ArrayList<>();
+    Map getIniUser = r.getIni().get("users");
+    if (getIniUser != null) {
+      Iterator it = getIniUser.entrySet().iterator();
+      while (it.hasNext()) {
+        Map.Entry pair = (Map.Entry) it.next();
+        userList.add(pair.getKey().toString().trim());
+      }
+    }
+    return userList;
+  }
+
+  /**
+   * * Get user roles from shiro.ini.
+   *
+   * @param r
+   * @return
+   */
+  private List<String> getRolesList(IniRealm r) {
+    List<String> roleList = new ArrayList<>();
+    Map getIniRoles = r.getIni().get("roles");
+    if (getIniRoles != null) {
+      Iterator it = getIniRoles.entrySet().iterator();
+      while (it.hasNext()) {
+        Map.Entry pair = (Map.Entry) it.next();
+        roleList.add(pair.getKey().toString().trim());
+      }
+    }
+    return roleList;
+  }
+
+  /** Function to extract users from LDAP. */
+  private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
+    List<String> userList = new ArrayList<>();
+    String userDnTemplate = r.getUserDnTemplate();
+    String userDn[] = userDnTemplate.split(",", 2);
+    String userDnPrefix = userDn[0].split("=")[0];
+    String userDnSuffix = userDn[1];
+    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
+    try {
+      LdapContext ctx = cf.getSystemLdapContext();
+      SearchControls constraints = new SearchControls();
+      constraints.setCountLimit(numUsersToFetch);
+      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
+      String[] attrIDs = {userDnPrefix};
+      constraints.setReturningAttributes(attrIDs);
+      NamingEnumeration result =
+          ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints);
+      while (result.hasMore()) {
+        Attributes attrs = ((SearchResult) result.next()).getAttributes();
+        if (attrs.get(userDnPrefix) != null) {
+          String currentUser = attrs.get(userDnPrefix).toString();
+          userList.add(currentUser.split(":")[1].trim());
+        }
+      }
+    } catch (Exception e) {
+      LOGGER.error("Error retrieving User list from Ldap Realm", e);
+    }
+    LOGGER.info("UserList: " + userList);
+    return userList;
+  }
+
+  /** Function to extract users from Zeppelin LdapRealm. */
+  private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
+    List<String> userList = new ArrayList<>();
+    LOGGER.debug("SearchText: " + searchText);
+    String userAttribute = r.getUserSearchAttributeName();
+    String userSearchRealm = r.getUserSearchBase();
+    String userObjectClass = r.getUserObjectClass();
+    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
+    try {
+      LdapContext ctx = cf.getSystemLdapContext();
+      SearchControls constraints = new SearchControls();
+      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
+      constraints.setCountLimit(numUsersToFetch);
+      String[] attrIDs = {userAttribute};
+      constraints.setReturningAttributes(attrIDs);
+      NamingEnumeration result =
+          ctx.search(
+              userSearchRealm,
+              "(&(objectclass="
+                  + userObjectClass
+                  + ")("
+                  + userAttribute
+                  + "=*"
+                  + searchText
+                  + "*))",
+              constraints);
+      while (result.hasMore()) {
+        Attributes attrs = ((SearchResult) result.next()).getAttributes();
+        if (attrs.get(userAttribute) != null) {
+          String currentUser;
+          if (r.getUserLowerCase()) {
+            LOGGER.debug("userLowerCase true");
+            currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
+          } else {
+            LOGGER.debug("userLowerCase false");
+            currentUser = (String) attrs.get(userAttribute).get();
+          }
+          LOGGER.debug("CurrentUser: " + currentUser);
+          userList.add(currentUser.trim());
+        }
+      }
+    } catch (Exception e) {
+      LOGGER.error("Error retrieving User list from Ldap Realm", e);
+    }
+    return userList;
+  }
+
+  /**
+   * * Get user roles from shiro.ini for Zeppelin LdapRealm.
+   *
+   * @param r
+   * @return
+   */
+  private List<String> getRolesList(LdapRealm r) {
+    List<String> roleList = new ArrayList<>();
+    Map<String, String> roles = r.getListRoles();
+    if (roles != null) {
+      Iterator it = roles.entrySet().iterator();
+      while (it.hasNext()) {
+        Map.Entry pair = (Map.Entry) it.next();
+        LOGGER.debug("RoleKeyValue: " + pair.getKey() + " = " + pair.getValue());
+        roleList.add((String) pair.getKey());
+      }
+    }
+    return roleList;
+  }
+
+  private List<String> getUserList(
+      ActiveDirectoryGroupRealm r, String searchText, int numUsersToFetch) {
+    List<String> userList = new ArrayList<>();
+    try {
+      LdapContext ctx = r.getLdapContextFactory().getSystemLdapContext();
+      userList = r.searchForUserName(searchText, ctx, numUsersToFetch);
+    } catch (Exception e) {
+      LOGGER.error("Error retrieving User list from ActiveDirectory Realm", e);
+    }
+    return userList;
+  }
+
+  /** Function to extract users from JDBCs. */
+  private List<String> getUserList(JdbcRealm obj) {
+    List<String> userlist = new ArrayList<>();
+    Connection con = null;
+    PreparedStatement ps = null;
+    ResultSet rs = null;
+    DataSource dataSource = null;
+    String authQuery = "";
+    String retval[];
+    String tablename = "";
+    String username = "";
+    String userquery;
+    try {
+      dataSource = (DataSource) FieldUtils.readField(obj, "dataSource", true);
+      authQuery = (String) FieldUtils.readField(obj, "authenticationQuery", true);
+      LOGGER.info(authQuery);
+      String authQueryLowerCase = authQuery.toLowerCase();
+      retval = authQueryLowerCase.split("from", 2);
+      if (retval.length >= 2) {
+        retval = retval[1].split("with|where", 2);
+        tablename = retval[0];
+        retval = retval[1].split("where", 2);
+        if (retval.length >= 2) {
+          retval = retval[1].split("=", 2);
+        } else {
+          retval = retval[0].split("=", 2);
+        }
+        username = retval[0];
+      }
+
+      if (StringUtils.isBlank(username) || StringUtils.isBlank(tablename)) {
+        return userlist;
+      }
+
+      userquery = String.format("SELECT %s FROM %s", username, tablename);
+    } catch (IllegalAccessException e) {
+      LOGGER.error("Error while accessing dataSource for JDBC Realm", e);
+      return Lists.newArrayList();
+    }
+
+    try {
+      con = dataSource.getConnection();
+      ps = con.prepareStatement(userquery);
+      rs = ps.executeQuery();
+      while (rs.next()) {
+        userlist.add(rs.getString(1).trim());
+      }
+    } catch (Exception e) {
+      LOGGER.error("Error retrieving User list from JDBC Realm", e);
+    } finally {
+      JdbcUtils.closeResultSet(rs);
+      JdbcUtils.closeStatement(ps);
+      JdbcUtils.closeConnection(con);
+    }
+    return userlist;
+  }
+}

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java
index 6d5cdb2..1c40d17 100644
--- a/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java
@@ -60,8 +60,8 @@ import org.apache.zeppelin.service.SimpleServiceCallback;
 import org.apache.zeppelin.ticket.TicketContainer;
 import org.apache.zeppelin.types.InterpreterSettingsList;
 import org.apache.zeppelin.user.AuthenticationInfo;
+import org.apache.zeppelin.utils.CorsUtils;
 import org.apache.zeppelin.utils.InterpreterBindingUtils;
-import org.apache.zeppelin.utils.SecurityUtils;
 import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
 import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
 import org.slf4j.Logger;
@@ -188,7 +188,7 @@ public class NotebookServer extends WebSocketServlet
 
   public boolean checkOrigin(HttpServletRequest request, String origin) {
     try {
-      return SecurityUtils.isValidOrigin(origin, ZeppelinConfiguration.create());
+      return CorsUtils.isValidOrigin(origin, ZeppelinConfiguration.create());
     } catch (UnknownHostException | URISyntaxException e) {
       LOG.error(e.toString(), e);
     }

http://git-wip-us.apache.org/repos/asf/zeppelin/blob/354b06f7/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CorsUtils.java
----------------------------------------------------------------------
diff --git a/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CorsUtils.java b/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CorsUtils.java
new file mode 100644
index 0000000..d1f2b54
--- /dev/null
+++ b/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CorsUtils.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.zeppelin.utils;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import org.apache.zeppelin.conf.ZeppelinConfiguration;
+
+public class CorsUtils {
+  public static Boolean isValidOrigin(String sourceHost, ZeppelinConfiguration conf)
+      throws UnknownHostException, URISyntaxException {
+
+    String sourceUriHost = "";
+
+    if (sourceHost != null && !sourceHost.isEmpty()) {
+      sourceUriHost = new URI(sourceHost).getHost();
+      sourceUriHost = (sourceUriHost == null) ? "" : sourceUriHost.toLowerCase();
+    }
+
+    sourceUriHost = sourceUriHost.toLowerCase();
+    String currentHost = InetAddress.getLocalHost().getHostName().toLowerCase();
+
+    return conf.getAllowedOrigins().contains("*")
+        || currentHost.equals(sourceUriHost)
+        || "localhost".equals(sourceUriHost)
+        || conf.getAllowedOrigins().contains(sourceHost);
+  }
+}