OAuth 2 Developers Guide--reference
Introduction
This is the user guide for the support for OAuth 2.0
. For OAuth 1.0, everything is different, so see its user guide.
This user guide is divided into two parts, the first for the OAuth 2.0 provider, the second for the OAuth 2.0 client.
OAuth 2.0 Provider
The OAuth 2.0 provider mechanism is responsible for exposing OAuth 2.0 protected resources. The configuration involves establishing the OAuth 2.0 clients that can access its protected resources on behalf of a user. The provider does this by managing and verifying the OAuth 2.0 tokens that can be used to access the protected resources. Where applicable, the provider must also supply an interface for the user to confirm that a client can be granted access to the protected resources (i.e. a confirmation page).
OAuth 2.0 Provider Implementation
The provider role in OAuth 2.0 is actually split between Authorization Service and Resource Service, and while these sometimes reside in the same application, with Spring Security OAuth you have the option to split them across two applications, and also to have multiple Resource Services that share an Authorization Service. The requests for the tokens are handled by Spring MVC controller endpoints, and access to protected resources is handled by standard Spring Security request filters. The following endpoints are required in the Spring Security filter chain in order to implement OAuth 2.0 Authorization Server:
AuthorizationEndpoint
is used to service requests for authorization. Default URL:/oauth/authorize
.TokenEndpoint
is used to service requests for access tokens. Default URL:/oauth/token
.
The following filter is required to implement an OAuth 2.0 Resource Server:
- The
OAuth2AuthenticationProcessingFilter
is used to load the Authentication for the request given an authenticated access token.
For all the OAuth 2.0 provider features, configuration is simplified using special Spring OAuth @Configuration
adapters. There is also XML namespace for OAuth configuration and the schema resides at http://www.springframework.org/schema/security/spring-security-oauth2.xsd. The namespace is http://www.springframework.org/schema/security/oauth2
.
Authorization Server Configuration
As you configure the Authorization Server, you have to consider the grant type that the client is to use to obtain an access token from the end-user (e.g. authorization code, user credentials, refresh token). The configuration of the server is used to provide implementations of the client details service and token services and to enable or disable certain aspects of the mechanism globally. Note, however, that each client can be configured specifically with permissions to be able to use certain authorization mechanisms and access grants. I.e. just because your provider is configured to support the "client credentials" grant type, doesn't mean that a specific client is authorized to use that grant type.
The @EnableAuthorizationServer
annotation is used to configure the OAuth 2.0 Authorization Server mechanism, together with any @Beans
that implement AuthorizationServerConfigurer
(there is a hander adapter implementation with empty methods). The following features are delegated to separate configurers that are created by Spring and passed into the AuthorizationServerConfigurer
:
ClientDetailsServiceConfigurer
: a configurer that defines the client details service. Client details can be initialized, or you can just refer to an existing store.AuthorizationServerSecurityConfigurer
: defines the authorization and token endpoints and the token services.
An important aspect of the provider configuration is the way that an authorization code is supplied to an OAuth client (in the authorization code grant). A authorization code is obtained by the OAuth client by directing the end-user to an authorization page where the user can enter her credentials, resulting in a redirection from the provider authorization server back to the OAuth client with the authorization code. Examples of this are elaborated in the OAuth 2 specification.
In XML there is an <authorization-server/>
element that is used in a similar way to configure the OAuth 2.0 Authorization Server.
Configuring Client Details
The ClientDetailsServiceConfigurer
(a callback from your AuthorizationServerConfigurer
) can be used used to define an in-memory or JDBC implementation of the client details service. Important attributes of a client are
clientId
: (required) the client id.secret
: (required for trusted clients) the client secret, if any.scope
: The scope to which the client is limited. If scope is undefined or empty (the default) the client is not limited by scope.authorizedGrantTypes
: Grasnt types that are authorized for the client to use. Default value is empty.authorities
: Authorities that are granted to the client (regular Spring Security authorities).
Client details can be updated in a running application by access the underlying store directly (e.g. database tables in the case ofJdbcClientDetailsService
) or through the ClientDetailsManager
interface (which both implementations or ClientDetailsService
also implement).
Managing Tokens
The AuthorizationServerTokenServices
interface defines the operations that are necessary to manage OAuth 2.0 tokens. Note the following:
- When an access token is created, the authentication must be stored so that the subsequent access token can reference it.
- The access token is used to load the authentication that was used to authorize its creation.
When creating your AuthorizationServerTokenServices
implementation, you may want to consider using the DefaultTokenServices
which creates tokens via random value and handles everything except for the persistence of the tokens which it delegates to a TokenStore
. The default store is an in-memory implementation, but there is also a jdbc version that may be suitable for your needs.
Grant Types
The grant types supported by the AuthorizationEndpoint
can be configured via the AuthorizationServerSecurityConfigurer
. By default all grant types are supported except password (see below for details of how to switch it on). The following properties affect grant types:
authenticationManager
: password grants are switched on by injecting anAuthenticationManager
.authorizationCodeServices
: defines the authorization code services (instance oforg.springframework.security.oauth2.provider.code.AuthorizationCodeServices
) for the auth code grantimplicitGrantService
: manages state during the imlpicit grant.tokenGranter
: theTokenGranter
(taking full control of the granting and ignoring the other properties above)
In XML grant types are included as child elements of the authorization-server
.
Configuring the Endpoint URLs
The AuthorizationServerSecurityConfigurer
has a pathMapping()
method. It takes two arguments:
- The default (framework implementation) URL path for the endpoint
- The custom path required (starting with a "/")
The URL paths provided by the framework are /oauth/authorize
(the authorization endpoint), /oauth/token
(the token endpoint),/oauth/confirm_access
(user posts approval for grants here) and /oauth/error
(used to render errors in the authorization server).
N.B. the Authorization endpoint /oauth/authorize
(or its mapped alternative) should be protected using Spring Security so that it is only accessible to authenticated users. The token endpoint is protected by default by Spring OAuth in the @Configuration
support using HTTP Basic authentication of the client secret, but not in XML (so in that case it should be protected explicitly).
In XML the <authorization-server/>
element has some attributes that can be used to change the default endpoint URLs in a similar way.
Customizing the Error Handling
Error handling in an Authorization Server uses standard Spring MVC features, namely @ExceptionHandler
methods in the endpoints themselves. Users can also provide a WebResponseExceptionTranslator
to the endpoints themselves which is the best way to change the content of the responses as opposed to the way they are rendered. The rendering of exceptions delegates to HttpMesssageConverters
(which can be added to the MVC configuration) in the case of token endpoint and to the OAuth error view (/oauth/error
) in the case of teh authorization endpoint. A whitelabel error endpoint is provided, but users probably need to provide a custom implementation (e.g. just add a @Controller
with@RequestMapping("/oauth/error")
).
Resource Server Configuration
A Resource Server (can be the same as the Authorization Server or a separate application) serves resources that are protected by the OAuth2 token. Spring OAuth provides a Spring Security authentication filter that implements this protection. You can switch it on with @EnableResourceServer
on an @Configuration
class, and configure it (as necessary) using a ResourceServerConfigurer
. The following features can be configured:
tokenServices
: the bean that defines the token services (instance ofResourceServerTokenServices
).resourceId
: the id for the resource (optional, but recommended and will be validated by the auth server if present).
The @EnableResourceServer
annotation adds a filter of type OAuth2AuthenticationProcessingFilter
to the Spring Security filter chain.
In XML there is a <resource-server/>
element with an id
attribute - this is the bean id for a servlet Filter
that can be added to the standard Spring Security chain.
Configuring An OAuth-Aware Expression Handler
You may want to take advantage of Spring Security's expression-based access control. An expression handler will be registered by default in the@EnableResourceServer
setup. The expressions include #oauth2.clientHasRole, #oauth2.clientHasAnyRole, and #oath2.denyClient which can be used to provide access based on the role of the oauth client (see OAuth2SecurityExpressionMethods
for a comprehensive list). In XML you can register a oauth-aware expression handler with the expression-handler
element of the regular <http/>
security configuration.
OAuth 2.0 Client
The OAuth 2.0 client mechanism is responsible for access the OAuth 2.0 protected resources of other servers. The configuration involves establishing the relevant protected resources to which users might have access. The client may also need to be supplied with mechanisms for storing authorization codes and access tokens for users.
Protected Resource Configuration
Protected resources (or "remote resources") can be defined using bean definitions of type OAuth2ProtectedResourceDetails
. A protected resource has the following properties:
id
: The id of the resource. The id is only used by the client to lookup the resource; it's never used in the OAuth protocol. It's also used as the id of the bean.clientId
: The OAuth client id. This is the id by which the OAuth provider identifies your client.clientSecret
: The secret associated with the resource. By default, no secret is empty.accessTokenUri
: The URI of the provider OAuth endpoint that provides the access token.scope
: Comma-separted list of strings specifying the scope of the access to the resource. By default, no scope will be specified.clientAuthenticationScheme
: The scheme used by your client to authenticate to the access token endpoint. Suggested values: "http_basic" and "form". Default: "http_basic". See section 2.1 of the OAuth 2 spec.
Different grant types have different concrete implementations of OAuth2ProtectedResourceDetails
(e.g. ClientCredentialsResource
for "client_credentials" grant type). For grant types that require user authorization there is a further property:
userAuthorizationUri
: The uri to which the user will be redirected if the user is ever needed to authorize access to the resource. Note that this is not always required, depending on which OAuth 2 profiles are supported.
In XML there is a <resource/>
element that can be used to create a bean of type OAuth2ProtectedResourceDetails
. It has attributes matching all the properties above.
Client Configuration
For the OAuth 2.0 client, configuration is simplified using @EnableOAuth2Client
. This does 2 things:
Creates a filter bean (with ID
oauth2ClientContextFilter
) to store the current request and context. In the case of needing to authenticate during a request it manages the redirection to and from the OAuth authentication uri.Creates a bean of type
AccessTokenRequest
in request scope. This can be used by authorization code (or implicit) grant clients to keep state related to individual users from colliding.
The filter has to be wired into the application (e.g. using a Servlet initializer or web.xml
configuration for a DelegatingFilterProxy
with the same name).
The AccessTokenRequest
can be used in an OAuth2RestTemplate
like this:
@Resource
@Qualifier("accessTokenRequest")
private AccessTokenRequest accessTokenRequest;
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestTemplate sparklrRestTemplate() {
return new OAuth2RestTemplate(sparklr(), new DefaultOAuth2ClientContext(accessTokenRequest));
}
The rest template is placed in session scope to keep the state for different users separate. Without that you would have to manage the equivalent data structure yourself on the server, mapping incoming requests to users, and associating each user with a separate instance of theOAuth2ClientContext
.
In XML there is a <client/>
element with an id
attribute - this is the bean id for a servlet Filter
that must be mapped as in the@Configuration
case to a DelegatingFilterProxy
(with the same name).
Accessing Protected Resources
Once you've supplied all the configuration for the resources, you can now access those resources. The suggested method for accessing those resources is by using the RestTemplate
introduced in Spring 3. OAuth for Spring Security has provided an extension of RestTemplate that only needs to be supplied an instance of OAuth2ProtectedResourceDetails
. To use it with user-tokens (authorization code grants) you should consider using the @EnableOAuth2Client
configuration (or the XML equivalent <oauth:rest-template/>
) which creates some request and session scoped context objects so that requests for different users do not collide at runtime.
Persisting Tokens in a Client
A client does not need to persist tokens, but it can be nice for users to not be required to approve a new token grant every time the client app is restarted. The ClientTokenServices
interface defines the operations that are necessary to persist OAuth 2.0 tokens for specific users. There is a JDBC implementation provided, but you can if you prefer implement your own service for storing the access tokens and associated authentication instances in a persistent database. If you want to use this feature you need provide a specially configured TokenProvider
to theOAuth2RestTemplate
e.g.
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestOperations restTemplate() {
OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(accessTokenRequest));
AccessTokenProviderChain provider = new AccessTokenProviderChain(Arrays.asList(new AuthorizationCodeAccessTokenProvider()));
provider.setClientTokenServices(clientTokenServices());
return template;
}
Customizations for Clients of External OAuth2 Providers
Some external OAuth2 providers (e.g. Facebook) do not quite implement the specification correctly, or else they are just stuck on an older version of the spec than Spring Security OAuth. To use those providers in your client application you might need to adapt various parts of the client-side infrastructure.
To use Facebook as an example, there is a Facebook feature in the tonr2
application (you need to change the configuration to add your own, valid, client id and secret - they are easy to generate on the Facebook website).
Facebook token responses also contain a non-compliant JSON entry for the expiry time of the token (they use expires
instead of expires_in
), so if you want to use the expiry time in your application you will have to decode it manually using a custom OAuth2SerializationService
.
reference:http://projects.spring.io/spring-security-oauth/docs/oauth2.html
OAuth 2 Developers Guide--reference的更多相关文章
- OAuth 2 Developers Guide
Introduction This is the user guide for the support for OAuth 2.0. For OAuth 1.0, everything is diff ...
- 转:Busy Developers' Guide to HSSF and XSSF Features
Busy Developers' Guide to Features Want to use HSSF and XSSF read and write spreadsheets in a hurry? ...
- Apache Struts 2 Documentation Core Developers Guide
http://struts.apache.org/docs/core-developers-guide.html
- oAuth 2.0 笔记
OAuth 2.0规范于2012年发布,很多大型互联网公司(比如:微信.微博.支付宝)对外提供的SDK中,授权部分基本上都是按这个规范来实现的. OAuth 2.0提供了4种基本的标准授权流程,最为复 ...
- 学习 OAuth2.0
基于浏览器 访问后跳到登录页面,登录成功后跳转到授权页面,授权成功后跳转到redirect_uri指定的地址. 1.请求授权. http://localhost:8080/oauth/authoriz ...
- 一文带你了解 OAuth2 协议与 Spring Security OAuth2 集成!
OAuth 2.0 允许第三方应用程序访问受限的HTTP资源的授权协议,像平常大家使用Github.Google账号来登陆其他系统时使用的就是 OAuth 2.0 授权框架,下图就是使用Github账 ...
- 基于TI Davinci架构的多核/双核开发高速扫盲(以OMAP L138为例),dm8168多核开发參考以及达芬奇系列资料user guide整理
基于TI Davinci架构的双核嵌入式应用处理器OMAPL138开发入门 原文转自http://blog.csdn.net/wangpengqi/article/details/8115614 感谢 ...
- OpenStreetMap(OSM) for developers
This article from: http://wiki.openstreetmap.org/wiki/Develop OpenStreetMap isn't just open data - i ...
- 【翻译】Flume 1.8.0 User Guide(用户指南) Sink
翻译自官网flume1.8用户指南,原文地址:Flume 1.8.0 User Guide 篇幅限制,分为以下5篇: [翻译]Flume 1.8.0 User Guide(用户指南) [翻译]Flum ...
随机推荐
- 【转】Application.mk 文件语法规范
原文网址:http://blog.sina.com.cn/s/blog_4c451e0e0100s6q4.html Application.mk file syntax specification A ...
- jquery放大镜
效果体验:http://runjs.cn/detail/dvygyp5t demo下载 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tra ...
- Oracle 给表添加主键和使ID自增、触发器、创建结构一样的表
1.关于主键:在建表时指定primary key字句即可:create table test( id number(6) primary key, name varchar2(30));如果是对于已经 ...
- hbase分页查询
为了广大技术爱好者学习netty,在这里帮新浪微博@nettying宣传下他出版的新书 <netty权威指南>@nettying兄在华为NIO实践多年,这本书是他的技术和经验的一个结晶.N ...
- HDU 1078 FatMouse and Cheese 记忆化搜索DP
直接爆搜肯定超时,除非你加了某种凡人不能想出来的剪枝...555 因为老鼠的路径上的点满足是递增的,所以满足一定的拓补关系,可以利用动态规划求解 但是复杂的拓补关系无法简单的用循环实现,所以直接采取记 ...
- 理解public,protected 以及 private
经常看到在类中看到public,protected,private以及它们在继承中表示的一些访问范围,很容易搞糊涂.我们首先要明白下面几点. 1.类的一个特征就是封装,public和private作用 ...
- 傲游浏览器4,傲游浏览器5如何一键批量打开url链接。
傲游浏览器批量打开网址的插件没用了.有很多网友发了方法也无法实现.实际上,是可以实现傲游浏览器4,傲游浏览器5一键批量打开url链接的.我来告诉大家如何来实现.最新的M5都能使用.在收藏夹添加一个收藏 ...
- OpenCV在Debug和Release两种模式下布恩那个同时运行的问题
首先,可以肯定的说,两者是可以随时切换进行运行的,若不能运行,必定是配置出了问题 以Debugx64和Releasex64为例: 在Releasex64模式下,我配置好了各种路径: 于是乎,我切换到D ...
- JVM 必备指南
简介 Java虚拟机(JVM)是Java应用的运行环境,从一般意义上来讲,JVM是通过规范来定义的一个虚拟的计算机,被设计用来解释执行从Java源码编译而来的字节码.更通俗地说,JVM是指对这个规范的 ...
- python 使用@property
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: s = Student() s.score = 9999 这显然不合逻辑.为了限制score的 ...