OpenID代码示例(自用)

发送认证到OP
1.  //创建消费者对象,它将向认证服务器发出认证请求
2.  ConsumerManager manager = new ConsumerManager();
3.  //setAssociations方法设置与OP的关联存放的位置,可以把它存在内存或者数据库或者xml或者文件中,这里将它存放在内存
4.  manager.setAssociations(new InMemoryConsumerAssociationStore());
5.  //setNonceVerifier方法设置记录response_nonce的位置
6.  manager.setNonceVerifier(new InMemoryNonceVerifier(5000));
7.  //下载OpenID提供者列表(一般只有一个提供者)
8.  List discoveries = manager.discover("https://example.com/login/openid/user/");
9.  //通过关联获取和OpenID提供者之间的共享密钥
10. DiscoveryInformation discovered = manager.associate(discoveries);  
11. //将关联(发现信息)保存,以备之后的使用
12. session.setAttribute("openid-disc", discovered);
13.  
14. //要重定向的地址
15. String returnURL = "http://example.com/openidresponse.jsp";
16. //将用户重定向到他们的OpenID提供者页面,并告诉OpenID提供者外部站点的地址
17. AuthRequest authReq = manager.authenticate(discovered, returnURL);
18. //在重定向之前添加额外的请求参数(email,fullname)
19. FetchRequest fetch = FetchRequest.createFetchRequest();
20. fetch.addAttribute("email", "http://schema.openid.net/contact/email", true);
21. fetch.addAttribute("fullname", "http://openid.net/schema/namePerson/friendly", true);
22. authReq.addExtension(fetch);
23. //重定向到OP认证
24. response.sendRedirect(authReq.getDestinationUrl(true));
接收来自OpenID提供者认证信息
1.  //获取响应参数列表
2.  ParameterList response = new ParameterList(request.getParameterMap());
3.  DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disc ");
4.  StringBuffer receivingURL = request.getRequestURL();
5.  String queryString = request.getQueryString();
6.  if (queryString != null && queryString.length() > 0)
7.      receivingURL.append("?").append(request.getQueryString());
8.  //根据参数列表,关联句柄以及url_query验证是否通过认证
9.  VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);
10. Identifier verified = verification.getVerifiedId();
11. if (verified != null) {
12.     if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
13.         FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
14.         List emails = fetchResp.getAttributeValues("email");
15.         email = (String) emails.get(0);
16.         List fullNames = fetchResp.getAttributeValues("fullname");
17.         fullName = (String) fullNames.get(0);
18.          // success..
19.     }
20. }
21. else
22.     // OpenID authentication failed

 

posted @ 2019-06-28 09:50  梦玄庭  阅读(1101)  评论(0编辑  收藏  举报