2012-10-12 91 views
1

我使用Java邮件API:如何使用Java Mail API验证电子邮件和密码?

PasswordAuthentication valid = new PasswordAuthentication(txtEmail.getText(), 
                 txtPassword.getText()); 

if (valid != null) { 
    lblInvalid.setText("Correct information!"); 
} else { 
    lblInvalid.setText("Invalid username or password!"); 
} 

我想要它做什么,我希望用户与他们的Gmail用户名和密码登录。我想检查该电子邮件用户名和密码是否是真正的Gmail登录信息。如何检查电子邮件和密码是否是用户Gmail帐户。

+3

阅读:[您应该了解的密码安全性](http://crackstation.net/hashing-security.htm) – NullUserException

+0

您的程序应该如何知道正确的密码是什么? – Wyzard

回答

2

在Java中,做new Anything()将永远不会返回null。

此外,该类似乎只是一个占位符数据结构,由JDK的其他部分使用。它本质上不做验证。

验证电子邮件地址通常使用正则表达式,并保持简单。如果这对你很重要,你应该向用户发送一条确认消息来验证他们的电子邮件地址。

使用正则表达式还可以验证密码的正确形式。

更新

你正试图发出错误信息更仔细地观察,它看起来像你想处理身份验证自己。这里有很多方法可以做到这一点,但一个非常简单的只有样机解决方案是这样的:

// create a static mapping of user/passwords: 
private static Map<String, String> logins = new HashMap<String, String>(); 

然后在您的处理程序:

if (txtPassword.getText().equals(logins.get(txtEmail.getText()))) { 
    lblInvalid.setText("Correct information!"); 
} else { 
    lblInvalid.setText("Invalid username or password!"); 
} 

对于你打算在生产中我使用的东西强烈建议Spring Security

+0

正则表达式如何检查用户名和密码是否正确?我需要验证,以便帐户和密码能够发送电子邮件。 –

+0

是的,我意识到我的初步答案后,如图所示更新它。这当然不适合客户使用的真实程序。我强烈推荐Spring Security。 –

0

这是一个很大的话题。

认证,授权和验证是三件不同的事情(但非常相关)。

如果你是一个初学者,你只是想通过硬编码凭证一些模拟验证,你可以提高你的代码有点像这样的东西:

public class Authenticator { 

public boolean authenticateWithCredentials(String email, String password) { 

    boolean areValidCredentials = false; 

    //Validate credentials here with database or hardcoded 
    if(email.equals("[email protected]") && password.equals("mypassword")) { 
     areValidCredentials = true; 
    } 

    return areValidCredentials; 
} 

}

如果你是要使用这个类的只是一个例子,你可以使用Singleton模式:

public class Authenticator { 

//Singleton pattern 
private static Authenticator instance; 

public static Authenticator getInstance() { 

    if(instance == null) { 
     instance = new Authenticator(); 
    } 

    return instance; 
} 

private Authenticator() { 
    //Block creation of Authenticator instances 
} 

public boolean authenticateWithCredentials(String email, String password) { 

    boolean areValidCredentials = false; 

    //Validate credentials here with database or hardcoded 
    if(email.equals("[email protected]") && password.equals("mypassword")) { 
     areValidCredentials = true; 
    } 

    return areValidCredentials; 
} 

}

+0

关于设计模式:何时使用Singleton?:http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton – zengr

+1

我同意使用Singleton的原因很少和99%,这不是一个很好的使用它的理由。 所以,如果你只是学习面向对象的编程做你从来没有听说过的单身! :) – Giorgio

相关问题