/**
  * 获得授权的button
  *
  * @param permission
  * @return
  */
 @Override
 public Map getButtonsByPermission(String permission) {
   if (permission == null || permission.isEmpty()) return null;
   Map resp = new HashMap();
   List<Map> buttons = new ArrayList<Map>();
   Subject subject = shiroService.getSubject();
   if (permission.indexOf("_") != -1) {
     String[] permissions = permission.split("_");
     for (String _permission : permissions) {
       Map button = new HashMap();
       button.put("permission", _permission);
       if (subject.hasRole(_permission)) {
         button.put("status", true);
       } else {
         button.put("status", false);
       }
       buttons.add(button);
     }
   } else {
     Map button = new HashMap();
     button.put("permission", permission);
     if (subject.hasRole(permission)) {
       button.put("status", true);
     } else {
       button.put("status", false);
     }
     buttons.add(button);
   }
   resp.put("buttons", buttons.toArray());
   return resp;
 }
 /**
  * 返回实现IModule接口的列表
  *
  * @param applicationId
  * @return
  */
 @Override
 public List<ModuleBean> getModuleByApplication(String applicationId) {
   Subject subject = shiroService.getSubject();
   List<IModule> moduleList = ModuleManager.getInstall().getModuleList(applicationId);
   List<ModuleBean> moduleBeanList = new ArrayList<ModuleBean>();
   if (moduleList == null) moduleList = new ArrayList<IModule>();
   Mapper mapper = new DozerBeanMapper();
   // 找出所有对应权限的功能模块
   if (moduleList != null && !moduleList.isEmpty()) {
     for (IModule module : moduleList) {
       // 调用isPermitted不能传入空字符,故此默认值为KALIX_NOT_PERMISSION
       String modulePermission =
           StringUtils.isEmpty(module.getPermission())
               ? Const.KALIX_NO_PERMISSION
               : module.getPermission();
       // 具有权限或不进行权限验证,都通过
       if (subject.hasRole(modulePermission)
           || modulePermission.equals(Const.KALIX_NO_PERMISSION)) {
         ModuleBean moduleBean = mapper.map(module, ModuleBean.class);
         moduleBean.setText(module.getText());
         moduleBeanList.add(moduleBean);
       }
     }
   }
   if (moduleBeanList != null && !moduleBeanList.isEmpty()) {
     for (ModuleBean moduleBean : moduleBeanList) {
       moduleBean.setChildren(new ArrayList<MenuBean>());
       List<IMenu> menuList = new ArrayList<IMenu>();
       List<IMenu> allMenu = MenuManager.getInstall().getMenuList(moduleBean.getId());
       // 去掉没有权限的菜单
       if (allMenu != null && !allMenu.isEmpty()) {
         for (IMenu menu : allMenu) {
           // 调用hasRole不能传入空字符,故此默认值为KALIX_NOT_PERMISSION
           String menuPermission =
               StringUtils.isEmpty(menu.getPermission())
                   ? Const.KALIX_NO_PERMISSION
                   : menu.getPermission();
           // 具有权限或不进行权限验证,都通过
           if (subject.hasRole(menuPermission)
               || menuPermission.equals(Const.KALIX_NO_PERMISSION)) {
             menuList.add(menu);
           }
         }
       }
       List<IMenu> rootMenus = getRootMenus(menuList);
       if (rootMenus != null && !rootMenus.isEmpty()) {
         for (IMenu rootMenu : rootMenus) {
           MenuBean menuBean = null;
           if (rootMenu != null) {
             menuBean = mapper.map(rootMenu, MenuBean.class);
             menuBean.setText(rootMenu.getText());
             getMenuChildren(menuBean, menuList, mapper);
           }
           moduleBean.getChildren().add(menuBean);
         }
       }
     }
   }
   return moduleBeanList;
 }
Example #3
0
 private void subjectLog() {
   Subject s = SecurityUtils.getSubject();
   log.info("subject: {}", s);
   log.info(
       "hasRole? admin:{} guest:{} geek:{}",
       s.hasRole("admin"),
       s.hasRole("guest"),
       s.hasRole("geek"));
   log.info("session: {}", s.getSession());
 }
Example #4
0
 /**
  * 判断当前用户是否有权限
  *
  * @param role
  * @return
  */
 public static boolean hasRole(String role) {
   if (StringUtils.isNotBlank(role)) {
     Subject subject = SecurityUtils.getSubject();
     if (subject.hasRole(role)) {
       return true;
     }
   }
   return false;
 }
Example #5
0
  @Test
  public void testShiro() {
    // init securityManager
    IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.properties");
    SecurityManager securityManager = factory.createInstance();

    // put into singleton
    SecurityUtils.setSecurityManager(securityManager);

    // get subject
    Subject subject = SecurityUtils.getSubject();

    // login
    AuthenticationToken token = new UsernamePasswordToken("user1", "password1".toCharArray());
    subject.login(token);

    // has role role1
    boolean hasRole = subject.hasRole("role1");
    assertTrue(hasRole);

    // has not role role2
    hasRole = subject.hasRole("role2");
    assertFalse(hasRole);

    // has permission perm1
    boolean permitted = subject.isPermitted("perm1");
    assertTrue(permitted);

    // has not permission perm3
    permitted = subject.isPermitted("perm3");
    assertFalse(permitted);

    // has permission a1:b1
    permitted = subject.isPermitted("a1:b1");
    assertTrue(permitted);

    // has permission a2:b2:c2
    permitted = subject.isPermitted("a2:b2:c2");
    assertTrue(permitted);

    // logout
    subject.logout();
  }
Example #6
0
 @Path("/listadmins")
 @GET
 public Response listadmins() {
   Subject subject = SecurityUtils.getSubject();
   if (subject.isAuthenticated() && subject.hasRole(RegAuthorizationInfo.ADMINSTRATOR_ROLE)) {
     UserStore userstore = Registry.get().getUserStore();
     return RequestProcessor.render(
         "admin-list.vm", uriInfo, servletContext, request, "admins", userstore.listAdminUsers());
   } else {
     return error("You must be logged in as an administrator to do this");
   }
 }
Example #7
0
  public boolean hasAnyRoles(Collection<String> roleNames) {
    Subject subject = SecurityUtils.getSubject();

    if (subject != null && roleNames != null) {
      for (String role : roleNames) {
        if (role != null && subject.hasRole(role.trim()) == true) {
          return true;
        }
      }
    }

    return false;
  }
Example #8
0
  public boolean hasAnyRoles(String[] roleNames) {
    Subject subject = SecurityUtils.getSubject();

    if (subject != null && roleNames != null) {
      for (int i = 0; i < roleNames.length; i++) {
        String role = roleNames[i];
        if (role != null && subject.hasRole(role.trim()) == true) {
          return true;
        }
      }
    }

    return false;
  }
  /**
   * Test that validates functionality for issue <a
   * href="https://issues.apache.org/jira/browse/JSEC-22">JSEC-22</a>
   */
  @Test
  public void testSubjectReuseAfterLogout() {

    Subject subject = SecurityUtils.getSubject();

    AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
    subject.login(token);
    assertTrue(subject.isAuthenticated());
    assertTrue("guest".equals(subject.getPrincipal()));
    assertTrue(subject.hasRole("guest"));

    Session session = subject.getSession();
    Serializable firstSessionId = session.getId();

    session.setAttribute("key", "value");
    assertEquals(session.getAttribute("key"), "value");

    subject.logout();

    assertNull(subject.getSession(false));
    assertNull(subject.getPrincipal());
    assertNull(subject.getPrincipals());

    subject.login(new UsernamePasswordToken("lonestarr", "vespa"));
    assertTrue(subject.isAuthenticated());
    assertTrue("lonestarr".equals(subject.getPrincipal()));
    assertTrue(subject.hasRole("goodguy"));

    assertNotNull(subject.getSession());
    assertFalse(firstSessionId.equals(subject.getSession().getId()));

    subject.logout();

    assertNull(subject.getSession(false));
    assertNull(subject.getPrincipal());
    assertNull(subject.getPrincipals());
  }
  protected boolean showTagBody(String roleNames) {
    boolean hasAnyRole = false;
    Subject subject = getSubject();

    if (subject != null) {
      // Iterate through roles and check to see if the user has one of the roles
      for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
        if (subject.hasRole(role.trim())) {
          hasAnyRole = true;
          break;
        }
      }
    }

    return hasAnyRole;
  }
Example #11
0
 @Path("/setrole")
 @POST
 public Response setrole(@FormParam("id") String id, @FormParam("role") String role) {
   Subject subject = SecurityUtils.getSubject();
   if (subject.isAuthenticated() && subject.hasRole(RegAuthorizationInfo.ADMINSTRATOR_ROLE)) {
     UserStore userstore = Registry.get().getUserStore();
     try {
       userstore.setRole(id, role.isEmpty() ? null : role);
       return redirectTo("/ui/admin");
     } catch (Exception e) {
       return error("Role assignment failed: " + e);
     }
   } else {
     return error("You must be logged in as an administrator to do this");
   }
 }
Example #12
0
  public boolean hasAnyRoles(String roleNames, String delimeter) {
    Subject subject = SecurityUtils.getSubject();
    if (subject != null) {
      if (delimeter == null || delimeter.length() == 0) {
        delimeter = ROLE_NAMES_DELIMETER;
      }

      for (String role : roleNames.split(delimeter)) {
        if (subject.hasRole(role.trim()) == true) {
          return true;
        }
      }
    }

    return false;
  }
  /**
   * @param request
   * @param response
   * @param mappedValue
   * @return
   * @throws IOException 如果发生任何错误就抛出异常
   */
  @Override
  public boolean isAccessAllowed(
      ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
    Subject subject = getSubject(request, response);

    String[] rolesArray = (String[]) mappedValue;

    if (rolesArray == null || rolesArray.length == 0) {
      // no roles specified, so nothing to check - allow access.
      return true;
    }

    Set<String> roles = CollectionUtils.asSet(rolesArray);
    for (String role : roles) {
      if (subject.hasRole(role)) {
        return true;
      }
    }
    return false;
  }
  @Test
  public void testDefaultConfig() {
    Subject subject = SecurityUtils.getSubject();

    AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
    subject.login(token);
    assertTrue(subject.isAuthenticated());
    assertTrue("guest".equals(subject.getPrincipal()));
    assertTrue(subject.hasRole("guest"));

    Session session = subject.getSession();
    session.setAttribute("key", "value");
    assertEquals(session.getAttribute("key"), "value");

    subject.logout();

    assertNull(subject.getSession(false));
    assertNull(subject.getPrincipal());
    assertNull(subject.getPrincipals());
  }
  /**
   * 返回实现IApplication接口的列表
   *
   * @return
   */
  @Override
  public List<ApplicationBean> getApplicationList() {
    Subject subject = shiroService.getSubject();
    List<ApplicationBean> applicationBeans = new ArrayList<>();
    if (subject == null) return applicationBeans;

    List<IApplication> applicationList = ApplicationManager.getInstall().getApplicationList();
    if (applicationList != null && applicationList.size() > 0) {
      Mapper mapper = new DozerBeanMapper();
      for (IApplication application : applicationList) {
        // 调用isPermitted不能传入空字符,故此默认值为KALIX_NOT_PERMISSION
        String permission =
            StringUtils.isEmpty(application.getPermission())
                ? Const.KALIX_NO_PERMISSION
                : application.getPermission();
        // 具有权限或不进行权限验证,都通过
        if (subject.hasRole(permission) || permission.equals(Const.KALIX_NO_PERMISSION)) {
          ApplicationBean applicationBean = mapper.map(application, ApplicationBean.class);
          applicationBeans.add(applicationBean);
        }
      }
    }
    return applicationBeans;
  }
Example #16
0
  /**
   * @param request - contains client request
   * @param response - contains servlet response to clients request
   * @exception IOException - throws error when IO exception occures
   *     <p>Method creates a UsernamePasswordToken by getting the username and password of the
   *     requesting user try-block runs secure: tests whether the user is admin, student or
   *     professor; if none of those exception is thrown. three possible exceptions: unknown
   *     account, incorrect credentials and the possibility to diagnose an exception
   *     (ex.printStackTrace()). Client request is redirected to previous URL
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    String url = "/login.jsp";

    // see /login.jsp for these form fields
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // create a UsernamePasswordToken using the
    // username and password provided by the user
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {

      // get the user (aka subject) associated with
      // this request.

      Subject subject = SecurityUtils.getSubject();

      // The use of IniShiroFilter specified in web.xml
      // caused JSecurity to create the DefaultWebSecurityManager object
      // see:
      // http://jsecurity.org/api/org/jsecurity/web/DefaultWebSecurityManager.html
      // This security manager is the default for web-based applications
      // The SecurityUtils was provided that security manager
      // automatically
      // The configuration specified in web.xml caused
      // a JdbcRealm object to be provided to the SecurityManager
      // so when the login method is called that JdbcRealm
      // object will be used
      // This application uses all the other defaults
      // For example the default authentication query string is
      // "select password from users where username = ?"
      // since the database this application uses (securityDB)
      // has a users table and that table has a column named username
      // and a column named password, the default authentication query
      // string will work
      // The call to login will cause the following to occur
      // Shiro will query the database for a password associated with the
      // provided username (which is stored in token). If a password is
      // found
      // and matches the password
      // provided by the user (also stored in the token), a new Subject
      // will be created that is
      // authenticated. This subject will be bound to the session for the
      // user who made this request
      // see:
      // http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/Authenticator.html
      // for a list of potential Exceptions that might be generated if
      // authentication fails (e.g. incorrect password, no username found)

      subject.login(token);

      // clear the information stored in the token

      token.clear();

      // add the username to the request
      request.setAttribute("username", username);

      if (subject.hasRole("admin")) {
        url = "/Admin";
      } else if (subject.hasRole("student")) {
        url = "/Student";
        // System.out.println(subject.getPrincipal());
        subject.getSession().setAttribute("student", subject.getPrincipal());
      } else if (subject.hasRole("professor")) {
        url = "/Professor";
      } else {
        throw new Exception();
      }
      // System.out.println("Log: " + username + " logged in successfully.");

    } catch (UnknownAccountException ex) {
      // username provided was not found
      // ex.printStackTrace(); ***commented out, Stack would otherwise fill up
      request.setAttribute("error", "Login failed! Username or password incorrect. Please retry.");

    } catch (IncorrectCredentialsException ex) {
      // password provided did not match password found in database
      // for the username provided
      // ex.printStackTrace(); ***commented out, Stack would otherwise fill up
      request.setAttribute("error", "Login failed! Username or password incorrect. Please retry.");
    } catch (Exception ex) {
      ex.printStackTrace();
      request.setAttribute("error", "Fatal Error! Please try again later.");
    }

    // TODO: Validate and catch Integer to String conversion #403
    Boolean audio;
    Boolean video;
    Boolean tts;
    Boolean subtitles;
    UserRealm realm = new UserRealm();
    String a;
    String b;
    String c;
    String d;

    try {
      ArrayList<Boolean> settings = realm.getSettings();

      audio = settings.get(0);
      video = settings.get(1);
      tts = settings.get(2);
      subtitles = settings.get(3);

      if (audio) {
        a = "true";
      } else {
        a = "false";
      }

      if (video) {
        b = "true";
      } else {
        b = "false";
      }

      if (tts) {
        c = "true";
      } else {
        c = "false";
      }

      if (subtitles) {
        d = "true";
      } else {
        d = "false";
      }

      Cookie audioSettings = new Cookie("audio", a);
      Cookie videoSettings = new Cookie("video", b);
      Cookie ttsSettings = new Cookie("tts", c);
      Cookie subtitlesSettings = new Cookie("subtitles", d);

      audioSettings.setMaxAge(12 * 60 * 60); // 12 hours.
      videoSettings.setMaxAge(12 * 60 * 60); // 12 hours.
      ttsSettings.setMaxAge(12 * 60 * 60); // 12 hours.
      subtitlesSettings.setMaxAge(12 * 60 * 60); // 12 hours.

      response.addCookie(audioSettings);
      response.addCookie(videoSettings);
      response.addCookie(ttsSettings);
      response.addCookie(subtitlesSettings);

    } catch (SQLException e) {
      e.printStackTrace();
    }

    // forward the request and response to the view
    // RequestDispatcher included = getServletContext()
    //		.getRequestDispatcher("/GetSettingsCookie");
    // included.include(request, response);

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
  }
Example #17
0
 public boolean hasRole(String role) {
   Subject subject = SecurityUtils.getSubject();
   return subject != null && subject.hasRole(role) == true;
 }