@Override
  public void filter(ContainerRequestContext context) throws IOException {
    // public void doFilter(ServletRequest request, ServletResponse
    // response,
    // FilterChain filter) throws IOException, ServletException {
    String authCredentials = context.getHeaderString(AUTHENTICATION_HEADER);
    logger.trace("Authorization header:" + authCredentials);

    // better injected
    AuthenticationService authenticationService = new AuthenticationService();

    boolean authenticationStatus = authenticationService.authenticate(authCredentials);

    if (authenticationStatus) {
      // proceedcontext.
    } else {
      Response r =
          Response.ok()
              .entity("Authentication Failure")
              // .cookie(authIdCookie)
              .type(MediaType.TEXT_PLAIN)
              // .header("session_id", session.getId())
              .build();
      context.abortWith(r);
    }
  }
  @Test
  public void testSetOneTimePasswordBadRequest() {
    try {
      String subscriberId = addSubscriber();
      JsonEntity subscriber = getSubscriberById(subscriberId);
      String loginName = subscriber.getAsString("Subscriber/Person/EmailAddress");
      System.out.println(loginName);

      UserCredentialJsonBuilder userCredential = new UserCredentialJsonBuilder();
      userCredential.setStrict(false);
      userCredential.setLoginName("").setNewPassword("new_password");
      System.out.println(userCredential.toJson());

      AuthenticationService authenticationService = getAuthenticationService();
      authenticationService.setOneTimePassword(userCredential);

      Assert.fail("Expected bad request response");

    } catch (BssException be) {
      // expecting this exception
      JsonJavaObject jsonObject = be.getResponseJson();
      System.err.println(jsonObject);
      Assert.assertNotNull("Expected JSON response", jsonObject);
      Assert.assertEquals("400", be.getResponseCode());
      Assert.assertNotNull(be.getResponseMessage());
      Assert.assertEquals("Error", be.getSeverity());
      Assert.assertNotNull(be.getUserAction());
      Assert.assertNotNull(be.getMessageId());
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("Error changing password caused by: " + e.getMessage());
    }
  }
 @Override
 public void respondUnauthorised(Resource resource, Response response, Request request) {
   if (authenticationService.canUseExternalAuth(resource, request)) {
     log.info("respondUnauthorised: use external authentication");
     initiateExternalAuth(resource, request, response);
   } else {
     log.info("respondUnauthorised: return staus: " + Response.Status.SC_UNAUTHORIZED);
     response.setStatus(Response.Status.SC_UNAUTHORIZED);
     List<String> challenges = authenticationService.getChallenges(resource, request);
     response.setAuthenticateHeader(challenges);
   }
 }
  public Object login(String username, String password, Map<String, Object> parameters)
      throws InvalidUsernameException, InvalidPasswordException {
    Object user = authenticationService.loadUser(username, parameters);
    if (user == null) {
      throw new InvalidUsernameException();
    }

    String encrypted = passwordEncryptor.encryptPassword(password, user);
    String userPassword = userAdapter.getPassword(user);
    if (!userPassword.equals(encrypted)) {
      throw new InvalidPasswordException();
    }

    if (userAdapter.areCredentialsExpired(user)) {
      throw new CredentialsExpiredException();
    } else if (userAdapter.isExpired(user)) {
      throw new AccountExpiredException();
    } else if (userAdapter.isLocked(user)) {
      throw new AccountLockedException();
    }

    // Save the user to the context since the login was good
    securityContextProvider.login(user);

    return user;
  }
  @Test(expected = BadCredentialsException.class)
  public void shouldThrowExceptionIfUserIsNotFound() {
    String username = "******";
    String password = "******";

    when(allAdminUsers.findByName(username)).thenReturn(null);

    authenticationService.checkFor(username, password);
  }
  @Test(expected = BadCredentialsException.class)
  public void shouldThrowExceptionIfUserPasswordIsNotCorrect() {
    String username = "******";
    String password = "******";
    AdminUser adminUser = new AdminUser(username, password);

    when(allAdminUsers.findByName(username)).thenReturn(adminUser);

    authenticationService.checkFor(username, "notAku");
  }
Beispiel #7
0
  protected void init(
      ResourceFactory rf, WebDavResponseHandler responseHandler, List<String> authHandlers)
      throws ServletException {
    AuthenticationService authService;
    if (authHandlers == null) {
      authService = new AuthenticationService();
    } else {
      List<AuthenticationHandler> list = new ArrayList<AuthenticationHandler>();
      for (String authHandlerClassName : authHandlers) {
        Object o = instantiate(authHandlerClassName);
        if (o instanceof AuthenticationHandler) {
          AuthenticationHandler auth = (AuthenticationHandler) o;
          list.add(auth);
        } else {
          throw new ServletException(
              "Class: "
                  + authHandlerClassName
                  + " is not a: "
                  + AuthenticationHandler.class.getCanonicalName());
        }
      }
      authService = new AuthenticationService(list);
    }

    // log the auth handler config
    log.debug(
        "Configured authentication handlers: " + authService.getAuthenticationHandlers().size());
    if (authService.getAuthenticationHandlers().size() > 0) {
      for (AuthenticationHandler hnd : authService.getAuthenticationHandlers()) {
        log.debug(" - " + hnd.getClass().getCanonicalName());
      }
    } else {
      log.warn(
          "No authentication handlers are configured! Any requests requiring authorisation will fail.");
    }

    if (responseHandler == null) {
      httpManager = new ServletHttpManager(rf, authService);
    } else {
      httpManager = new ServletHttpManager(rf, responseHandler, authService);
    }
  }
  @Test
  public void shouldUseAllAdminUsersToValidateUser() {
    String username = "******";
    String password = "******";
    AdminUser adminUser = new AdminUser(username, password);

    when(allAdminUsers.findByName(username)).thenReturn(adminUser);

    AuthenticationResponse authenticationResponse =
        authenticationService.checkFor(username, password);
    assertTrue(authenticationResponse.roles().contains("admin"));
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
      throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
      HttpServletRequest httpServletRequest = (HttpServletRequest) request;
      String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);

      // better injected
      AuthenticationService authenticationService = new AuthenticationService();

      boolean authenticationStatus = authenticationService.authenticate(authCredentials);

      if (authenticationStatus) {
        filter.doFilter(request, response);
      } else {
        if (response instanceof HttpServletResponse) {
          HttpServletResponse httpServletResponse = (HttpServletResponse) response;
          httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
      }
    }
  }
  @Test
  public void testSetOneTimePassword() {
    try {
      String subscriberId = addSubscriber();
      JsonEntity subscriber = getSubscriberById(subscriberId);
      String loginName = subscriber.getAsString("Subscriber/Person/EmailAddress");
      System.out.println(loginName);

      UserCredentialJsonBuilder userCredential = new UserCredentialJsonBuilder();
      userCredential.setLoginName(loginName).setNewPassword("one_time_passw0rd");
      System.out.println(userCredential.toJson());

      AuthenticationService authenticationService = getAuthenticationService();
      authenticationService.setOneTimePassword(userCredential);

    } catch (BssException be) {
      JsonJavaObject jsonObject = be.getResponseJson();
      System.err.println(jsonObject);
      Assert.fail("Error setting one time password because: " + jsonObject);
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("Error setting one time password caused by: " + e.getMessage());
    }
  }
 public Establishment createEstablishment(Establishment establishment) {
   establishment.setPassword(authenticationService.encryptPassword(establishment.getPassword()));
   final EntityManager em = entityManagerService.createEntityManager();
   try {
     em.getTransaction().begin();
     em.persist(establishment);
     em.getTransaction().commit();
     return establishment;
   } finally {
     if (em.getTransaction().isActive()) {
       em.getTransaction().rollback();
     }
     em.close();
   }
 }
 private ExternalIdentityProvider getSelectedIP(Request request) {
   List<ExternalIdentityProvider> list = authenticationService.getExternalIdentityProviders();
   if (list.size() == 1) {
     return list.get(0);
   } else {
     String ipName = request.getParams().get("_ip");
     if (ipName != null && ipName.length() > 0) {
       for (ExternalIdentityProvider eip : list) {
         if (ipName.equals(eip.getName())) {
           return eip;
         }
       }
     }
     return null;
   }
 }
  public String submit(String username, String password, ModelMap model) {

    Authentication authentication = authenticationService.authenticate(username, password);

    if (Authentication.SUCCEEDED.equals(authentication)) {
      model.addAttribute("user", userRepository.getById(username));
      return "redirect:/";
    }

    if (Authentication.USER_NOT_FOUND.equals(authentication)) {
      model.addAttribute("message", "User not found");

    } else if (Authentication.INCORRECT_PASSWORD.equals(authentication)) {
      model.addAttribute("message", "Incorrect password");

    } else if (Authentication.ERROR.equals(authentication)) {
      model.addAttribute("message", "Unknown Error. Please try again.");
    }
    return "redirect:/login.html";
  }
 @Test
 public void testConnectWithBadUserName() throws IOException {
   assertThat(authenticationService.connect("bad username", GOOD_PASSWORD)).isFalse();
 }
 @Test
 public void testConnectWithBadPassword() throws IOException {
   assertThat(authenticationService.connect(GOOD_USERNAME, BAD_PASSWORD)).isFalse();
 }
 @Test
 public void testConnect() throws IOException {
   assertThat(authenticationService.connect(GOOD_USERNAME, GOOD_PASSWORD)).isTrue();
 }