Esempio n. 1
0
  public boolean authenticate() {
    log.debug("testing: " + isTesting());

    try {
      username = credentials.getUsername();
      String password = credentials.getPassword();

      if (StringUtils.isEmpty(username)) {
        messages.error("login", "User name must be specified.");
        return false;
      }

      if (username.equals("admin")) {
        identity.addRole("admin");
      }

      principal = userService.getUserByName(username);
      if (principal != null && principal.getPassword().equals(password)) {
        log.debug("authenticated: " + username);
        raiseUserAuthenticatedEvent();
        return true;
      }

      messages.error("login", "Invalid user name or password.");
      log.debug("not-authenticated");
      return false;

    } catch (Throwable e) {
      messages.error("login", e.getMessage());
      log.error("not-authenticated: " + e);
      return false;
    }
  }
Esempio n. 2
0
  private void processBasicAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Context ctx = new SessionContext(new ServletRequestSessionMap(request));
    Identity identity = (Identity) ctx.get(Identity.class);

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = (Credentials) ctx.get(Credentials.class);

    boolean requireAuth = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Basic ")) {
      String base64Token = header.substring(6);
      String token = new String(Base64.decode(base64Token));

      String username = "";
      String password = "";
      int delim = token.indexOf(":");

      if (delim != -1) {
        username = token.substring(0, delim);
        password = token.substring(delim + 1);
      }

      // Only reauthenticate if username doesn't match Identity.username and user isn't
      // authenticated
      if (!username.equals(credentials.getUsername()) || !identity.isLoggedIn()) {
        try {
          credentials.setPassword(password);
          authenticate(request, username);
        } catch (Exception ex) {
          log.warn("Error authenticating: " + ex.getMessage());
          requireAuth = true;
        }
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      response.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
    }
  }
Esempio n. 3
0
 public boolean authenticate() {
   log.info("authenticating {0}", credentials.getUsername());
   // write your authentication logic here,
   // return true if the authentication was
   // successful, false otherwise
   if ("admin".equals(credentials.getUsername())) {
     identity.addRole("admin");
     return true;
   }
   return false;
 }
Esempio n. 4
0
 @Override
 public void authenticate() {
   if ("test".equals(creds.getUsername())) {
     this.setStatus(AuthenticationStatus.SUCCESS);
     this.setUser(new SimpleUser("test"));
   }
 }
 @Override
 public void authenticate() {
   String username = credentials.getUsername();
   if (username != null && !username.isEmpty()) {
     setStatus(AuthenticationStatus.SUCCESS);
     setUser(new SimpleUser(username));
   }
 }
Esempio n. 6
0
  /**
   * Authenticate jpa.
   *
   * @throws ClientException the client exception
   */
  protected void authenticateJPA() throws ClientException {
    User user = userDAO.getUserByLogin(credentials.getUsername());
    boolean hasNoError = true;

    hasNoError = authorizeUser(user);

    String password = null;
    if (hasNoError) {
      if (credentials != null && credentials.getCredential() instanceof PasswordCredential) {
        password = ((PasswordCredential) credentials.getCredential()).getValue();
      }
      if (password == null) {
        messages.error(new YoutestitMSG("error.login.password.require"));
        hasNoError = false;
      }
    }

    if (hasNoError) {
      final String cryptedPassword = Sha1Encryption.getInstance().encryptToSha1(password);

      if (user.getPassword().equals(cryptedPassword)) {
        loginEventSrc.fire(user);
        setUser(new SimpleUser(user.getLogin()));
        identity.getUser();
      } else {
        messages.error(new YoutestitMSG("error.login.password.wrong"));
        hasNoError = false;
      }
    }

    if (hasNoError) {
      setStatus(AuthenticationStatus.SUCCESS);
    } else {
      setStatus(AuthenticationStatus.FAILURE);
    }
  }
 // @Create
 public void inicializar() {
   log.info("personaHome.getInstance() == null:" + personaHome.getInstance() == null);
   if (personaHome.getInstance().getIdPersona() == 0) {
     Persona persona = personaDAO.obtenerPersonaXUsuario(credentials.getUsername());
     // personaHome = new PersonaHome();
     personaHome.setInstance(persona);
     alumnoHome.setInstance(personaHome.getInstance().getAlumno());
     periodoAcademicoHome.setInstance(
         periodoAcademicoDAO.obtenerPeriodoAcademicoEnCurso(
             alumnoHome.getInstance().getColegio().getIdColegio()));
     subPeriodoAcademicoHome.setInstance(
         periodoAcademicoDAO.obtenerSubPeriodoAcademicoEnCurso(
             alumnoHome.getInstance().getColegio().getIdColegio()));
     resumenAlumnoHome.setInstance(
         alumnoDAO.obtenerResumenPeriodo(
             alumnoHome.getInstance().getIdPersona(),
             periodoAcademicoHome.getInstance().getIdPeriodoAcademico()));
     log.info("Inicializando Datos:" + personaHome.getInstance().getIdPersona());
   }
 }
Esempio n. 8
0
  private void processDigestAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Context ctx = new SessionContext(new ServletRequestSessionMap(request));
    Identity identity = (Identity) ctx.get(Identity.class);

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = (Credentials) ctx.get(Credentials.class);

    boolean requireAuth = false;
    boolean nonceExpired = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Digest ")) {
      String section212response = header.substring(7);

      String[] headerEntries = section212response.split(",");
      Map<String, String> headerMap = new HashMap<String, String>();
      for (String entry : headerEntries) {
        String[] vals = split(entry, "=");
        headerMap.put(vals[0].trim(), vals[1].replace("\"", "").trim());
      }

      DigestRequest digestRequest = new DigestRequest();
      digestRequest.setHttpMethod(request.getMethod());
      digestRequest.setSystemRealm(realm);
      digestRequest.setRealm(headerMap.get("realm"));
      digestRequest.setKey(key);
      digestRequest.setNonce(headerMap.get("nonce"));
      digestRequest.setUri(headerMap.get("uri"));
      digestRequest.setClientDigest(headerMap.get("response"));
      digestRequest.setQop(headerMap.get("qop"));
      digestRequest.setNonceCount(headerMap.get("nc"));
      digestRequest.setClientNonce(headerMap.get("cnonce"));

      try {
        digestRequest.validate();
        request.getSession().setAttribute(DigestRequest.DIGEST_REQUEST, digestRequest);
        authenticate(request, headerMap.get("username"));
      } catch (DigestValidationException ex) {
        log.warn(
            String.format(
                "Digest validation failed, header [%s]: %s", section212response, ex.getMessage()));
        requireAuth = true;

        if (ex.isNonceExpired()) nonceExpired = true;
      } catch (Exception ex) {
        log.warn("Error authenticating: " + ex.getMessage());
        requireAuth = true;
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      long expiryTime = System.currentTimeMillis() + (nonceValiditySeconds * 1000);

      String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
      String nonceValue = expiryTime + ":" + signatureValue;
      String nonceValueBase64 = Base64.encodeBytes(nonceValue.getBytes());

      // qop is quality of protection, as defined by RFC 2617.
      // we do not use opaque due to IE violation of RFC 2617 in not
      // representing opaque on subsequent requests in same session.
      String authenticateHeader =
          "Digest realm=\"" + realm + "\", " + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\"";

      if (nonceExpired) authenticateHeader = authenticateHeader + ", stale=\"true\"";

      response.addHeader("WWW-Authenticate", authenticateHeader);
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }