@SuppressWarnings({"ThrowableInstanceNeverThrown"})
 private void useAnonymousIfPossible(
     HttpServletRequest request,
     HttpServletResponse response,
     FilterChain chain,
     SecurityContext securityContext)
     throws IOException, ServletException {
   boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
   if (anonAccessEnabled || authInterceptors.accept(request)) {
     log.debug("Using anonymous");
     Authentication authentication = getNonUiCachedAuthentication(request);
     if (authentication == null) {
       log.debug("Creating the Anonymous token");
       final UsernamePasswordAuthenticationToken authRequest =
           new UsernamePasswordAuthenticationToken(UserInfo.ANONYMOUS, "");
       AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
       //noinspection unchecked
       authRequest.setDetails(ads.buildDetails(request));
       // explicitly ask for the default spring authentication manager by name (we have another one
       // which
       // is only used by the basic authentication filter)
       AuthenticationManager authenticationManager =
           context.beanForType("authenticationManager", AuthenticationManager.class);
       authentication = authenticationManager.authenticate(authRequest);
       if (authentication != null
           && authentication.isAuthenticated()
           && !RequestUtils.isUiRequest(request)) {
         AuthCacheKey authCacheKey =
             new AuthCacheKey(authFilter.getCacheKey(request), request.getRemoteAddr());
         nonUiAuthCache.put(authCacheKey, authentication);
         log.debug("Added anonymous authentication {} to cache", authentication);
       }
     } else {
       log.debug("Using cached anonymous authentication");
     }
     useAuthentication(request, response, chain, authentication, securityContext);
   } else {
     if (authFilter.acceptEntry(request)) {
       log.debug("Sending request requiring authentication");
       authFilter.commence(
           request,
           response,
           new InsufficientAuthenticationException("Authentication is required"));
     } else {
       log.debug("No filter or entry just chain");
       chain.doFilter(request, response);
     }
   }
 }
Esempio n. 2
0
  public void authenticate(
      OAuthAccessToken oAuthAccessToken, HttpServletRequest request, HttpServletResponse response)
      throws FacebookException, IOException, ServletException {
    Facebook facebook =
        Face4jFactory.getInstance().getFacebookFactory().getInstance(oAuthAccessToken);
    User fbUser = facebook.getCurrentUser();
    PreAuthenticatedAuthenticationToken token =
        new PreAuthenticatedAuthenticationToken(fbUser, null);
    token.setDetails(ads.buildDetails((HttpServletRequest) request));

    try {
      Authentication authentication = authenticationManager.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(authentication);

      HttpSession session = request.getSession(true);
      session.setAttribute("username", fbUser.getEmail());

      LOG.info("Facebook user " + fbUser.getName());
      if (authentication.getAuthorities().contains(AppRole.NEW_USER)) {
        LOG.debug("New user authenticated. Redirecting to registration page");
        ((HttpServletResponse) response).sendRedirect(REGISTRATION_URL);

        return;
      }

    } catch (AuthenticationException e) {
      failureHandler.onAuthenticationFailure(
          (HttpServletRequest) request, (HttpServletResponse) response, e);

      return;
    }
  }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {

      Authentication authentication = tokenExtractor.extract(request);

      if (authentication == null) {
        if (debug) {
          logger.debug("No token in request, will continue chain.");
        }
      } else {
        request.setAttribute(
            OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
        if (authentication instanceof AbstractAuthenticationToken) {
          AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
          needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
        }
        Authentication authResult = authenticationManager.authenticate(authentication);

        if (debug) {
          logger.debug("Authentication success: " + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);
      }
    } catch (OAuth2Exception failed) {
      SecurityContextHolder.clearContext();

      if (debug) {
        logger.debug("Authentication request failed: " + failed);
      }

      authenticationEntryPoint.commence(
          request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));

      return;
    }

    chain.doFilter(request, response);
  }
  /**
   * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse, javax.servlet.FilterChain).
   */
  public final void doFilter(
      final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(headerToken);
    logger.debug(pathInfo);

    // first of all, check HTTP if exists accept header
    if (!validateAcceptHeader(request, response)) {
      return;
    }

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
      /** It is not needed to authenticate these operations */
      logger.debug("Operation does not need to Authenticate");
    } else {

      if (headerToken == null) {
        headerToken = "";
      }

      try {
        String token = headerToken;
        if ("".equals(token)) {
          String str = "Missing token header";
          logger.info(str);
          throw new BadCredentialsException(str);
        }
        String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
        logger.debug(tenantId);
        logger.debug(token);
        // String tenantId = request.getPathInfo().split("/")[3];

        if (debug) {
          logger.debug(
              "OpenStack Authentication Authorization header "
                  + "found for user '"
                  + token
                  + "' and tenant "
                  + tenantId);
        }

        UsernamePasswordAuthenticationToken authRequest =
            new UsernamePasswordAuthenticationToken(token, tenantId);
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authResult = authenticationManager.authenticate(authRequest);

        if (debug) {
          logger.debug("Authentication success: " + authResult);
        }

        // check AUTH-TOKEN and VDC are the same
        String uri = request.getRequestURI();
        logger.debug("URI: " + uri);
        if (uri.contains("vdc") && !uri.contains(tenantId)) {
          String str = "Bad credentials for requested VDC";
          logger.info(str);
          throw new AccessDeniedException(str);
        }

        UserDetails user = (UserDetails) authResult.getPrincipal();

        logger.debug("User: "******"Token: " + user.getPassword());
        if (authResult.isAuthenticated()) {
          SecurityContextHolder.getContext().setAuthentication(authRequest);
        }

        // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

        rememberMeServices.loginSuccess(request, response, authResult);

        onSuccessfulAuthentication(request, response, authResult);

      } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
          logger.debug("Authentication request for failed: " + failed);
        }

        rememberMeServices.loginFail(request, response);
        onUnsuccessfulAuthentication(request, response, failed);

        if (ignoreFailure) {
          chain.doFilter(request, response);
        } else {
          authenticationEntryPoint.commence(request, response, failed);
        }

        return;
      } catch (AccessDeniedException ex) {
        throw ex;
      } catch (Exception ex) {
        SecurityContextHolder.clearContext();

        if (debug) {
          logger.debug("Authentication exception: " + ex);
        }

        rememberMeServices.loginFail(request, response);

        if (ignoreFailure) {
          chain.doFilter(request, response);
        } else {
          response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
        return;
      }

      String keystoneURL =
          systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

      response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);
  }