以GoogleOpenID 为例,试验了OAuth单点登录的用法:

  1. <dependency>
  2. <groupId>org.openid4java</groupId>
  3. <artifactId>openid4java</artifactId>
  4. <version>0.9.8</version>
  5. </dependency>
  1. import java.util.List;
  2.  
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5.  
  6. import org.openid4java.OpenIDException;
  7. import org.openid4java.consumer.ConsumerManager;
  8. import org.openid4java.consumer.VerificationResult;
  9. import org.openid4java.discovery.DiscoveryInformation;
  10. import org.openid4java.discovery.Identifier;
  11. import org.openid4java.message.AuthRequest;
  12. import org.openid4java.message.AuthSuccess;
  13. import org.openid4java.message.ParameterList;
  14. import org.openid4java.message.ax.AxMessage;
  15. import org.openid4java.message.ax.FetchRequest;
  16. import org.openid4java.message.ax.FetchResponse;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.stereotype.Controller;
  20. import org.springframework.web.bind.annotation.RequestMapping;
  21. import org.springframework.web.util.UriComponentsBuilder;
  22.  
  23. import com.google.common.base.Throwables;
  24.  
  25. @Controller
  26. @RequestMapping("/openid")
  27. @SuppressWarnings("rawtypes")
  28. public class SecurityOpenIDController {
  29.  
  30. public static final String GOOGLE_ENDPOINT = "https://www.google.com/accounts/o8/id";
  31. private static final Logger LOGGER = LoggerFactory.getLogger(SecurityOpenIDController.class);
  32.  
  33. public final ConsumerManager manager = new ConsumerManager();
  34.  
  35. @RequestMapping("/login")
  36. public void login(
  37. UriComponentsBuilder builder,
  38. HttpServletRequest request,
  39. HttpServletResponse response
  40. ) throws Exception
  41. {
  42. // configure the return_to URL where your application will receive
  43. // the authentication responses from the OpenID provider
  44. String returnUrl = builder.path("/openid/return").build().toUriString();
  45.  
  46. // --- Forward proxy setup (only if needed) ---
  47. // ProxyProperties proxyProps = new ProxyProperties();
  48. // proxyProps.setProxyName("proxy.example.com");
  49. // proxyProps.setProxyPort(8080);
  50. // HttpClientFactory.setProxyProperties(proxyProps);
  51.  
  52. // perform discovery on the user-supplied identifier
  53. List discoveries = manager.discover(GOOGLE_ENDPOINT);
  54.  
  55. // attempt to associate with the OpenID provider
  56. // and retrieve one service endpoint for authentication
  57. DiscoveryInformation discovered = manager.associate(discoveries);
  58.  
  59. // store the discovery information in the user's session
  60. request.getSession().setAttribute("openid-disc", discovered);
  61.  
  62. // obtain a AuthRequest message to be sent to the OpenID provider
  63. AuthRequest authReq = manager.authenticate(discovered, returnUrl);
  64.  
  65. // attribute Exchange
  66. FetchRequest fetch = FetchRequest.createFetchRequest();
  67. fetch.addAttribute("email", "http://axschema.org/contact/email", true);
  68. fetch.addAttribute("firstName", "http://axschema.org/namePerson/first", true);
  69. fetch.addAttribute("lastName", "http://axschema.org/namePerson/last", true);
  70.  
  71. // attach the extension to the authentication request
  72. authReq.addExtension(fetch);
  73.  
  74. if (!discovered.isVersion2()) {
  75. // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
  76. // The only method supported in OpenID 1.x
  77. // redirect-URL usually limited ~2048 bytes
  78. response.sendRedirect(authReq.getDestinationUrl(true));
  79. } else {
  80. // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
  81. response.sendRedirect(authReq.getDestinationUrl(true));
  82. }
  83. }
  84.  
  85. @RequestMapping("/return")
  86. public void verifyResponse(HttpServletRequest request) {
  87. String email = null;
  88. String lastName = null;
  89. String firstName = null;
  90.  
  91. try {
  92. // extract the parameters from the authentication response
  93. // (which comes in as a HTTP request from the OpenID provider)
  94. ParameterList response = new ParameterList(request.getParameterMap());
  95.  
  96. // retrieve the previously stored discovery information
  97. DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
  98.  
  99. // extract the receiving URL from the HTTP request
  100. StringBuffer receivingURL = request.getRequestURL();
  101. String queryString = request.getQueryString();
  102. if (queryString != null && queryString.length() > 0) {
  103. receivingURL.append("?").append(request.getQueryString());
  104. }
  105.  
  106. // verify the response; ConsumerManager needs to be the same
  107. // (static) instance used to place the authentication request
  108. VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);
  109.  
  110. // examine the verification result and extract the verified
  111. // identifier
  112. Identifier verified = verification.getVerifiedId();
  113. if (verified != null) {
  114. AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
  115.  
  116. if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
  117. FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
  118.  
  119. List emails = fetchResp.getAttributeValues("email");
  120. email = (String) emails.get(0);
  121.  
  122. List lastNames = fetchResp.getAttributeValues("lastName");
  123. lastName = (String) lastNames.get(0);
  124.  
  125. List firstNames = fetchResp.getAttributeValues("firstName");
  126. firstName = (String) firstNames.get(0);
  127.  
  128. LOGGER.debug("email: {}", email);
  129. LOGGER.debug("lastName: {}", lastName);
  130. LOGGER.debug("firstName: {}", firstName);
  131. }
  132. // success
  133.  
  134. // 在这里与安全框架集成 apache-shiro/spring-security
  135. // 这里要根据相关的信息自己定义Principal
  136. }
  137. } catch (OpenIDException e) {
  138. LOGGER.error(e.getMessage(), e);
  139. Throwables.propagate(e);
  140. }
  141. }
  142. }

spring-mvc 与 openid4java的更多相关文章

  1. 如何用Java类配置Spring MVC(不通过web.xml和XML方式)

    DispatcherServlet是Spring MVC的核心,按照传统方式, 需要把它配置到web.xml中. 我个人比较不喜欢XML配置方式, XML看起来太累, 冗长繁琐. 还好借助于Servl ...

  2. Spring MVC重定向和转发以及异常处理

    SpringMVC核心技术---转发和重定向 当处理器对请求处理完毕后,向其他资源进行跳转时,有两种跳转方式:请求转发与重定向.而根据要跳转的资源类型,又可分为两类:跳转到页面与跳转到其他处理器.对于 ...

  3. Spring MVC入门

    1.什么是SpringMvc Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 M ...

  4. Spring7:基于注解的Spring MVC(下篇)

    Model 上一篇文章<Spring6:基于注解的Spring MVC(上篇)>,讲了Spring MVC环境搭建.@RequestMapping以及参数绑定,这是Spring MVC中最 ...

  5. Spring6:基于注解的Spring MVC(上篇)

    什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...

  6. 高性能的关键:Spring MVC的异步模式

    我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表的文章,以一个更简单的视角,把异步模式讲清楚. 什 ...

  7. Java Spring mvc 操作 Redis 及 Redis 集群

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5941953.html 关于 Redis 集群搭建可以参考我的另一篇文章 Redis集群搭建与简单使用 R ...

  8. 深入分析Spring 与 Spring MVC容器

    1 Spring MVC WEB配置 Spring Framework本身没有Web功能,Spring MVC使用WebApplicationContext类扩展ApplicationContext, ...

  9. spring mvc DispatcherServlet详解之前传---FrameworkServlet

    做项目时碰到Controller不能使用aop进行拦截,从网上搜索得知:使用spring mvc 启动了两个context:applicationContext 和WebapplicationCont ...

  10. 我是如何进行Spring MVC文档翻译项目的环境搭建、项目管理及自动化构建工作的

    感兴趣的同学可以关注这个翻译项目 . 我的博客原文 和 我的Github 前段时间翻译的Spring MVC官方文档完成了第一稿,相关的文章和仓库可以点击以下链接.这篇文章,主要是总结一下这个翻译项目 ...

随机推荐

  1. 使用C#写windows服务

    首先,创建一个windows服务项目

  2. 如何让其他计算机访问我的计算机上数据库mysql

    第一种:能ping通,说明你们在同一个网络中,可以直接访问.你只要在你的登录用户中的帐号加上可外部访问就可以了...也就是授权.比如你的帐号是root   你可以进入mysql后, 你可以看到,每个帐 ...

  3. COM技术の组件

    什么是COM COM,Component Object Mode即组件对象模型.之所以称之为“模型”,是表明COM是一种编程规范(非具体代码),通过这种规范我们能够编写出语言无关的,可扩展的,内部变化 ...

  4. 一次编译Android源码实验

    注意,本文只供参考,是老文章 1.必要的软件环境 sudo apt-get install build-essential sudo apt-get install make sudo apt-get ...

  5. Python3基础 大于一个数的同时小于一个数

    镇场诗:---大梦谁觉,水月中建博客.百千磨难,才知世事无常.---今持佛语,技术无量愿学.愿尽所学,铸一良心博客.------------------------------------------ ...

  6. SQL事务回滚样例

    选课系统,当同意学号选课数量超过则回滚事务,符合条件则正常插入数据 --开始一个事务处理Begin Tran T1 --执行插入操作insert into Courselist values('201 ...

  7. 【leetcode❤python】235. Lowest Common Ancestor of a Binary Search Tree

    #-*- coding: UTF-8 -*- # Definition for a binary tree node.# class TreeNode(object):#     def __init ...

  8. 可是把ie67下面的bug改好了,其实很简单,ie67下面取出来的字符串是带有空格的,不知道为什么

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  9. [转]GameObject的Active与InActive

    GameObject的Active与InActive 1.Script可以控制InActive的GameObject,但前提是Script所依附的GameObject不能是InActive,一旦为In ...

  10. 将文件读取到内存、打印pe结构

    #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h&g ...