public void validateBeforeAdding(
      LoginMethodDto loginMethodDto, String username, String password) {
    try {
      ldapHelper.authenticateLDAPUser(
          loginMethodDto.getUrl(), loginMethodDto.getId(), username, password);
    } catch (InternalAuthenticationServiceException ex) {
      throw new AppException(
          HttpStatus.UNAUTHORIZED.value(),
          "The LDAP server " + loginMethodDto.getUrl() + " is unauthorized.",
          null);
    }

    if (loginMethodRepository.findByPriority(loginMethodDto.getPriority()) != null) {
      throw new AppException(
          HttpStatus.CONFLICT.value(),
          "The loginMethod.priority " + loginMethodDto.getPriority() + " already exists.",
          null,
          null);
    }

    LoginMethodEntity loginMethod = loginMethodRepository.findByUrl(loginMethodDto.getUrl());

    if (loginMethod != null) {
      throw new AppException(
          HttpStatus.CONFLICT.value(),
          "The loginMethod.url " + loginMethodDto.getUrl() + " has already existed.",
          "The login method [id = "
              + loginMethod.getId()
              + "] also has url "
              + loginMethodDto.getUrl(),
          null);
    }
  }
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws Exception {
    if (isLoginRequest(request, response)) {
      if (isLoginSubmission(request, response)) {
        if (logger.isTraceEnabled()) {
          logger.trace("Login submission detected.  Attempting to execute login.");
        }
        return executeLogin(request, response);
      } else {
        if (logger.isTraceEnabled()) {
          logger.trace("Login page view.");
        }
        // allow them to see the login page ;)
        return true;
      }
    } else {
      if (logger.isTraceEnabled()) {
        logger.trace(
            "Attempting to access a path which requires authentication.  Forwarding to the "
                + "Authentication url ["
                + getLoginUrl()
                + "]");
      }

      if (isMobileAppAccess(request)) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        return true;
      } else {
        saveRequestAndRedirectToLogin(request, response);
        return false;
      }
    }
  }
 @Test
 public void testCommenceWithUnauthorizedWithAccept() throws Exception {
   request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
   authenticationEntryPoint.commence(request, response, null);
   assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatus());
   assertNotNull(response.getHeader(HttpHeaders.WWW_AUTHENTICATE));
 }
 /**
  * If credentials are incorrect or not provided for Basic Auth, then Android may throw this
  * exception when an HTTP 401 is received. A separate exception is thrown for proxy authentication
  * errors. Checking for this response and returning the proper status.
  *
  * @param ex the exception raised from Android
  * @return HTTP Status Code
  */
 private int handleIOException(IOException ex) throws IOException {
   if (AUTH_ERROR.equals(ex.getMessage()) || AUTH_ERROR_JELLY_BEAN.equals(ex.getMessage())) {
     return HttpStatus.UNAUTHORIZED.value();
   } else if (PROXY_AUTH_ERROR.equals(ex.getMessage())) {
     return HttpStatus.PROXY_AUTHENTICATION_REQUIRED.value();
   } else {
     throw ex;
   }
 }
  private LobbySession getVerifiedSession(final HttpServletRequest request)
      throws RequestException {
    final LobbySession activeSession = lobbySessionCache.getActiveSession(request);

    if (activeSession == null) {
      LOG.warn("PaymentController could not load session for player {}", request);
      throw new RequestException(HttpStatus.UNAUTHORIZED.value(), "no session");
    }
    return activeSession;
  }
 @Test
 public void givenNoAPIKey_WhenCallingSecureAPI_ThenShouldNotBeAllowed() throws Exception {
   setSecurity(sally_admin); // Sally is Authorised and has not API Key
   request.setRequestURI("/api/v1/fortress/");
   // exception.expect(SecurityException.class);
   // ToDo: Move to MVC tests
   TestCase.assertFalse(apiKeyInterceptor.preHandle(request, response, null));
   TestCase.assertNotNull(response.getErrorMessage());
   TestCase.assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatus());
 }
 /**
  * If marshall unmarshall fails then return bad request.
  *
  * @param ex Exception.
  * @return Error message.
  */
 @ExceptionHandler
 @ResponseStatus(HttpStatus.UNAUTHORIZED)
 @ResponseBody
 public ErrorElementType handleException(final InvalidTokenException ex) {
   LOGGER.info("Invalid bearer token. " + ex.getMessage());
   ErrorElementType element = new ErrorElementType();
   element.setErrorcode(BigInteger.valueOf(HttpStatus.UNAUTHORIZED.value()));
   element.setMessage("User token is either missing or wrong. " + ex.getOAuth2ErrorCode());
   return element;
 }
 /** 无效token */
 @ExceptionHandler({InvalidTokenException.class})
 @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
 @ResponseBody
 public BaseResponseEntity<?> handleInvalidTokenException(
     InvalidTokenException exception, HttpServletRequest request) {
   return BaseResponseEntity.build(
       HttpStatus.UNAUTHORIZED.value(),
       APIStatus.INVALID_TOKEN.getStatus(),
       APIStatus.INVALID_TOKEN.name(),
       exception,
       request);
 }