示例#1
0
 @RequestMapping(value = "/login_process", method = RequestMethod.POST)
 public ModelAndView loginProcess(
     @RequestParam("nick") final String username,
     @RequestParam("passwd") final String password,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   UsernamePasswordAuthenticationToken token =
       new UsernamePasswordAuthenticationToken(username, password);
   try {
     UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
     token.setDetails(details);
     Authentication auth = authenticationManager.authenticate(token);
     UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
     if (!userDetails.getUser().isActivated()) {
       throw new AccessViolationException("User not activated");
     }
     SecurityContextHolder.getContext().setAuthentication(auth);
     rememberMeServices.loginSuccess(request, response, auth);
     AuthUtil.updateLastLogin(auth, userDao);
   } catch (Exception e) {
     return new ModelAndView(new RedirectView("/login.jsp?error=true"));
   }
   return new ModelAndView(new RedirectView("/"));
 }
示例#2
0
  @RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST)
  public HttpEntity<LoginStatus> loginAjax(
      @RequestParam("nick") final String username,
      @RequestParam("passwd") final String password,
      HttpServletRequest request,
      HttpServletResponse response) {
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);
    try {
      UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
      token.setDetails(details);
      Authentication auth = authenticationManager.authenticate(token);
      UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
      if (!userDetails.getUser().isActivated()) {
        return entity(new LoginStatus(false, "User not activated"));
      }
      SecurityContextHolder.getContext().setAuthentication(auth);
      rememberMeServices.loginSuccess(request, response, auth);
      AuthUtil.updateLastLogin(auth, userDao);

      return entity(new LoginStatus(auth.isAuthenticated(), auth.getName()));
    } catch (LockedException e) {
      return entity(new LoginStatus(false, "User locked"));
    } catch (UsernameNotFoundException e) {
      return entity(new LoginStatus(false, "Bad credentials"));
    } catch (BadCredentialsException e) {
      return entity(new LoginStatus(false, e.getMessage()));
    }
  }
  private boolean initSession(
      UserProfile user,
      String password,
      boolean requirePassword,
      HttpServletRequest request,
      HttpServletResponse response) {

    Authentication auth;

    try {
      if (requirePassword) {
        UsernamePasswordAuthenticationToken token =
            new UsernamePasswordAuthenticationToken(user.getUsername(), password);
        auth = authenticationManager.authenticate(token);
      } else {
        auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
      }

      context.getLogManager().loggedIn(user);
      SecurityContextHolder.getContext().setAuthentication(auth);
      securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
      rememberMeServices.loginSuccess(request, response, auth);
      request
          .getSession()
          .setAttribute("nquire-it-token", new BigInteger(260, random).toString(32));
    } catch (Exception ex) {
      auth = null;
    }

    return auth != null
        && auth.getPrincipal() != null
        && auth.getPrincipal() instanceof UserProfile;
  }
  @Override
  public Credentials logon(String username, String password, boolean rememberMe)
      throws AuthenticationFailedException {

    try {
      profileService.authenticate(username, password);
      Credentials credentials = getCurrentUser();
      if (rememberMe && SecurityContextHolder.getContext().getAuthentication() != null) {
        rememberMeServices.loginSuccess(
            getThreadLocalRequest(),
            getThreadLocalResponse(),
            SecurityContextHolder.getContext().getAuthentication());
      }
      return credentials;
    } catch (AuthenticationException e) {
      throw new AuthenticationFailedException(e.getMessage());
    }
  }
  /**
   * (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);
  }