/** {@inheritDoc} */
  @Override
  public void commence(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authException)
      throws IOException, ServletException {

    AuthenticationEntryPoint entryPoint = getAppropriateEntryPoint(request);

    entryPoint.commence(request, response, authException);
  }
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith(AUTH_TOKEN)) {
      chain.doFilter(request, response);
      return;
    }

    try {
      final String[] tokens = this.extractAndDecodeHeader(header, request);
      final String username = tokens[0];

      if (authenticationIsRequired(username)) {

        final String access_token = tokens[1];
        final String provider = tokens[2];
        String usernameToken = null;
        String profileName = null;

        if (provider.equals(FACEBOOK)) {
          UserOperations userOperations = new FacebookTemplate(access_token).userOperations();
          usernameToken = userOperations.getUserProfile().getEmail();
          profileName = userOperations.getUserProfile().getName();
        } else if (provider.equals(GOOGLEPLUS)) {
          PlusOperations plusOperations = new GoogleTemplate(access_token).plusOperations();
          usernameToken = plusOperations.getGoogleProfile().getAccountEmail();
          profileName = plusOperations.getGoogleProfile().getDisplayName();
        }

        if (usernameToken == null || !usernameToken.equals(username)) {
          throw new BadCredentialsException("Invalid access authentication token");
        }

        User user = this.loginService.findUserByEmail(username);

        if (user != null && user.isEnabled() == false) {
          throw new BadCredentialsException("Invalid credentials - User disabled");
        } else if (user == null) {
          user = this.loginService.insertSocialUser(new User(profileName, username));
        }

        final SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(
            new UsernamePasswordAuthenticationToken(
                user, user.getPassword(), user.getAuthorities()));
      }
    } catch (AuthenticationException failed) {
      SecurityContextHolder.clearContext();
      authenticationEntryPoint.commence(request, response, failed);
      return;
    }

    chain.doFilter(request, response);
  }
  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);
  }
Exemple #5
0
 /**
  * The login process starts from here, using the CasAuthenticationEntryPoint defined in the
  * CasSecurityRealm.groovy application context.
  */
 public void doCommenceLogin(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   AuthenticationEntryPoint entryPoint =
       (AuthenticationEntryPoint) getApplicationContext().getBean("casAuthenticationEntryPoint");
   entryPoint.commence(req, rsp, null);
 }
  @Override
  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 credentials = extractCredentials(request);

      if (credentials != null) {

        if (debug) {
          logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
        }

        Authentication authResult = authenticationManager.authenticate(credentials);

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

        Authentication requestingPrincipal = SecurityContextHolder.getContext().getAuthentication();
        if (requestingPrincipal == null) {
          throw new BadCredentialsException(
              "No client authentication found. Remember to put a filter upstream of the LoginAuthenticationFilter.");
        }

        String clientId = request.getParameter("client_id");
        if (null == clientId) {
          logger.error("No client_id in the request");
          throw new BadCredentialsException("No client_id in the request");
        }

        // Check that the client exists
        ClientDetails authenticatingClient = clientDetailsService.loadClientByClientId(clientId);
        if (authenticatingClient == null) {
          throw new BadCredentialsException("No client " + clientId + " found");
        }

        DefaultAuthorizationRequest authorizationRequest =
            new DefaultAuthorizationRequest(
                getSingleValueMap(request),
                null,
                authenticatingClient.getClientId(),
                getScope(request));
        if (requestingPrincipal.isAuthenticated()) {
          // Ensure the OAuth2Authentication is authenticated
          authorizationRequest.setApproved(true);
        }

        SecurityContextHolder.getContext()
            .setAuthentication(new OAuth2Authentication(authorizationRequest, authResult));

        onSuccessfulAuthentication(request, response, authResult);
      }

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

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

      onUnsuccessfulAuthentication(request, response, failed);

      authenticationEntryPoint.commence(request, response, failed);

      return;
    }

    chain.doFilter(request, response);
  }