---
title: "spring-security-oauth使用笔记"
author: "bukebuhao"
date: "2011-12-30T16:42:53Z"
tags: []
categories: ["企业架构"]
slug: "spring-security-oauth"
draft: false
lastmod: "2011-12-31T15:56:53Z"
id: 1330623
url: "https://bukebuhao.iteye.com/blog/1330623"
---

最新公司的项目也搞对外开放，也就是加入开放的潮流。目前有很多大公司都已开放api，为何我们公司还搞的，我们搞的主要目的不是为了对外开放api，只是方便第三方应用获取用户授权的信息，整合所有的有效资源，因此来说我们采用的oauth协议是最简单最实用的。由于公司自己没有实力，只能依靠开源的实现，经过对多方考察，感觉spring-security-oauth实现的最好，大家可参考http://netment.iteye.com/blog/945402博客，他们也认为spring-security-oauth不错的。不过，我自己去实际考察又发现，不只是有oauth1.0和oauth2.0，而且虽然都是基于security的实现，竟然有两种不同的实现版本，主要讨论的是oauth2.0

**第一个版本**

网址是http://svn.codehaus.org/spring-security-oauth/branches/SS3/，已提交到maven仓库了groupId=org.codehaus.spring-security-oauth，这个版本实现的相对比较简单，只支持内存保存token,而且结合security比较紧密，非常适合学习。

oauth2.0的基本流程，1.请求用户授权，2.获取code，3.获取token，4.请求资源验证token。 因此，只需要关注WebServerOAuth2Filter，BasicUserApprovalFilter，OAuth2AuthorizationFilter，OAuth2ProtectedResourceFilter，其中WebServerOAuth2Filter是/oauth/user/authorize入口，验证code无效， unapprovedAuthenticationHandler跳转到*/oauth/confirm\_access，用户提交之后* BasicUserApprovalFilter拦截之后，获取授权参数，就交给 WebServerOAuth2Filter获取code,获取code返回到client，然后client再次请求 /oauth/authorize,OAuth2AuthorizationFilter获取token，之后只要请求的时候带上token由 OAuth2ProtectedResourceFilter负责验证，是否可获取用户资源。

**第二个版本**

网址https://github.com/SpringSource/spring-security-oauth/wiki/oauth2,这个版本oauth2.0的基本所有功能都已实现,不过还是处于内部测试当中，spring-security-oauth2-1.0.0.BUILD-SNAPSHOT，需要自己手动下载后利用maven编译成jar，其中第一次编译的时候,去掉 &lt;module&gt;samples&lt;/module&gt;，否则就会出现编译错误。我们公司目前的程序开发也处于内部测试当中，因此，大胆采用该版本。现在详细论述一下，具体的实现流程。

按照oauth2.0的协议规定，oauth2.0大体的流程如下：

![](/upload/picture/pic/105186/d166ccfe-452b-3873-81e0-3fc8788d5c8b.png)

具体的协议可参考http://oauth.net/2/，我们这里主要说明一下Authorization Grant，主要有四类Authorization Code，Implicit，Resource Owner Password Credentials，Client Credentials，这里主要介绍服务端Authorization Code授权流程，基本流程：1.请求用户授权，2.获取code，3.获取token，4.请求资源验证token。

- **请求用户授权和获取code**

首先要请求用户授权，其次才会生成一个临时的code.可参考一下，我简单画得一个流程图如下:

![](/upload/picture/pic/105184/80020a0c-f691-3195-bffc-907f1f423c4d.png)

 

**code关联类如下：**

 

![](/upload/picture/pic/105182/b3ea66df-88e1-34c1-b917-e63876becc95.png)

- **获取token** ![](/upload/picture/pic/105180/7b454480-6b2c-3df8-9dfb-53556cd712be.png)

**token相关的类图**

![](/upload/picture/pic/105178/9fd3035b-8784-3e5a-bbaf-a54295cafdc2.png)

- **请求资源验证token**

![](/upload/picture/pic/105188/161ac3e3-1491-3429-913d-7ddb33fa76ef.png)

大体的流程基本如上，具体的xml配置请参考sparklr2的src/main/webapp/WEB-INF/spring-servlet.xml。