spring OAuth 2 Developers Guide 英译汉

来源:互联网 发布:紫萱和徐长卿知乎 编辑:程序博客网 时间:2024/06/10 10:07
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.
 For both the provider and the client, the best source of sample code is the integration tests and sample apps.
介绍

这是OAuth 2.0的支持用户指南。 对于OAuth 1.0,一切都是不同的,所以看到它的用户指南。

本用户指南分为两部分,第一部分为OAuth 2.0提供者,第二部分为OAuth 2.0客户端。
对于提供商和客户端,示例代码的最佳来源是集成测试和示例应用程序。
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 independently or on behalf of a
user.
The provider does this by managing and verifying the OAuth 2.0 tokens 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提供程序

OAuth 2.0提供者机制负责公开OAuth 2.0受保护的资源。
该配置包括建立可独立或代表用户访问其受保护资源的OAuth 2.0客户端。
提供者通过管理和验证用于访问受保护资源的OAuth 2.0令牌来实现。
在适用情况下,提供商还必须为用户提供接口,以确认客户端可以被授权访问受保护的资源(即确认页面)。
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:
OAuth 2.0提供程序实现

OAuth 2.0中的提供者角色实际上是在授权服务和资源服务之间分割的,
而有时它们位于同一个应用程序中,使用Spring Security OAuth,您可以选择在两个应用程序之间进行拆分,
并且还可以共享多个资源服务 授权服务。
令牌的请求由Spring MVC控制器端点处理,对受保护资源的访问由标准的Spring Security请求过滤器处理。
 为了实现OAuth 2.0授权服务器,Spring Security过滤器链中需要以下端点:
    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.
AuthorizationEndpoint用于服务请求授权。 默认URL:/ oauth / authorize。
TokenEndpoint用于服务访问令牌的请求。 默认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
an 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.
实施OAuth 2.0资源服务器需要以下过滤器:

     OAuth2AuthenticationProcessingFilter用于加载授权认证访问令牌的请求的身份验证。

对于所有OAuth 2.0提供程序的功能,使用特殊的Spring OAuth @Configuration适配器可简化配置。
 还有一个用于OAuth配置的XML命名空间,并且模式位于http://www.springframework.org/schema/security/spring-security-oauth2.xsd。
命名空间是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 handy adapter implementation with empty methods). The following features are
delegated to separate configurers that are created by Spring and passed into the AuthorizationServerConfigurer:
授权服务器配置

在配置授权服务器时,您必须考虑客户端用于从最终用户获取访问令牌(例如授权代码,用户凭据,刷新令牌)的授权类型。
服务器的配置用于提供客户端详细信息服务和令牌服务的实现,并且启用或禁用全局机制的某些方面。
但是请注意,每个客户端都可以特别配置,以便能够使用某些授权机制和访问授权。
即只是因为您的提供商配置为支持“客户端凭据”授权类型,并不意味着特定客户端被授权使用该授权类型。

@EnableAuthorizationServer注释用于配置OAuth 2.0授权服务器机制,
以及实现AuthorizationServerConfigurer的任何@Beans(有一个方便的适配器实现)。
将以下功能委派给由Spring创建并传递给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 security constraints on the token endpoint.
    AuthorizationServerEndpointsConfigurer: 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.

ClientDetailsServiceConfigurer:定义客户端详细信息服务的配置程序。
客户端的详细信息可以初始化,也可以参考现有的存储。
     AuthorizationServerSecurityConfigurer:定义令牌端点上的安全约束。
     AuthorizationServerEndpointsConfigurer:定义授权和令牌端点和令牌服务。

提供商配置的一个重要方面是授权代码提供给OAuth客户端(授权代码授权)的方式。
授权代码由OAuth客户端通过将最终用户指向用户可以输入其凭据的授权页面获得,
导致从提供商授权服务器重定向到具有授权码的OAuth客户端。 这在OAuth 2规范中有详细说明。

在XML中,有一个<authorization-server />元素以类似的方式用于配置OAuth 2.0授权服务器。

Configuring Client Details

The ClientDetailsServiceConfigurer (a callback from your AuthorizationServerConfigurer) can be 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: Grant 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 of
JdbcClientDetailsService) or through the ClientDetailsManager interface (which both implementations of ClientDetailsService also
implement).

    NOTE: the schema for the JDBC service is not packaged with the library (because there are too many variations you might like to
use in practice), but there is an example you can start from in the test code in github.
配置客户端详细信息

ClientDetailsS​​erviceConfigurer(来自AuthorizationServerConfigurer的回调)可用于定义客户端详细信息服务的内存或JDBC实现。
客户端的重要属性是

    clientId:(必需)客户端ID。
    secret:(可信客户需要)客户机密码(如有)。
     scope:客户端受限的范围。如果范围未定义或为空(默认值),客户端不受范围限制。
    authorizedGrantTypes:授予客户端使用的授权类型。默认值为空。
    authorities:授予客户的当局(普通的Spring Security Authority)。

可以通过直接访问底层store,例如在JdbcClientDetailsS​​ervice的情况下的数据库表)或通过ClientDetailsManager接口(ClientDetailsS​​ervice的两个实现也都实现)来更新运行的应用程序中的客户端详细信息。

    注意:JDBC服务的架构未与库一起打包(因为在实践中可能需要使用太多变体),而是可以从github中的测试代码中开始。
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 resources accepting the access token can reference it
later.
    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 has
many strategies that can be plugged in to change the format and storage of access tokens. By default it 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 are some other implementations available. Here's a description with some discussion of each of them
管理令牌

AuthorizationServerTokenServices接口定义了管理OAuth 2.0令牌所必需的操作。 请注意以下事项:

     当创建访问令牌时,必须存储身份验证,以便接受访问令牌的资源可以稍后引用。
     访问令牌用于加载用于授权其创建的认证。

创建AuthorizationServerTokenServices实现时,
您可能需要考虑使用具有许多可插入策略的DefaultTokenServices来更改访问令牌的格式和存储。
默认情况下,它通过随机值创建令牌,并处理除TokenStore所代理的令牌的持久性以外的所有内容。
 默认存储是内存中的实现,但还有一些其他可用的实现。
 这是一个关于每一个的一些讨论的描述


    The default InMemoryTokenStore is perfectly fine for a single server (i.e. low traffic and no hot swap to a backup server in the
case of failure). Most projects can start here, and maybe operate this way in development mode, to make it easy to start a server with
no dependencies.

    The JdbcTokenStore is the JDBC version of the same thing, which stores token data in a relational database. Use the JDBC version
if you can share a database between servers, either scaled up instances of the same server if there is only one, or the Authorization
and Resources Servers if there are multiple components. To use the JdbcTokenStore you need "spring-jdbc" on the classpath.

    The JSON Web Token (JWT) version of the store encodes all the data about the grant into the token itself (so no back end store at
all which is a significant advantage). One disadvantage is that you can't easily revoke an access token, so they normally are granted
with short expiry and the revocation is handled at the refresh token. Another disadvantage is that the tokens can get quite large if
you are storing a lot of user credential information in them. The JwtTokenStore is not really a "store" in the sense that it doesn't
persist any data, but it plays the same role of translating betweeen token values and authentication information in the
DefaultTokenServices.

    NOTE: the schema for the JDBC service is not packaged with the library (because there are too many variations you might like to
use in practice), but there is an example you can start from in the test code in github. Be sure to @EnableTransactionManagement to
prevent clashes between client apps competing for the same rows when tokens are created. Note also that the sample schema has explicit
PRIMARY KEY declarations - these are also necessary in a concurrent environment.

默认的InMemoryTokenStore对于单个服务器是完全正常的(即,在出现故障的情况下,流量较低且没有热插拔备份服务器)。
大多数项目可以从这里开始,也可以在开发模式下运行,以便轻松启动没有依赖关系的服务器。

    JdbcTokenStore是同一件事的JDBC版本,它将令牌数据存储在关系数据库中。
如果您可以在服务器之间共享数据库,则可以使用JDBC版本,如果只有一个,则扩展同一服务器的实例,或者如果有多个组件,
则授权和资源服务器。要使用JdbcTokenStore,您需要在类路径上使用“spring-jdbc”。

    商店的JSON Web令牌(JWT)版本将所有关于授权的数据编码到令牌本身(因此,根本没有后端存储是一个显着的优势)。
一个缺点是您不能轻易地撤销访问令牌,因此通常被授予短期到期权,撤销在刷新令牌处理。
另一个缺点是,如果您在其中存储了大量用户凭据信息,令牌可能会变得非常大。
JwtTokenStore不是真正的“存储”,它不会保留任何数据,
而是在DefaultTokenServices中翻译令牌值和身份验证信息之间起到相同的作用。

    注意:JDBC服务的架构未与库一起打包(因为在实践中可能需要使用太多变体),而是可以从github中的测试代码中开始。
确保@EnableTransactionManagement可以防止在创建令牌时竞争相同行的客户端应用程序之间的冲突。
还要注意,示例模式有明确的PRIMARY KEY声明 - 这些在并发环境中也是必需的。
JWT Tokens

To use JWT tokens you need a JwtTokenStore in your Authorization Server. The Resource Server also needs to be able to decode the
tokens so the JwtTokenStore has a dependency on a JwtAccessTokenConverter, and the same implementation is needed by both the
Authorization Server and the Resource Server. The tokens are signed by default, and the Resource Server also has to be able to verify
the signature, so it either needs the same symmetric (signing) key as the Authorization Server (shared secret, or symmetric key), or
it needs the public key (verifier key) that matches the private key (signing key) in the Authorization Server (public-private or
asymmetric key). The public key (if available) is exposed by the Authorization Server on the /oauth/token_key endpoint, which is
secure by default with access rule "denyAll()". You can open it up by injecting a standard SpEL expression into the
AuthorizationServerSecurityConfigurer (e.g. "permitAll()" is probably adequate since it is a public key).

To use the JwtTokenStore you need "spring-security-jwt" on your classpath (you can find it in the same github repository as Spring
OAuth but with a different release cycle).
JWT令牌

要使用JWT令牌,您需要授权服务器中的JwtTokenStore。
资源服务器还需要能够对令牌进行解码,以便JwtTokenStore具有对JwtAccessTokenConverter的依赖
性,并且授权服务器和资源服务器都需要相同的实现。
默认情况下,令牌被签名,资源服务器还必须能够验证签名,因此它需要与授权服务器(共享密钥或对称
密钥)相同的对称(签名)密钥,或者需要公共密钥(验证者密钥),
其与授权服务器中的私钥(签名密钥)匹配(公私属或非对称密钥)。
公钥(如果可用)由授权服务器在/ oauth / token_key端点公开,默认情况下,
访问规则为“denyAll()”。
您可以通过在AuthorizationServerSecurityConfigurer中注入标准的Spel表达式来打开它
(例如,“permitAll()”可能是足够的,因为它是公钥)。

要使用JwtTokenStore,您需要在类路径中使用“spring-security-jwt”(您可以在与Spring OAuth相同的github存储库中找到它,但具有不同的发行周期)

Grant Types

The grant types supported by the AuthorizationEndpoint can be configured via the AuthorizationServerEndpointsConfigurer. 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 an AuthenticationManager.
    userDetailsService: if you inject a UserDetailsService or if one is configured globally anyway (e.g. in a
GlobalAuthenticationManagerConfigurer) then a refresh token grant will contain a check on the user details, to ensure that the account
is still active
    authorizationCodeServices: defines the authorization code services (instance of AuthorizationCodeServices) for the auth code
grant.
    implicitGrantService: manages state during the imlpicit grant.
    tokenGranter: the TokenGranter (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.
Grant类型

AuthorizationEndpoint支持的授权类型可以通过AuthorizationServerEndpointsConfigurer进行配置。
默认情况下,所有授权类型均受支持,除了密码(有关如何切换它的详细信息,请参见下文)。
以下属性会影响授权类型:

    authenticationManager:通过注入AuthenticationManager来打开密码授权。
    userDetailsS​​ervice:如果您注入UserDetailsS​​ervice或者全局配置(例如在GlobalAuthenticationManagerConfigurer中),
    则刷新令牌授权将包含对用户详细信息的检查,以确保该帐户仍然处于活动状态
    authorizationCodeServices:定义授权码服务(AuthorizationCodeServices的实例)用于验证码授权。
    implicitGrantService:在imlpicit授权期间管理状态。
    tokenGranter:TokenGranter(完全控制授权和忽略上面的其他属性)

在XML授权类型中,作为授权服务器的子元素。
Configuring the Endpoint URLs

The AuthorizationServerEndpointsConfigurer 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), /oauth/error (used to render errors in the authorization server),
/oauth/check_token (used by Resource Servers to decode access tokens), and /oauth/token_key (exposes public key for token verification
if using JWT tokens).

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. For instance using a standard Spring Security WebSecurityConfigurer:
配置端点URL

AuthorizationServerEndpointsConfigurer具有一个pathMapping()方法。 它有两个参数:

     端点的默认(框架实现)URL路径
     需要的自定义路径(以“/”开头)

由框架提供的URL路径为/ oauth / authorize(授权端点),
/ oauth / token(令牌端点),
/ oauth / confirm_access(用户在此批准资助),
/ oauth / error(用于呈现错误 在授权服务器中)/ oauth / check_token(由资源服务器用于解码访问令牌)
和/ oauth / token_key(如果使用JWT令牌,则公开
用于令牌验证的公钥)。

N.B. 授权端点/ oauth / authorize(或其映射的备选方案)应使用Spring Security进行保护,
以使其只能由经过身份验证的用户访问。 例如使用标准的
Spring Security WebSecurityConfigurer:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests().antMatchers("/login").permitAll().and()
        // default protection for all resources (including /oauth/authorize)
            .authorizeRequests()
                .anyRequest().hasRole("USER")
        // ... more configuration, e.g. for form login
    }




    Note: if your Authorization Server is also a Resource Server then there is another security filter chain with lower priority
controlling the API resources. Fo those requests to be protected by access tokens you need their paths not to be matched by the ones
in the main user-facing filter chain, so be sure to include a request matcher that picks out only non-API resources in the
WebSecurityConfigurer above.

The token endpoint is protected for you by default by Spring OAuth in the @Configuration support using HTTP Basic authentication of
the client secret. This is not the case in XML (so 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.
The /check_token endpoint has to be explicitly enabled (with the check-token-enabled attribute).
注意:如果您的授权服务器也是资源服务器,那么还有另一个优先级较低的安全过滤器链控制API资源。
通过访问令牌来保护这些请求,您需要将其路径与主用户面向过滤器链中的路径不匹配,
因此请务必在上述WebSecurityConfigurer中包含一个仅选择非API资源的请求匹配器。

默认情况下,令牌端点在使用HTTP Basic身份验证的客户机密码的@Configuration支持中由Spring OAuth保护。
 在XML中不是这样(因此应该明确保护)。

在XML中,<authorization-server />元素具有一些可用于以类似方式更改默认端点URL的属性。
必须明确地启用/ check_token端点(启用启用检查令的属性)。

Customizing the UI

Most of the Authorization Server endpoints are used primarily by machines, but there are a couple of resource that need a UI and those
are the GET for /oauth/confirm_access and the HTML response from /oauth/error. They are provided using whitelabel implementations in
the framework, so most real-world instances of the Authorization Server will want to provide their own so they can control the styling
and content. All you need to do is provide a Spring MVC controller with @RequestMappings for those endpoints, and the framework
defaults will take a lower priority in the dispatcher. In the /oauth/confirm_access endpoint you can expect an AuthorizationRequest
bound to the session carrying all the data needed to seek approval from the user (the default implementation is
WhitelabelApprovalEndpoint so look there for a starting point to copy). You can grab all the data from that request and render it
however you like, and then all the user needs to do is POST back to /oauth/authorize with information about approving or denying the
grant. The request parameters are passed directly to a UserApprovalHandler in the AuthorizationEndpoint so you can interpret the data
more or less as you please. The default UserApprovalHandler depends on whether or not you have supplied an ApprovalStore in your
AuthorizationServerEndpointsConfigurer (in which case it is an ApprovalStoreUserApprovalHandler) or not (in which case it is a
TokenStoreUserApprovalHandler). The standard approval handlers accept the following:

自定义UI

大多数授权服务器端点主要由机器使用,但有一些资源需要一个UI,
那些是/ oauth / confirm_access的GET和/ oauth / error的HTML响应。
它们是在框架中使用白名单实现提供的,
因此授权服务器的大多数真实世界实例都希望提供自己的实例,
以便他们可以控制样式和内容。
所有您需要做的是为这些端点提供一个具有@RequestMappings的Spring MVC控制器,
并且框架默认在调度程序中占用较低的优先级。
在/ oauth / confirm_access端点中,
您可以期望授权对象会话承载所有需要从用户获得批准的数据(默认实现为WhitelabelApprovalEndpoint,因此请查看
复制起始点)。
您可以从该请求中获取所有数据,然后根据需要进行渲染,
然后所有用户需要执行的操作是使用/ oauth / authorize来查看有关批准或拒绝授权的信息。
请求参数直接传递给AuthorizationEndpoint中的UserApprovalHandler,
因此您可以随便解释数据。
默认的UserApprovalHandler取决于您是否在AuthorizationServerEndpointsConfigurer中提供了一个ApprovalStore(在这种情况下它是一个
ApprovalStoreUserApprovalHandler)(在这种情况下它是一个TokenStoreUserApprovalHandler)。
标准审批处理程序接受以下内容:


    TokenStoreUserApprovalHandler: a simple yes/no decision via user_oauth_approval equals to "true" or "false".

    ApprovalStoreUserApprovalHandler: a set of scope.* parameter keys with "*" equal to the scopes being requested. The value of the
parameter can be "true" or "approved" (if the user approved the grant) else the user is deemed to have rejected that scope. A grant is
successful if at least one scope is approved.

    NOTE: don't forget to include CSRF protection in your form that you render for the user. Spring Security is expecting a request
parameter called "_csrf" by default (and it provides the value in a request attribute). See the Spring Security user guide for more
information on that, or look at the whitelabel implementation for guidance.


TokenStoreUserApprovalHandler:通过user_oauth_approval的简单的是/否决定等于“true”或“false”。

     ApprovalStoreUserApprovalHandler:一组范围。*参数键与“*”等于所请求的范围。
参数的值可以是“true”或“approved”(如果用户批准了授权),则该用户被认为已经拒绝了该范围。
如果批准了至少一个范围,则grant是成功的。

     注意:不要忘记在您为用户呈现的表单中包含CSRF保护。
     默认情况下,Spring Security正期待一个名为“_csrf”的请求参数(它在请求属性中提供值
)。 有关更多信息,请参阅Spring Security用户指南,或查看whitelabel实现的指导。
Enforcing SSL

Plain HTTP is fine for testing but an Authorization Server should only be used over SSL in production. You can run the app in a secure
container or behind a proxy and it should work fine if you set the proxy and the container up correctly (which is nothing to do with
OAuth2). You might also want to secure the endpoints using Spring Security requiresChannel() constraints. For the /authorize endpoint
is up to you to do that as part of your normal application security. For the /token endpoint there is a flag in the
AuthorizationServerEndpointsConfigurer that you can set using the sslOnly() method. In both cases the secure channel setting is
optional but will cause Spring Security to redirect to what it thinks is a secure channel if it detects a request on an insecure
channel.
执行SSL

普通HTTP对于测试是很好的,但授权服务器只能在生产中使用SSL。
您可以在安全容器或代理服务器后面运行应用程序,如果您正确设置代理和容器(这与
OAuth2无关),
则应该可以正常运行。
您也可能希望使用Spring Security requireChannel()约束保护端点。
对于/授权终结点,您可以将其作为正常应用
程序安全性的一部分。
对于/ token端点,在AuthorizationServerEndpointsConfigurer中有一个可以使用sslOnly()方法设置的标志。
在这两种情况下,
安全通道设置是可选的,但是如果Spring Security在不安全的通道上检测到请求,
则会导致Spring Security重定向到安全通道。

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. The whitelabel error endpoint is provided for HTML responses, but users probably need to provide a custom
implementation (e.g. just add a @Controller with @RequestMapping("/oauth/error")).

自定义错误处理

授权服务器中的错误处理使用标准的Spring MVC功能,即端点本身的@ExceptionHandler方法。
用户还可以向端点本身提供WebResponseExceptionTranslator
,这是更改响应内容的最佳方式,而不是渲染方式。
在授权端点的情况下,在令牌端点和OAuth错误视图(/ oauth / error)的情况下,
异常的呈现委托给HttpMesssageConverters(可以添加到MVC配置中)。
为HTML响应提供了白名单错误端点,但用户可能需要提供自定义实现(例如,只需添加@Controller与
@RequestMapping(“/ oauth / error”))。

Mapping User Roles to Scopes

It is sometimes useful to limit the scope of tokens not only by the scopes assigned to the client, but also according to the user's
own permissions. If you use a DefaultOAuth2RequestFactory in your AuthorizationEndpoint you can set a flag checkUserScopes=true to
restrict permitted scopes to only those that match the user's roles. You can also inject an OAuth2RequestFactory into the
TokenEndpoint but that only works (i.e. with password grants) if you also install a TokenEndpointAuthenticationFilter - you just need
to add that filter after the HTTP BasicAuthenticationFilter. Of course, you can also implement your own rules for mapping scopes to
roles and install your own version of the OAuth2RequestFactory. The AuthorizationServerEndpointsConfigurer allows you to inject a
custom OAuth2RequestFactory so you can use that feature to set up a factory if you use @EnableAuthorizationServer.

将用户角色映射到范围

限制令牌范围不仅仅是分配给客户端的范围,还可以根据用户自己的权限来进行限制。
如果您在AuthorizationEndpoint中使用DefaultOAuth2RequestFactory,
您可以设置一个标志checkUserScopes = true,以将允许的范围限制为与用户角色匹配的范围。
您也可以将OAuth2RequestFactory注入到TokenEndpoint中,
但只有在安装了TokenEndpointAuthenticationFilter的情况下才可以使用(即使用密码授权) - 您只需在
HTTP BasicAuthenticationFilter之后添加该过滤器即可。
当然,您也可以实现自己的规则,将作用域映射到角色,并安装自己的OAuth2RequestFactory版
本。 AuthorizationServerEndpointsConfigurer允许您注入自定义OAuth2RequestFactory,
以便您可以使用该功能来设置工厂,如果您使用
@EnableAuthorizationServer。

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:

资源服务器配置

资源服务器(可以与授权服务器或单独的应用程序相同)提供受OAuth2令牌保护的资源。
Spring OAuth提供了实现此保护的Spring Security认证过滤器。
您可以在@Configuration类上使用@EnableResourceServer进行开启,
并使用ResourceServerConfigurer进行配置(如有必要)。 可以配置以下功能:


    tokenServices: the bean that defines the token services (instance of ResourceServerTokenServices).
    resourceId: the id for the resource (optional, but recommended and will be validated by the auth server if present).
    other extension points for the resourecs server (e.g. tokenExtractor for extracting the tokens from incoming requests)
    request matchers for protected resources (defaults to all)
    access rules for protected resources (defaults to plain "authenticated")
    other customizations for the protected resources permitted by the HttpSecurity configurer in Spring Security

The @EnableResourceServer annotation adds a filter of type OAuth2AuthenticationProcessingFilter automatically 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 then be added
manually to the standard Spring Security chain.

Your ResourceServerTokenServices is the other half of a contract with the Authorization Server. If the Resource Server and
Authorization Server are in the same application and you use DefaultTokenServices then you don't have to think too hard about this
because it implements all the necessary interfaces so it is automatically consistent. If your Resource Server is a separate
application then you have to make sure you match the capabilities of the Authorization Server and provide a
ResourceServerTokenServices that knows how to decode the tokens correctly. As with the Authorization Server, you can often use the
DefaultTokenServices and the choices are mostly expressed through the TokenStore (backend storage or local encoding). An alternative
is the RemoteTokenServices which is a Spring OAuth features (not part of the spec) allowing Resource Servers to decode tokens through
an HTTP resource on the Authorization Server (/oauth/check_token). RemoteTokenServices are convenient if there is not a huge volume of
traffic in the Resource Servers (every request has to be verified with the Authorization Server), or if you can afford to cache the
results. To use the /oauth/check_token endpoint you need to expose it by changing its access rule (default is "denyAll()") in the
AuthorizationServerSecurityConfigurer, e.g.

tokenServices:定义令牌服务的bean(ResourceServerTokenServices的实例)。
    resourceId:资源的ID(可选,但建议并由验证服务器验证)。
    用于恢复服务器的其他扩展点(例如,用于从传入请求中提取令牌的tokenExtractor)
    请求匹配的受保护资源(默认为全部)
    受保护资源的访问规则(默认为“已验证”)
    Spring Security中HttpSecurity配置程序允许的受保护资源的其他自定义

@EnableResourceServer注释将自动将一个OAuth2AuthenticationProcessingFilter类型的过滤器添加到Spring Security过滤器链中。

在XML中有一个具有id属性的<resource-server />元素
- 这是一个servlet Filter的bean id,然后可以手动添加到标准的Spring Security链。

您的ResourceServerTokenServices是与授权服务器的合同的另一半。
如果资源服务器和授权服务器在同一应用程序中,并且您使用DefaultTokenServices,
那么您不需要太过分考虑这一点,因为它实现了所有必要的接口,
因此它是自动一致的。
如果您的资源服务器是单独的应用程序,那么您必须确保与授权服务器
的功能相匹配,并提供一个ResourceServerTokenServices,
该服务器知道如何正确解码令牌。
与授权服务器一样,您经常可以使用DefaultTokenServices,
并且选择主要通过TokenStore(后端存储或本地编码)来表达。
另一种方法是RemoteTokenServices,它是Spring OAuth功能(不是规范的一部分),允许资源
服务器通过授权服务器(/ oauth / check_token)上的HTTP资源对令牌进行解码。
如果资源服务器中没有巨大的流量,RemoteTokenServices就会很方便(每
个请求都必须通过授权服务器进行验证),或者如果能够缓存结果。
要使用/ oauth / check_token端点,您需要通过更改其访问规则(默认为“denyAll()
”)在AuthorizationServerSecurityConfigurer(例如,

        
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess(
                "hasAuthority('ROLE_TRUSTED_CLIENT')");
    }

In this example we are configuring both the /oauth/check_token endpoint and the /oauth/token_key endpoint (so trusted resources can
obtain the public key for JWT verification). These two endpoints are protected by HTTP Basic authentication using client credentials.
在这个例子中,我们配置了/ oauth / check_token端点和/ oauth / token_key端点
(所以信任的资源可以获取JWT验证的公钥)。 这两个端点受到使用客户
端凭据的HTTP基本身份验证的保护。

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感知表达式处理程序

您可能希望利用Spring Security基于表达式的访问控制。
默认情况下,@EnableResourceServer安装程序将注册表达式处理程序。
这些表达式包括#
oauth2.clientHasRole,#oauth2.clientHasAnyRole和#oath2.denyClient,
可用于基于oauth客户端的角色提供访问(请参阅
OAuth2SecurityExpressionMethods作为综合列表)。
在XML中,您可以使用常规<http />安全配置的expression-handler元素注册一个oauth感知表达式处
理程序。
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.

OAuth 2.0客户端

OAuth 2.0客户端机制负责访问其他服务器的OAuth 2.0保护资源。
该配置包括建立用户可能访问的相关受保护资源。
客户端还可能需要提供用于存储用户的授
权码和访问令牌的机制。

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.
受保护的资源配置

可以使用OAuth2ProtectedResourceDetails类型的bean定义来定义受保护的资源(或“远程资源”)。受保护资源具有以下属性:

    id:资源的id。该id仅由客户端用于查找资源;它在OAuth协议中从未使用过。它也被用作bean的id。
    clientId:OAuth客户端ID。这是OAuth提供商识别您的客户端的ID。
    clientSecret:与资源相关联的秘密。默认情况下,没有密码为空。
    accessTokenUri:提供访问令牌的提供者OAuth端点的URI。
    scope:逗号分隔的字符串列表,指定对资源的访问范围。缺省情况下,不指定范围。
    clientAuthenticationScheme:您的客户端用于向访问令牌端点进行身份验证的方案。
    建议的值:“http_basic”和“form”。默认值为“http_basic”
。请参阅OAuth 2规范的第2.1节。

不同的授权类型具有OAuth2ProtectedResourceDetails的不同具体实现
(例如,“client_credentials”授权类型的ClientCredentialsResource)。
对于需要用户授权的授权类型,还有一个其他属性:

    userAuthorizationUri:如果用户需要授权访问资源的用户将被重定向到该uri。
    请注意,这并不总是需要,具体取决于支持哪个OAuth 2配置文件。

在XML中有一个可以用来创建OAuth2ProtectedResourceDetails类型的bean的<resource />元素。
它具有匹配上述所有属性的属性。
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:
客户端配置

对于OAuth 2.0客户端,使用@ EnableOAuth2Client简化配置。
这有两件事情:

     创建一个过滤器bean(ID为oauth2ClientContextFilter)来存储当前请求和上下文。
     在需要在请求期间进行身份验证的情况下,管理重定向到和从OAuth认证uri。

     在请求范围内创建AccessTokenRequest类型的bean。
     授权代码(或隐式)授权客户端可以使用这种方式来保持与个别用户的状态相关。

过滤器必须连接到应用程序中(例如,对于具有相同名称的DelegatingFilterProxy使用Servlet初始化程序或web.xml配置)。

AccessTokenRequest可以在OAuth2RestTemplate中使用,如下所示:
    @Autowired
    private OAuth2ClientContext oauth2Context;

    @Bean
    public OAuth2RestTemplate sparklrRestTemplate() {
        return new OAuth2RestTemplate(sparklr(), oauth2Context);
}


The OAuth2ClientContext is placed (for you) 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 the OAuth2ClientContext.

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).
在会话范围中放置OAuth2ClientContext(为您),以保持不同用户的状态分开。
没有了,您将不得不自己在服务器上管理等效的数据结构,将传入的请求映射
到用户,并将每个用户与OAuth2ClientContext的单独实例相关联。

在XML中有一个带有id属性的<client />元素
- 这是一个servlet Filter的bean id,必须像@Configuration一样映射到DelegatingFilterProxy(具有相同
名称)。

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.

As a general rule, a web application should not use password grants, so avoid using ResourceOwnerPasswordResourceDetails if you can in
favour of AuthorizationCodeResourceDetails. If you desparately need password grants to work from a Java client, then use the same
mechanism to configure your OAuth2RestTemplate and add the credentials to the AccessTokenRequest (which is a Map and is ephemeral) not
the ResourceOwnerPasswordResourceDetails (which is shared between all access tokens).

访问受保护的资源

一旦您提供了资源的所有配置,您现在可以访问这些资源。
用于访问这些资源的建议方法是使用Spring 3中引入的RestTemplate .Oracle for Spring
Security提供了RestTemplate的扩展,只需要为OAuth2ProtectedResourceDetails提供一个实例。
要使用用户令牌(授权代码授权),您应该考虑使用@ EnableOAuth2Client配置(或XML等效的<oauth:rest-template />)
来创建一些请求和会话范围的上下文对象,以便不同用户的请求不会在运行时发生冲突。

作为一般规则,Web应用程序不应使用密码授权,因此如果可以支持AuthorizationCodeResourceDetails,
则避免使用ResourceOwnerPasswordResourceDetails。
如果您需要密码授权才能从Java客户端工作,那么请使用相同的机制配置OAuth2RestTemplate,
并将凭据添加到AccessTokenRequest(它是Map并且是短暂的),
而不是ResourceOwnerPasswordResourceDetails(在所有访问令牌之间共享) 。

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 the OAuth2RestTemplate e.g.
在客户端中持久化令牌

客户端不需要持久化令牌,但是每次重新启动客户端应用程序时,
用户都不需要批准新的令牌授权,这是不错的选择。 ClientTokenServices接口定义了为特定
用户维护OAuth 2.0令牌所必需的操作。 提供了一个JDBC实现,
但如果您希望实现自己的服务来将持久性数据库中的访问令牌和关联的身份验证实例存储起来,
那么您可以使用。 如果要使用此功能,则需要向OAuth2RestTemplate提供特殊配置的TokenProvider。

@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.
外部OAuth2提供商客户端的定制

一些外部OAuth2提供商(例如Facebook)不能正确地实现规范,
或者它们只是比Spring Security OAuth更旧的规范。 要在客户端应用程序中使用这些提供程
序,您可能需要调整客户端基础架构的各个部分。

要以Facebook为例,tonr2应用程序中有一个Facebook功能
(您需要更改配置以添加自己的,有效的客户端ID和密码 - 它们可以在Facebook网站上生成)。

Facebook令牌响应还包含令牌到期时间的不合规JSON条目(它们使用到期而不是expires_in),
因此,如果要在应用程序中使用到期时间,则必须使用自定义
OAuth2SerializationService手动解码它 。



0 0
原创粉丝点击