spring-mvc 与 openid4java
以GoogleOpenID 为例,试验了OAuth单点登录的用法:
<dependency>
<groupId>org.openid4java</groupId>
<artifactId>openid4java</artifactId>
<version>0.9.8</version>
</dependency>
import java.util.List; 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.UriComponentsBuilder; import com.google.common.base.Throwables; @Controller
@RequestMapping("/openid")
@SuppressWarnings("rawtypes")
public class SecurityOpenIDController { public static final String GOOGLE_ENDPOINT = "https://www.google.com/accounts/o8/id";
private static final Logger LOGGER = LoggerFactory.getLogger(SecurityOpenIDController.class); public final ConsumerManager manager = new ConsumerManager(); @RequestMapping("/login")
public void login(
UriComponentsBuilder builder,
HttpServletRequest request,
HttpServletResponse response
) throws Exception
{
// configure the return_to URL where your application will receive
// the authentication responses from the OpenID provider
String returnUrl = builder.path("/openid/return").build().toUriString(); // --- 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(GOOGLE_ENDPOINT); // 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
request.getSession().setAttribute("openid-disc", discovered); // obtain a AuthRequest message to be sent to the OpenID provider
AuthRequest authReq = manager.authenticate(discovered, returnUrl); // attribute Exchange
FetchRequest fetch = FetchRequest.createFetchRequest();
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); // attach the extension to the authentication request
authReq.addExtension(fetch); if (!discovered.isVersion2()) {
// Option 1: GET HTTP-redirect to the OpenID Provider endpoint
// The only method supported in OpenID 1.x
// redirect-URL usually limited ~2048 bytes
response.sendRedirect(authReq.getDestinationUrl(true));
} else {
// Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
response.sendRedirect(authReq.getDestinationUrl(true));
}
} @RequestMapping("/return")
public void verifyResponse(HttpServletRequest request) {
String email = null;
String lastName = null;
String firstName = null; try {
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList response = new ParameterList(request.getParameterMap()); // retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc"); // extract the receiving URL from the HTTP request
StringBuffer receivingURL = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(request.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");
email = (String) emails.get(0); List lastNames = fetchResp.getAttributeValues("lastName");
lastName = (String) lastNames.get(0); List firstNames = fetchResp.getAttributeValues("firstName");
firstName = (String) firstNames.get(0); LOGGER.debug("email: {}", email);
LOGGER.debug("lastName: {}", lastName);
LOGGER.debug("firstName: {}", firstName);
}
// success // 在这里与安全框架集成 apache-shiro/spring-security
// 这里要根据相关的信息自己定义Principal
}
} catch (OpenIDException e) {
LOGGER.error(e.getMessage(), e);
Throwables.propagate(e);
}
}
}
spring-mvc 与 openid4java的更多相关文章
- 如何用Java类配置Spring MVC(不通过web.xml和XML方式)
DispatcherServlet是Spring MVC的核心,按照传统方式, 需要把它配置到web.xml中. 我个人比较不喜欢XML配置方式, XML看起来太累, 冗长繁琐. 还好借助于Servl ...
- Spring MVC重定向和转发以及异常处理
SpringMVC核心技术---转发和重定向 当处理器对请求处理完毕后,向其他资源进行跳转时,有两种跳转方式:请求转发与重定向.而根据要跳转的资源类型,又可分为两类:跳转到页面与跳转到其他处理器.对于 ...
- Spring MVC入门
1.什么是SpringMvc Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 M ...
- Spring7:基于注解的Spring MVC(下篇)
Model 上一篇文章<Spring6:基于注解的Spring MVC(上篇)>,讲了Spring MVC环境搭建.@RequestMapping以及参数绑定,这是Spring MVC中最 ...
- Spring6:基于注解的Spring MVC(上篇)
什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...
- 高性能的关键:Spring MVC的异步模式
我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表的文章,以一个更简单的视角,把异步模式讲清楚. 什 ...
- Java Spring mvc 操作 Redis 及 Redis 集群
本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5941953.html 关于 Redis 集群搭建可以参考我的另一篇文章 Redis集群搭建与简单使用 R ...
- 深入分析Spring 与 Spring MVC容器
1 Spring MVC WEB配置 Spring Framework本身没有Web功能,Spring MVC使用WebApplicationContext类扩展ApplicationContext, ...
- spring mvc DispatcherServlet详解之前传---FrameworkServlet
做项目时碰到Controller不能使用aop进行拦截,从网上搜索得知:使用spring mvc 启动了两个context:applicationContext 和WebapplicationCont ...
- 我是如何进行Spring MVC文档翻译项目的环境搭建、项目管理及自动化构建工作的
感兴趣的同学可以关注这个翻译项目 . 我的博客原文 和 我的Github 前段时间翻译的Spring MVC官方文档完成了第一稿,相关的文章和仓库可以点击以下链接.这篇文章,主要是总结一下这个翻译项目 ...
随机推荐
- Mysql-学习笔记(==》事件 十二)
事件 计划任务(定期定时执行) -- 查看当前mysql数据库是否开启时间功能,默认关闭SHOW VARIABLES LIKE 'event_scheduler'; -- event_schedule ...
- Nhibernate中CreateSQLQuery用法实例
说明: 使用原生SQL查询时,若要通过addEntity方法引入对象,则查询结果列中必须包含该对象的所有属性,否则会抛出System.IndexOutOfRangeException异常. 结论: 若 ...
- 万年历---java版
程序难点 : 1. 每年每个月有多少天? 2. 每个月的1号是星期几? 3. 每年的2月份是多少天? 难点解析 : 1. 每年每个月除去1 3 5 7 8 10 12是31天以外, 其他月份(除去2月 ...
- LNMP(linux+nginx+mysql+php)服务器环境配置
一.简介 Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为 “engine X”, 是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服 ...
- mysql正则匹配解决查询一个字段是否在另一个字段中
select b.filter_name , count(*) from at_goods a , at_search_filter bwhere a.application REGEXP b.fil ...
- DevExpress Crack
开发者论坛 DevExpressComponents-16.1.6.16270.exe http://www.dxper.net/thread-7440-1-1.html http://www.dxp ...
- GBrowse配置相关资料
GBrowse配置相关资料(形状.颜色.配置.gff3) http://gmod.org/wiki/Glyphs_and_Glyph_Optionshttp://gmod.org/wiki/GBrow ...
- virtualenv -- python虚拟沙盒(linux版本)
有人说:virtualenv.fabric 和 pip 是 pythoneer 的三大神器. 不管认不认同,至少要先认识一下,pip现在倒是经常用到,virtualenv第一次听说,不过,总得尝试一下 ...
- C# WPF MVVM 实战 – 5- 用绑定,通过 VM 设置 View 的控件焦点
本文介绍在 MVVM 中,如何用 ViewModel 控制焦点. 这焦点设置个东西嘛,有些争论.就是到底要不要用 ViewModel 来控制视图的键盘输入焦点.这里不讨论,假设你就是要通过 VM,设置 ...
- Web开发——Tomcat的配置
1.选择Tomcat 1.Apache官网http://apache.org/ 2.Tomcat官网http://tomcat.apache.org/ 3.Tomcat下载地址http://tomca ...