OpenId-如何返回用户登录前所在的url
当我的站点的用户单击登录时,会同时发送一个返回url,这样我就知道用户在成功登录后应该返回到哪个页面。但是,当我将用户重定向到他们的openid提供者时,这些信息就丢失了 如何保存返回urlOpenId-如何返回用户登录前所在的url,openid,Openid,当我的站点的用户单击登录时,会同时发送一个返回url,这样我就知道用户在成功登录后应该返回到哪个页面。但是,当我将用户重定向到他们的openid提供者时,这些信息就丢失了 如何保存返回url 如果有必要的话,我使用的是openid4java。当您将用户重定向到他们的身份提供者时,您会为其提供一个URL以重定向或将用户发送回。这可以是你的返回URL。如果需要跟踪其他URL或任何其他信息,可以将它们作为参数包含在此URL中。当您将用户重定向到其身份提供商时,可以为其提供一个URL以重定向或将用户发送
如果有必要的话,我使用的是openid4java。当您将用户重定向到他们的身份提供者时,您会为其提供一个URL以重定向或将用户发送回。这可以是你的返回URL。如果需要跟踪其他URL或任何其他信息,可以将它们作为参数包含在此URL中。当您将用户重定向到其身份提供商时,可以为其提供一个URL以重定向或将用户发送回。这可以是你的返回URL。如果您需要跟踪其他URL或任何其他信息,可以将它们作为此URL的参数包含在内。我今天遇到了这个问题,三个小时后,看起来我已经解决了这个问题 我正在使用以下命令调用LoginServlet:
out.println("<!--Open IDs login-->");
out.println("<div style=\"margin-left: 50px; margin-top: 40px; height: 60px;\"><form action=\"../web/login?identifier=https://www.google.com/accounts/o8/id&afterLoginUrl="
+ UsualHtmlUtils.encodeURL(returnToUrl) + "\" method=\"post\"> <input class=\"google openid_large_btn\" "
+ "style=\"background: #fff url(../images/openid-logos.png); background-position: -1px -1px;\" type=\"image\" value=\" \" /></form>");
out.println("<form action=\"../web/login?identifier=https://me.yahoo.com&afterLoginUrl=" + UsualHtmlUtils.encodeURL(returnToUrl)
+ "\" method=\"post\"><input class=\"google openid_large_btn\" style=\"background: #fff url(../images/openid-logos.png); background-position: -1px -63px;\" type=\"image\" value=\" \" /> </form></div>");
out.println(“”);
out.println(“”);
out.println(“”);
实际的LoginServlet如下所示:
import commons.StringUtils;
import commons.UsualHtmlUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
/**
*
* @author mladen
*/
@WebServlet(name = "LoginServlet", urlPatterns = {"/web/login"})
public class LoginServlet extends HttpServlet {
final static String YAHOO_ENDPOINT = "https://me.yahoo.com";
final static String GOOGLE_ENDPOINT = "https://www.google.com/accounts/o8/id";
private static final long serialVersionUID = 309579782731258702L;
private ServletContext context;
private ConsumerManager manager;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
context = config.getServletContext();
this.manager = new ConsumerManager();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//log.debug("context: " + context);
Identifier identifier = this.verifyResponse(req);
//log.debug("identifier: " + identifier);
// if openid login succeded redirect to home page using our demo account
//if your site is open to anyone without login you can do the redirect directly
if (identifier != null) {
//WebAuthentication pwl = new WebAuthentication();
//pwl.login("guest", "guest");**
String afterLoginUrl = req.getParameter("afterLoginUrl");
if (afterLoginUrl == null) {
afterLoginUrl = "../def/";
}
resp.sendRedirect(afterLoginUrl);
} else {
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "attr= {0}", StringUtils.toString("login with openid failed"));
resp.sendRedirect("../def/");
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String identifier = req.getParameter("identifier");
String afterLoginUrl = req.getParameter("afterLoginUrl");
//req.getSession().setAttribute("afterLoginUrl", req.getRequestURL().toString());
this.authRequest(identifier, afterLoginUrl, req, resp);
}
// --- placing the authentication request ---
public String authRequest(String userSuppliedString, String afterLoginUrl,
HttpServletRequest httpReq, HttpServletResponse httpResp)
throws IOException {
try {
// configure the return_to URL where your application will receive
// the authentication responses from the OpenID provider
String returnToUrl = httpReq.getRequestURL().toString() + "?afterLoginUrl=" + UsualHtmlUtils.encodeURL(afterLoginUrl);
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "attr= {0}", StringUtils.toString("444 returnToUrl=" + returnToUrl));
// --- Forward proxy setup (only if needed) ---
// ProxyProperties proxyProps = new ProxyProperties();
// proxyProps.setProxyName("proxy.example.com");
// proxyProps.setProxyPort(8080);
// HttpClientFactory.setProxyProperties(proxyProps);
// perform discovery on the user-supplied identifier
List discoveries = manager.discover(userSuppliedString);
// attempt to associate with the OpenID provider
// and retrieve one service endpoint for authentication
DiscoveryInformation discovered = manager.associate(discoveries);
// store the discovery information in the user's session
httpReq.getSession().setAttribute("openid-disc", discovered);
// obtain a AuthRequest message to be sent to the OpenID provider
AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
FetchRequest fetch = FetchRequest.createFetchRequest();
if (userSuppliedString.startsWith(GOOGLE_ENDPOINT)) {
fetch.addAttribute("email", "http://axschema.org/contact/email", true);
fetch.addAttribute("firstName", "http://axschema.org/namePerson/first", true);
fetch.addAttribute("lastName", "http://axschema.org/namePerson/last", true);
} else if (userSuppliedString.startsWith(YAHOO_ENDPOINT)) {
fetch.addAttribute("email", "http://axschema.org/contact/email", true);
fetch.addAttribute("fullname", "http://axschema.org/namePerson", true);
} else { // works for myOpenID
fetch.addAttribute("fullname", "http://schema.openid.net/namePerson", true);
fetch.addAttribute("email", "http://schema.openid.net/contact/email", true);
}
// attach the extension to the authentication request
authReq.addExtension(fetch);
httpResp.sendRedirect(authReq.getDestinationUrl(true));
} catch (OpenIDException e) {
// present error to the user
}
return null;
}
// --- processing the authentication response ---
public Identifier verifyResponse(HttpServletRequest httpReq) {
try {
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList response = new ParameterList(httpReq.getParameterMap());
// retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) httpReq.getSession().getAttribute("openid-disc");
// extract the receiving URL from the HTTP request
StringBuffer receivingURL = httpReq.getRequestURL();
String queryString = httpReq.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(httpReq.getQueryString());
}
// verify the response; ConsumerManager needs to be the same
// (static) instance used to place the authentication request
VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);
// examine the verification result and extract the verified
// identifier
Identifier verified = verification.getVerifiedId();
if (verified != null) {
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
List emails = fetchResp.getAttributeValues("email");
String email = (String) emails.get(0);
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "OpenIdlogin done with email: {0}", email);
Map<String, List<String>> respAttributes = fetchResp.getAttributes();
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "attr= {0}", StringUtils.toString(respAttributes));
//for (Map.Entry<String, List<String>> entry : respAttributes.entrySet()) {
//Logger.getLogger(this.getClass().getName()).log(Level.INFO, "key = " + entry + ", value = " + StringUtils.toString(respAttributes));
// entry.getKey();
//}
//fetch.addAttribute("firstName", "http://axschema.org/namePerson/first", true);
//fetch.addAttribute("lastName", "http://axschema.org/namePerson/last", true);
}
return verified; // success
}
} catch (OpenIDException e) {
// present error to the user
}
return null;
}
}
import commons.StringUtils;
导入commons.usualhtmlits;
导入java.io.IOException;
导入java.util.List;
导入java.util.Map;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.servlet.ServletConfig;
导入javax.servlet.ServletContext;
导入javax.servlet.ServletException;
导入javax.servlet.annotation.WebServlet;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.openid4java.OpenIDException;
导入org.openid4java.consumer.ConsumerManager;
导入org.openid4java.consumer.VerificationResult;
导入org.openid4java.discovery.DiscoveryInformation;
导入org.openid4java.discovery.Identifier;
导入org.openid4java.message.AuthRequest;
导入org.openid4java.message.AuthSuccess;
导入org.openid4java.message.ParameterList;
导入org.openid4java.message.ax.AxMessage;
导入org.openid4java.message.ax.FetchRequest;
导入org.openid4java.message.ax.FetchResponse;
/**
*
*@作者姆拉登
*/
@WebServlet(name=“LoginServlet”,urlPatterns={”/web/login“})
公共类LoginServlet扩展了HttpServlet{
最终静态字符串YAHOO_端点=”https://me.yahoo.com";
最终静态字符串GOOGLE_端点=”https://www.google.com/accounts/o8/id";
私有静态最终长serialVersionUID=309579782731258702L;
私有服务上下文;
私人消费者管理经理;
@凌驾
public void init(ServletConfig config)抛出ServletException{
super.init(config);
context=config.getServletContext();
this.manager=new ConsumerManager();
}
受保护的无效数据集(HttpServletRequest-req、HttpServletResponse-resp)
抛出ServletException、IOException{
//调试(“上下文:“+context”);
标识符=此。验证响应(req);
//log.debug(“标识符:“+identifier”);
//如果openid登录成功,请使用我们的演示帐户重定向到主页
//如果您的站点对任何未登录的人开放,您可以直接执行重定向
if(标识符!=null){
//WebAuthentication pwl=新的WebAuthentication();
//密码登录(“来宾”、“来宾”)**
字符串afterLoginUrl=req.getParameter(“afterLoginUrl”);
if(afterLoginUrl==null){
afterLoginUrl=“../def/”;
}
分别为sendRedirect(afterLoginUrl);
}否则{
Logger.getLogger(this.getClass().getName()).log(Level.INFO,“attr={0}”、StringUtils.toString(“使用openid登录失败”);
分别为sendRedirect(“../def/”);
}
}
受保护的void doPost(HttpServletRequest-req、HttpServletResponse-resp)
抛出ServletException、IOException{
字符串标识符=req.getParameter(“标识符”);
字符串afterLoginUrl=req.getParameter(“afterLoginUrl”);
//req.getSession().setAttribute(“afterLoginUrl”,req.getRequestURL().toString());
此.authRequest(标识符、afterLoginUrl、req、resp);
}
//---放置身份验证请求---
公共字符串authRequest(字符串userSuppliedString、字符串afterLoginUrl、,
HttpServletRequest httpReq,HttpServletResponse httpResp)
抛出IOException{
试一试{
//配置应用程序将接收的返回URL
//来自OpenID提供程序的身份验证响应
字符串returnToUrl=httpReq.getRequestURL().toString()+“?afterLoginUrl=“+UsualHtmlUtils.encodeURL(afterLoginUrl));
Logger.getLogger(this.getClass().getName()).log(Level.INFO,“attr={0}”,StringUtils.toString(“444 returnToUrl=“+returnToUrl));
//---转发代理设置(仅在需要时)---
//ProxyProperties proxyProps=新的ProxyProperties();
//setProxyName(“proxy.example.com”);
//proxyProps.setProxyPort(8080);
//HttpClientFactory.setProxyProperties(proxyProps);
//对用户提供的标识符执行发现
列表发现=manager.discover(userSuppliedString);
//尝试与OpenID提供程序关联
//并检索一个用于身份验证的服务端点
DiscoveryInformation discovered=manager.associate(discoveries);
//将发现信息存储在用户会话中
httpReq.getSession().setAttribute(“openid光盘”,已发现);
//获取要发送到OpenID提供程序的AuthRequest消息
AuthRequest authReq=manager.authenticate(已发现,返回ToURL);
FetchRequest fetch=FetchRequest.createFetchRequest();
if(userSuppliedString.startsWith(GOOGLE_端点)){
fetch.addAttribute(“电子邮件”http://axschema.org/contact/email“,对);
fetch.addAttribute(“firstName”http://axschema.org/namePerson/first“,对);
fetch.addAttribute(“lastName”http://axschema.org/namePerson/last“,对);
}else if(用户