我正在尝试将 google recaptcha 与 spring mvc 集成,但 gRecaptchaResponse 总是 return false.Here 是一些代码
I'm trying to integrate google recaptcha with spring mvc but gRecaptchaResponse always return false.Here are some codes
VerifyRecaptcha class
public class VerifyRecaptcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg";
private final static String USER_AGENT = "Mozilla/5.0";
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en:q=0.5");
String postParams = "secret" + secret + "&response=" + gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters :" + postParams);
System.out.println("Response Code :" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println("test "+ response.toString());
// parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
登录控制器class
@Controller
public class LoginController {
/*
* ========================================================================
* Constants
* ========================================================================
*/
/** Attribute name msg */
private static final String ATTRIBUTE_NAME_MSG = "msg";
/** Attribute name error */
private static final String ATTRIBUTE_NAME_ERROR = "error";
/** Attribute value Login detail */
private static final String ATTRIBUTE_VAL_MSG_LOGIN_DETAIL = "Please Enter Your Login Details";
/** Attribute value invalid user name and password */
private static final String ATTRIBUTE_VAL_INVALID = "Invalid username and password";
/** Attribute value enter user name and password */
private static final String ATTRIBUTE_VAL_ENTER_USR_PWD = "Please enter username and password.";
/** Attribute value verify Recaptcha */
private static final String ATTRIBUTE_VAL_ENTER_RECAPTCHA = "Please verify captcha.";
/** Path to file connection DataBase */
private static final String RESOURCE_PATH = "e7bankaccountprinting/config/mybatis-config.xml";
/*
* ========================================================================
* RequestMapping
* ========================================================================
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String init(Model model) {
// model.addAttribute(ATTRIBUTE_NAME_MSG,ATTRIBUTE_VAL_ENTER_USR_PWD);
System.out.println("model test");
return "login";
}
/*
* String gRecaptchaResponse = loginBean.getgRecaptchaResponse()
* System.out.println("captcha response "+gRecaptchaResponse); boolean verify =
* VerifyRecaptcha.verify(gRecaptchaResponse);
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submit(Model model, @ModelAttribute("loginBean") LoginBean loginBean, HttpServletRequest req)
throws IOException {
String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
System.out.println(gRecaptchaResponse);
boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
System.out.println(verify);
if (loginBean != null && loginBean.getUserName() != null && loginBean.getPassword() != null
&& verify != false) {
SqlSession sqlSession = Connection.sqlSession(RESOURCE_PATH);
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
// Set parameters to Account
Account inputAccount = new Account();
inputAccount.setUserName(loginBean.getUserName());
inputAccount.setPassword(loginBean.getPassword());
Account rs_account = accountMapper.getAccount(inputAccount);
if (rs_account != null) {
// if(inputAccount.setUserName(loginBean.getUserName()!=null)){
model.addAttribute(ATTRIBUTE_NAME_MSG, "Welcome " + loginBean.getUserName());
sqlSession.close();
return "A4Print";
} else {
model.addAttribute(ATTRIBUTE_NAME_ERROR, ATTRIBUTE_VAL_INVALID);
sqlSession.close();
return "login";
}
} else {
model.addAttribute(ATTRIBUTE_VAL_ENTER_USR_PWD, ATTRIBUTE_VAL_ENTER_RECAPTCHA);
return "login";
}
}
/*
* ========================================================================
* private method
* ========================================================================
*/
}
错误信息
Sending 'POST' request to URL : https://www.google.com/recaptcha/api/siteverify
Post parameters : secret6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg&response=03AO
LTBLSWWCbUzVHAfCZRYgrsnTt6VpW1nRx0NzI0FXUL1lngDgrSBbZbth0G5drjVCn6dtFBaygHibx7mRhkkI2cMJa0u0X9ls-
Response Code :200
TEst { "success": false, "error-codes": [ "missing-input-secret" ]}
false
错误信息很清楚。
不应该是
//added missing = after secret
`String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;`
VerifyRecaptcha class
public class VerifyRecaptcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg";
private final static String USER_AGENT = "Mozilla/5.0";
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en:q=0.5");
String postParams = "secret" + secret + "&response=" + gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters :" + postParams);
System.out.println("Response Code :" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println("test "+ response.toString());
// parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
登录控制器class
@Controller
public class LoginController {
/*
* ========================================================================
* Constants
* ========================================================================
*/
/** Attribute name msg */
private static final String ATTRIBUTE_NAME_MSG = "msg";
/** Attribute name error */
private static final String ATTRIBUTE_NAME_ERROR = "error";
/** Attribute value Login detail */
private static final String ATTRIBUTE_VAL_MSG_LOGIN_DETAIL = "Please Enter Your Login Details";
/** Attribute value invalid user name and password */
private static final String ATTRIBUTE_VAL_INVALID = "Invalid username and password";
/** Attribute value enter user name and password */
private static final String ATTRIBUTE_VAL_ENTER_USR_PWD = "Please enter username and password.";
/** Attribute value verify Recaptcha */
private static final String ATTRIBUTE_VAL_ENTER_RECAPTCHA = "Please verify captcha.";
/** Path to file connection DataBase */
private static final String RESOURCE_PATH = "e7bankaccountprinting/config/mybatis-config.xml";
/*
* ========================================================================
* RequestMapping
* ========================================================================
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String init(Model model) {
// model.addAttribute(ATTRIBUTE_NAME_MSG,ATTRIBUTE_VAL_ENTER_USR_PWD);
System.out.println("model test");
return "login";
}
/*
* String gRecaptchaResponse = loginBean.getgRecaptchaResponse()
* System.out.println("captcha response "+gRecaptchaResponse); boolean verify =
* VerifyRecaptcha.verify(gRecaptchaResponse);
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submit(Model model, @ModelAttribute("loginBean") LoginBean loginBean, HttpServletRequest req)
throws IOException {
String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
System.out.println(gRecaptchaResponse);
boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
System.out.println(verify);
if (loginBean != null && loginBean.getUserName() != null && loginBean.getPassword() != null
&& verify != false) {
SqlSession sqlSession = Connection.sqlSession(RESOURCE_PATH);
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
// Set parameters to Account
Account inputAccount = new Account();
inputAccount.setUserName(loginBean.getUserName());
inputAccount.setPassword(loginBean.getPassword());
Account rs_account = accountMapper.getAccount(inputAccount);
if (rs_account != null) {
// if(inputAccount.setUserName(loginBean.getUserName()!=null)){
model.addAttribute(ATTRIBUTE_NAME_MSG, "Welcome " + loginBean.getUserName());
sqlSession.close();
return "A4Print";
} else {
model.addAttribute(ATTRIBUTE_NAME_ERROR, ATTRIBUTE_VAL_INVALID);
sqlSession.close();
return "login";
}
} else {
model.addAttribute(ATTRIBUTE_VAL_ENTER_USR_PWD, ATTRIBUTE_VAL_ENTER_RECAPTCHA);
return "login";
}
}
/*
* ========================================================================
* private method
* ========================================================================
*/
}
错误信息
Sending 'POST' request to URL : https://www.google.com/recaptcha/api/siteverify Post parameters : secret6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg&response=03AO LTBLSWWCbUzVHAfCZRYgrsnTt6VpW1nRx0NzI0FXUL1lngDgrSBbZbth0G5drjVCn6dtFBaygHibx7mRhkkI2cMJa0u0X9ls-
Response Code :200 TEst { "success": false, "error-codes": [ "missing-input-secret" ]} false
错误信息很清楚。
不应该是
//added missing = after secret
`String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;`