【问题标题】:how to authorize an user using jGit如何使用 jGit 授权用户
【发布时间】:2018-10-30 17:02:14
【问题描述】:

我正在用 Java 创建一个应用程序并使用 jGit。作为其中的一部分,我需要对用户进行身份验证。我想输出用户是否存在。目前我得到一个例外为user is not authorized。下面是我的代码。

import java.io.File;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class AuthenticateanUser {

    public static void main(String[] args) throws Exception {
        final String REMOTE_URL = "https://myRepo.git";
        // prepare a new folder for the cloned repository
        File localPath = File.createTempFile("TestGitRepository", "");
        localPath.delete();
        // then clone
        try (Git result = Git.cloneRepository().setURI(REMOTE_URL)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider("myId", "myPwd"))
                .setDirectory(localPath).call()) {

            System.out.println("Having repository: " + result.status());
        }
    }

}

当我运行上面的代码时,如果我提供正确的凭据,我会得到输出

Having repository:XXXXX

如果我提供错误的凭据,我会收到错误

Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: https://myRepo.git: not authorized

我想打印的不是这个,而是无效的凭据。

请让我知道我哪里出错了,我该如何解决这个问题。

谢谢

【问题讨论】:

  • @GhostCat 我的错,一开始就应该这样做:)

标签: java jgit


【解决方案1】:

你去:

try (Git result = Git.cloneRepository().setURI(REMOTE_URL) {
  ...         
} catch (TransportException te) {
     System.out.println("Invalid credentials");
}

例如。

您应该告诉用户该帐户是否存在。如:如果你告诉攻击者,他可以断定他已经获得了一个有效的用户名。

【讨论】:

  • 感谢@GhostCat 的快速答复。我还有另一个愚蠢的问题,如果用户提供了正确的凭据,但他没有任何访问该仓库的权限怎么办?在这种情况下我将如何区分?就像,2 条不同的错误消息...如果没有经过身份验证 Invalid Credentials(正如您在回答中所说的那样),如果没有被授权使用 repo,you are not authorized to use this repo。再次感谢!!!
  • @user3872094 在这种情况下,显然凭据是正确的。然后我会将其打印给用户(这可能意味着您必须解析异常消息或类似的东西。如果可能,请查看异常是否包含一些数字错误代码,或者底层异常的类型是否为不同的,以正确识别确切的问题)。
  • 抱歉尚未接受。我有最后一个问题,在我正在寻找的情况下,用户登录,如果他已登录,我不想抛出任何异常,并在 sysout 中显示一条消息作为登录和继续,目前如果用户没有访问权限用户输入了无效的凭据,则抛出异常。有没有办法可以限制这件事?用其他信息更新了我的问题。
  • 我没有得到最后一个问题。对不起:不要那样做。不要在 cmets ping pong 中玩“再问一个问题”。当一个问题完成后,接受/投票可能是答案,并提出一个新问题。本站为问答站。不是一个导师论坛,人们和你坐下来指导你完成作业。
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2015-10-25
  • 2011-03-12
  • 2014-12-01
  • 1970-01-01
相关资源
最近更新 更多