// Ch 6 Access Denied
 @RequestMapping(method = RequestMethod.GET, value = "/accessDenied.do")
 public void accessDenied(ModelMap model, HttpServletRequest request) {
   AccessDeniedException ex =
       (AccessDeniedException)
           request.getAttribute(
               AccessDeniedHandlerImpl.SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY);
   StringWriter sw = new StringWriter();
   model.addAttribute("errorDetails", ex.getMessage());
   ex.printStackTrace(new PrintWriter(sw));
   model.addAttribute("errorTrace", sw.toString());
 }
 /**
  * If marshall unmarshall fails then return bad request.
  *
  * @param ex Caused exception.
  * @return Error message.
  */
 @ExceptionHandler
 @ResponseStatus(HttpStatus.FORBIDDEN)
 @ResponseBody
 public ErrorElementType handleException(final AccessDeniedException ex) {
   LOGGER.info("Access denied. " + ex.getMessage());
   ErrorElementType element = new ErrorElementType();
   element.setErrorcode(BigInteger.valueOf(HttpStatus.FORBIDDEN.value()));
   element.setMessage(
       "User does not have access to the resource. Contact [email protected] for more information.");
   return element;
 }
Esempio n. 3
0
 @Override
 public void decide(
     Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
     throws AccessDeniedException {
   FilterInvocation fi = (FilterInvocation) object;
   authentication = fresh(authentication, fi.getRequest());
   try {
     super.decide(authentication, object, configAttributes);
   } catch (AccessDeniedException ade) {
     throw new MyAccessDeniedException(ade.getMessage(), authentication, object, configAttributes);
   }
 }
  @Test
  public void testEditWithoutPermission() throws Exception {
    log.debug("testing edit...");
    request = newGet("/userform.html");
    request.addParameter("id", "-1"); // regular user

    try {
      c.showForm(request, new MockHttpServletResponse());
      fail("AccessDeniedException not thrown...");
    } catch (AccessDeniedException ade) {
      assertNotNull(ade.getMessage());
    }
  }
  // Test fix to http://issues.appfuse.org/browse/APF-96
  @Test
  public void testChangeToAdminRoleFromUserRole() throws Exception {
    UserManager userManager = makeInterceptedTarget();
    User user = new User("user");
    user.setId(1L);
    user.getRoles().add(new Role(Constants.ADMIN_ROLE));

    try {
      userManager.saveUser(user);
      fail("AccessDeniedException not thrown");
    } catch (AccessDeniedException expected) {
      assertNotNull(expected);
      assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED);
    }
  }
  @Test
  public void testAddUserWithoutAdminRole() throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    assertTrue(auth.isAuthenticated());
    UserManager userManager = makeInterceptedTarget();
    User user = new User("admin");
    user.setId(2L);

    try {
      userManager.saveUser(user);
      fail("AccessDeniedException not thrown");
    } catch (AccessDeniedException expected) {
      assertNotNull(expected);
      Assert.assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED);
    }
  }
Esempio n. 7
0
  public String save() throws Exception {
    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
      user = userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (UserExistsException e) {
      addMessage("errors.existing.user", new Object[] {user.getUsername(), user.getEmail()});

      // redisplay the unencrypted passwords
      user.setPassword(user.getConfirmPassword());
      return null;
    }

    addMessage("user.registered");
    getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject"));

    try {
      sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
    } catch (MailException me) {
      addError(me.getMostSpecificCause().getMessage());
      return null;
    }

    return "mainMenu";
  }
Esempio n. 8
0
 @ExceptionHandler(AccessDeniedException.class)
 @ResponseStatus(HttpStatus.FORBIDDEN)
 @ResponseBody
 public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) {
   return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
 }
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      final User user,
      final BindingResult errors,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {
    if (request.getParameter("cancel") != null) {
      return getCancelView();
    }

    if (validator != null) { // validator is null during testing
      validator.validate(user, errors);

      if (StringUtils.isBlank(user.getPassword())) {
        errors.rejectValue(
            "password",
            "errors.required",
            new Object[] {getText("user.password", request.getLocale())},
            "Password is a required field.");
      }

      if (errors.hasErrors()) {
        return "signup";
      }
    }

    final Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    // unencrypted users password to log in user automatically
    final String password = user.getPassword();

    try {
      this.getUserManager().saveUser(user);
    } catch (final AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (final UserExistsException e) {
      errors.rejectValue(
          "username",
          "errors.existing.user",
          new Object[] {user.getUsername(), user.getEmail()},
          "duplicate user");

      return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    final UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), password, user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
      log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));

    try {
      sendUserMessage(
          user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (final MailException me) {
      saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
  }
Esempio n. 10
0
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      User user, BindingResult errors, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    if (request.getParameter("cancel") != null) {
      if (!StringUtils.equals(request.getParameter("from"), "list")) {
        return getCancelView();
      } else {
        return getSuccessView();
      }
    }

    if (validator != null) { // validator is null during testing
      validator.validate(user, errors);

      if (errors.hasErrors()
          && request.getParameter("delete") == null) { // don't validate when deleting
        return "userform";
      }
    }

    log.info(request.getRemoteUser() + " is modifying user := "******"delete") != null) {
      getUserManager().removeUser(user.getId().toString());
      saveMessage(request, getText("user.deleted", user.getUsername(), locale));

      return getSuccessView();
    } else {

      // only attempt to change roles if user is admin for other users,
      // showForm() method will handle populating
      if (request.isUserInRole(Constants.ADMIN_ROLE)) {
        String[] userRoles = request.getParameterValues("userRoles");

        if (userRoles != null) {
          user.getRoles().clear();
          for (String roleName : userRoles) {
            user.addRole(roleManager.getRole(roleName));
          }
        }
      } else {
        // if user is not an admin then load roles from the database
        // (or any other user properties that should not be editable
        // by users without admin role)
        User cleanUser = getUserManager().getUserByUsername(request.getRemoteUser());
        user.setRoles(cleanUser.getRoles());
      }

      Integer originalVersion = user.getVersion();

      try {
        getUserManager().saveUser(user);
      } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
      } catch (UserExistsException e) {
        errors.rejectValue(
            "username",
            "errors.existing.user",
            new Object[] {user.getUsername(), user.getEmail()},
            "duplicate user");

        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        // reset the version # to what was passed in
        user.setVersion(originalVersion);

        return "userform";
      }

      if (!StringUtils.equals(request.getParameter("from"), "list")) {
        saveMessage(request, getText("user.saved", user.getUsername(), locale));

        // return to main Menu
        return getCancelView();
      } else {
        if (StringUtils.isBlank(request.getParameter("version"))) {
          saveMessage(request, getText("user.added", user.getUsername(), locale));

          // // Send an account information e-mail
          // message.setSubject(getText("signup.email.subject",
          // locale));
          //
          // try {
          // sendUserMessage(user, getText("newuser.email.message",
          // user.getUsername(), locale),
          // RequestUtil.getAppURL(request));
          // } catch (MailException me) {
          // saveError(request, me.getCause().getLocalizedMessage());
          // }

          return getSuccessView();
        } else {
          saveMessage(request, getText("user.updated.byAdmin", user.getUsername(), locale));
        }
      }
    }

    return "userform";
  }
Esempio n. 11
0
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      User user, BindingResult errors, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    if (request.getParameter("cancel") != null) {
      if (!StringUtils.equals(request.getParameter("from"), "list")) {
        return getCancelView();
      } else {
        return getSuccessView();
      }
    }

    if (validator != null) { // validator is null during testing
      validator.validate(user, errors);

      if (errors.hasErrors()
          && request.getParameter("delete") == null) { // don't validate when deleting
        return "/userform";
      }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
      getUserManager().removeUser(user.getId().toString());
      saveMessage(request, getText("user.deleted", user.getFullName(), locale));
      return getSuccessView();
    } else {

      // only attempt to change roles if user is admin for other users,
      // showForm() method will handle populating
      if (request.isUserInRole(Constants.ADMIN_ROLE)) {
        String[] userRoles = request.getParameterValues("userRoles");

        if (userRoles != null) {
          user.getRoles().clear();
          for (String roleName : userRoles) {
            user.addRole(roleManager.getRole(roleName));
          }
        }
      }

      Integer originalVersion = user.getVersion();

      try {
        User userx = roleManager.getUserByUsername(user.getUsername());
        if (userx != null) {
          if (!userx.getPassword().equals(user.getPassword())) {
            user.setPassword(AeSimpleSHA1.SHA1(user.getPassword()));
          }
        } else {
          user.setPassword(AeSimpleSHA1.SHA1(user.getPassword()));
        }
        // user.setOriginalPassword(user.getOriginalPassword());//new
        // String pass = AeSimpleSHA1.SHA1(user.getOriginalPassword()); //new
        // user.setPassword(pass);//new
        getUserManager().saveUser(user);
      } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        log.warn(ade.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
      } catch (UserExistsException e) {
        errors.rejectValue(
            "username",
            "errors.existing.user",
            new Object[] {user.getUsername(), user.getEmail()},
            "duplicate user");

        // reset the version # to what was passed in
        user.setVersion(originalVersion);

        return "/userform";
      }

      if (!StringUtils.equals(request.getParameter("from"), "list")) {
        saveMessage(request, getText("user.saved", user.getFullName(), locale));

        // return to main Menu
        return getCancelView();
      } else {
        if (StringUtils.isBlank(request.getParameter("version"))) {
          saveMessage(request, getText("user.added", user.getFullName(), locale));

          // Send an account information e-mail
          // Aun no podemos enviar correos :(
          //                    message.setSubject(getText("signup.email.subject", locale));

          //                    try {
          //                        sendUserMessage(user, getText("newuser.email.message",
          // user.getFullName(), locale),
          //                                        RequestUtil.getAppURL(request));
          //                    } catch (MailException me) {
          //                        saveError(request, me.getCause().getLocalizedMessage());
          //                    }

          return getSuccessView();
        } else {
          saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
        }
      }
    }

    return getSuccessView();
  }
Esempio n. 12
0
  /**
   * Gets the content and defers to registered viewers to generate the markup.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess =
        (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest = getContentRequest(request);
    if (contentRequest.getDataUri() == null) {
      request.setAttribute("title", "Error");
      request.setAttribute("messages", "The data reference must be specified.");

      // forward to the error page
      final ServletContext viewerContext = servletContext.getContext("/nifi");
      viewerContext.getRequestDispatcher("/message").forward(request, response);
      return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
      downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
      request.setAttribute("title", "Error");
      request.setAttribute("messages", "Unable to find the specified content");

      // forward to the error page
      final ServletContext viewerContext = servletContext.getContext("/nifi");
      viewerContext.getRequestDispatcher("/message").forward(request, response);
      return;
    } catch (final AccessDeniedException ade) {
      request.setAttribute("title", "Acess Denied");
      request.setAttribute(
          "messages", "Unable to approve access to the specified content: " + ade.getMessage());

      // forward to the error page
      final ServletContext viewerContext = servletContext.getContext("/nifi");
      viewerContext.getRequestDispatcher("/message").forward(request, response);
      return;
    } catch (final Exception e) {
      request.setAttribute("title", "Error");
      request.setAttribute("messages", "An unexcepted error has occurred: " + e.getMessage());

      // forward to the error page
      final ServletContext viewerContext = servletContext.getContext("/nifi");
      viewerContext.getRequestDispatcher("/message").forward(request, response);
      return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
      mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
      displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
      request.setAttribute("title", "Error");
      request.setAttribute("messages", "Invalid display mode: " + mode);

      // forward to the error page
      final ServletContext viewerContext = servletContext.getContext("/nifi");
      viewerContext.getRequestDispatcher("/message").forward(request, response);
      return;
    }

    // buffer the content to support reseting in case we need to detect the content type or char
    // encoding
    try (final BufferedInputStream bis =
        new BufferedInputStream(downloadableContent.getContent()); ) {
      final String mimeType;

      // when standalone and we don't know the type is null as we were able to directly access the
      // content bypassing the rest endpoint,
      // when clustered and we don't know the type set to octet stream since the content was
      // retrieved from the node's rest endpoint
      if (downloadableContent.getType() == null
          || downloadableContent.getType().equals(MediaType.OCTET_STREAM.toString())) {
        // attempt to detect the content stream if we don't know what it is ()
        final DefaultDetector detector = new DefaultDetector();

        // create the stream for tika to process, buffered to support reseting
        final TikaInputStream tikaStream = TikaInputStream.get(bis);

        // provide a hint based on the filename
        final Metadata metadata = new Metadata();
        metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

        // Get mime type
        final MediaType mediatype = detector.detect(tikaStream, metadata);
        mimeType = mediatype.toString();
      } else {
        mimeType = downloadableContent.getType();
      }

      // add attributes needed for the header
      request.setAttribute("filename", downloadableContent.getFilename());
      request.setAttribute("contentType", mimeType);

      // generate the header
      request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

      // remove the attributes needed for the header
      request.removeAttribute("filename");
      request.removeAttribute("contentType");

      // generate the markup for the content based on the display mode
      if (DisplayMode.Hex.equals(displayMode)) {
        final byte[] buffer = new byte[BUFFER_LENGTH];
        final int read = StreamUtils.fillBuffer(bis, buffer, false);

        // trim the byte array if necessary
        byte[] bytes = buffer;
        if (read != buffer.length) {
          bytes = new byte[read];
          System.arraycopy(buffer, 0, bytes, 0, read);
        }

        // convert bytes into the base 64 bytes
        final String base64 = Base64.encodeBase64String(bytes);

        // defer to the jsp
        request.setAttribute("content", base64);
        request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
      } else {
        // lookup a viewer for the content
        final String contentViewerUri = servletContext.getInitParameter(mimeType);

        // handle no viewer for content type
        if (contentViewerUri == null) {
          request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
        } else {
          // create a request attribute for accessing the content
          request.setAttribute(
              ViewableContent.CONTENT_REQUEST_ATTRIBUTE,
              new ViewableContent() {
                @Override
                public InputStream getContentStream() {
                  return bis;
                }

                @Override
                public String getContent() throws IOException {
                  // detect the charset
                  final CharsetDetector detector = new CharsetDetector();
                  detector.setText(bis);
                  detector.enableInputFilter(true);
                  final CharsetMatch match = detector.detect();

                  // ensure we were able to detect the charset
                  if (match == null) {
                    throw new IOException("Unable to detect character encoding.");
                  }

                  // convert the stream using the detected charset
                  return IOUtils.toString(bis, match.getName());
                }

                @Override
                public ViewableContent.DisplayMode getDisplayMode() {
                  return displayMode;
                }

                @Override
                public String getFileName() {
                  return downloadableContent.getFilename();
                }

                @Override
                public String getContentType() {
                  return mimeType;
                }
              });

          try {
            // generate the content
            final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
            viewerContext.getRequestDispatcher("/view-content").include(request, response);
          } catch (final Exception e) {
            String message = e.getMessage() != null ? e.getMessage() : e.toString();
            message = "Unable to generate view of data: " + message;

            // log the error
            logger.error(message);
            if (logger.isDebugEnabled()) {
              logger.error(StringUtils.EMPTY, e);
            }

            // populate the request attributes
            request.setAttribute("title", "Error");
            request.setAttribute("messages", message);

            // forward to the error page
            final ServletContext viewerContext = servletContext.getContext("/nifi");
            viewerContext.getRequestDispatcher("/message").forward(request, response);
            return;
          }

          // remove the request attribute
          request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
        }
      }

      // generate footer
      request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
  }