(window.webpackJsonp=window.webpackJsonp||[]).push([[642],{1074:function(e,t,r){"use strict";r.r(t);var a=r(56),n=Object(a.a)({},(function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[r("h1",{attrs:{id:"oauth2-0资源服务器jwt"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#oauth2-0资源服务器jwt"}},[e._v("#")]),e._v(" OAuth2.0资源服务器JWT")]),e._v(" "),r("h2",{attrs:{id:"jwt的最小依赖项"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#jwt的最小依赖项"}},[e._v("#")]),e._v(" JWT的最小依赖项")]),e._v(" "),r("p",[e._v("大多数资源服务器支持被收集到"),r("code",[e._v("spring-security-oauth2-resource-server")]),e._v("中。然而,对JWTS的解码和验证的支持是"),r("code",[e._v("spring-security-oauth2-jose")]),e._v(",这意味着这两个都是必要的,以便拥有一个支持JWT编码的承载令牌的工作资源服务器。")]),e._v(" "),r("h2",{attrs:{id:"jwts的最小配置"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#jwts的最小配置"}},[e._v("#")]),e._v(" JWTS的最小配置")]),e._v(" "),r("p",[e._v("当使用"),r("a",{attrs:{href:"https://spring.io/projects/spring-boot",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Boot"),r("OutboundLink")],1),e._v("时,将应用程序配置为资源服务器包括两个基本步骤。首先,包括所需的依赖关系,其次,指示授权服务器的位置。")]),e._v(" "),r("h3",{attrs:{id:"指定授权服务器"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#指定授权服务器"}},[e._v("#")]),e._v(" 指定授权服务器")]),e._v(" "),r("p",[e._v("在 Spring 引导应用程序中,要指定使用哪个授权服务器,只需执行以下操作:")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("spring:\n security:\n oauth2:\n resourceserver:\n jwt:\n issuer-uri: https://idp.example.com/issuer\n")])])]),r("p",[e._v("其中"),r("code",[e._v("[https://idp.example.com/issuer](https://idp.example.com/issuer)")]),e._v("是授权服务器将发布的JWT令牌的"),r("code",[e._v("iss")]),e._v("声明中包含的值。Resource Server将使用此属性进一步自我配置,发现授权服务器的公钥,并随后验证传入的JWTS。")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("要使用"),r("code",[e._v("issuer-uri")]),e._v("属性,还必须证明"),r("code",[e._v("[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)")]),e._v("、"),r("code",[e._v("[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)")]),e._v("或"),r("code",[e._v("[https://idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)")]),e._v("中的一个是授权服务器所支持的端点。"),r("br"),e._v("此端点被称为"),r("a",{attrs:{href:"https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig",target:"_blank",rel:"noopener noreferrer"}},[e._v("提供者配置"),r("OutboundLink")],1),e._v("端点或"),r("a",{attrs:{href:"https://tools.ietf.org/html/rfc8414#section-3",target:"_blank",rel:"noopener noreferrer"}},[e._v("授权服务器元数据"),r("OutboundLink")],1),e._v("端点。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("p",[e._v("就这样!")]),e._v(" "),r("h3",{attrs:{id:"创业期望"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#创业期望"}},[e._v("#")]),e._v(" 创业期望")]),e._v(" "),r("p",[e._v("当使用此属性和这些依赖项时,Resource Server将自动配置自身以验证JWT编码的承载令牌。")]),e._v(" "),r("p",[e._v("它通过一个确定性的启动过程来实现这一点:")]),e._v(" "),r("ol",[r("li",[r("p",[e._v("查询"),r("code",[e._v("jwks_url")]),e._v("属性的提供者配置或授权服务器元数据端点")])]),e._v(" "),r("li",[r("p",[e._v("查询"),r("code",[e._v("jwks_url")]),e._v("端点以获得支持的算法")])]),e._v(" "),r("li",[r("p",[e._v("将验证策略配置为查询"),r("code",[e._v("jwks_url")]),e._v("中找到的算法的有效公钥")])]),e._v(" "),r("li",[r("p",[e._v("将验证策略配置为针对"),r("code",[e._v("[https://idp.example.com](https://idp.example.com)")]),e._v("的每个JWTS"),r("code",[e._v("iss")]),e._v("索赔进行验证。")])])]),e._v(" "),r("p",[e._v("此过程的结果是,为了使资源服务器成功启动,授权服务器必须启动并接收请求。")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("如果在资源服务器查询时,授权服务器处于关闭状态(给定适当的超时),那么启动将失败。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("h3",{attrs:{id:"运行时期望"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#运行时期望"}},[e._v("#")]),e._v(" 运行时期望")]),e._v(" "),r("p",[e._v("一旦启动应用程序,Resource Server将尝试处理任何包含"),r("code",[e._v("Authorization: Bearer")]),e._v("报头的请求:")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("GET / HTTP/1.1\nAuthorization: Bearer some-token-value # Resource Server will process this\n")])])]),r("p",[e._v("只要表明了该方案,资源服务器就会尝试根据承载令牌规范来处理请求。")]),e._v(" "),r("p",[e._v("给定一个格式良好的JWT,资源服务器将:")]),e._v(" "),r("ol",[r("li",[r("p",[e._v("根据在启动过程中从"),r("code",[e._v("jwks_url")]),e._v("端点获得并与JWT匹配的公钥验证其签名")])]),e._v(" "),r("li",[r("p",[e._v("验证JWT的"),r("code",[e._v("exp")]),e._v("和"),r("code",[e._v("nbf")]),e._v("时间戳以及JWT的"),r("code",[e._v("iss")]),e._v("声明,并")])]),e._v(" "),r("li",[r("p",[e._v("将每个作用域映射到一个前缀"),r("code",[e._v("SCOPE_")]),e._v("的权限。")])])]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("由于授权服务器提供了可用的新密钥, Spring 安全性将自动旋转用于验证JWTS的密钥。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("p",[e._v("默认情况下,生成的"),r("code",[e._v("Authentication#getPrincipal")]),e._v("是 Spring security"),r("code",[e._v("Jwt")]),e._v("对象,并且"),r("code",[e._v("Authentication#getName")]),e._v("映射到JWT的"),r("code",[e._v("sub")]),e._v("属性(如果存在)。")]),e._v(" "),r("p",[e._v("从这里开始,考虑跳到:")]),e._v(" "),r("ul",[r("li",[r("p",[r("a",{attrs:{href:"#oauth2resourceserver-jwt-architecture"}},[e._v("JWT身份验证的工作方式")])])]),e._v(" "),r("li",[r("p",[r("a",{attrs:{href:"#oauth2resourceserver-jwt-jwkseturi"}},[e._v("如何在不将资源服务器启动与授权服务器的可用性绑定的情况下进行配置")])])]),e._v(" "),r("li",[r("p",[r("a",{attrs:{href:"#oauth2resourceserver-jwt-sansboot"}},[e._v("How to Configure without Spring Boot")])])])]),e._v(" "),r("h2",{attrs:{id:"jwt身份验证的工作方式"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#jwt身份验证的工作方式"}},[e._v("#")]),e._v(" JWT身份验证的工作方式")]),e._v(" "),r("p",[e._v("接下来,让我们看看 Spring Security在基于 Servlet 的应用程序中支持"),r("a",{attrs:{href:"https://tools.ietf.org/html/rfc7519",target:"_blank",rel:"noopener noreferrer"}},[e._v("JWT"),r("OutboundLink")],1),e._v("身份验证所使用的体系结构组件,就像我们刚才看到的那样。")]),e._v(" "),r("p",[e._v("["),r("code",[e._v("JwtAuthenticationProvider")]),e._v("](https://DOCS. Spring.io/ Spring-security/site/DOCS/5.6.2/api/org/springframework/security/oauth2/server/resource/authentication/jwtauthenticationprovider.html)是一个["),r("code",[e._v("AuthenticationProvider")]),e._v("](../.../././////认证/architectification/architecture.html# Servlet-authentification-authenticationprovider)实现,它利用了一个[<"),r("code",[e._v("JwtDecoder")]),e._v("](#oaut")]),e._v(" "),r("p",[e._v("让我们来看看"),r("code",[e._v("JwtAuthenticationProvider")]),e._v("在 Spring 安全性中是如何工作的。该图详细说明了"),r("code",[e._v("AuthenticationManager")]),e._v("](.../../authentication/architecture.html# Servlet-authentication-authenticationmanager)在"),r("a",{attrs:{href:"#oauth2resourceserver-authentication-bearertokenauthenticationfilter"}},[e._v("读取不记名令牌")]),e._v("中的工作原理。")]),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/servlet/oauth2/jwtauthenticationprovider.png",alt:"JWTAutHenticationProvider"}})]),e._v(" "),r("p",[e._v("图1. "),r("code",[e._v("JwtAuthenticationProvider")]),e._v("用法")]),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/icons/number_1.png",alt:"number 1"}}),e._v("来自"),r("a",{attrs:{href:"#oauth2resourceserver-authentication-bearertokenauthenticationfilter"}},[e._v("读取不记名令牌")]),e._v("的身份验证"),r("code",[e._v("Filter")]),e._v("将一个"),r("code",[e._v("BearerTokenAuthenticationToken")]),e._v("传递到"),r("code",[e._v("AuthenticationManager")]),e._v(",这是由["),r("code",[e._v("ProviderManager")]),e._v("](.../../authentication/architecture.html# Servlet-authentication-providermanager)实现的。")]),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/icons/number_2.png",alt:"number 2"}}),r("code",[e._v("ProviderManager")]),e._v("被配置为使用"),r("RouterLink",{attrs:{to:"/authentication/architecture.html#servlet-authentication-authenticationprovider"}},[e._v("身份验证提供者")]),e._v("类型的"),r("code",[e._v("JwtAuthenticationProvider")]),e._v("。")],1),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/icons/number_3.png",alt:"number 3"}}),r("code",[e._v("JwtAuthenticationProvider")]),e._v("使用["),r("code",[e._v("JwtDecoder")]),e._v("](#OAuth2Resourceserver-JWT-decoder)对"),r("code",[e._v("Jwt")]),e._v("进行解码、验证和验证。")]),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/icons/number_4.png",alt:"number 4"}}),r("code",[e._v("JwtAuthenticationProvider")]),e._v("然后使用["),r("code",[e._v("JwtAuthenticationConverter")]),e._v("](#OAuth2Resourceserver-JWT-Authorization-Extraction)将"),r("code",[e._v("Jwt")]),e._v("转换为授予权限的"),r("code",[e._v("Collection")]),e._v("。")]),e._v(" "),r("p",[r("img",{attrs:{src:"https://docs.spring.io/spring-security/reference/_images/icons/number_5.png",alt:"number 5"}}),e._v("当身份验证成功时,返回的["),r("code",[e._v("Authentication")]),e._v("](.../../authentication/architecture.html# Servlet-authentication-authentication)类型为"),r("code",[e._v("JwtAuthenticationToken")]),e._v(",并且具有一个主体,即由配置的"),r("code",[e._v("JwtDecoder")]),e._v("返回的"),r("code",[e._v("Jwt")]),e._v("。最终,返回的"),r("code",[e._v("JwtAuthenticationToken")]),e._v("将由身份验证"),r("code",[e._v("Filter")]),e._v("设置在["),r("code",[e._v("SecurityContextHolder")]),e._v("](.../authentication/architecture.html# Servlet-authentication-securitycontextholder)上。")]),e._v(" "),r("h2",{attrs:{id:"直接指定授权服务器jwk设置的uri"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#直接指定授权服务器jwk设置的uri"}},[e._v("#")]),e._v(" 直接指定授权服务器JWK设置的URI")]),e._v(" "),r("p",[e._v("如果授权服务器不支持任何配置端点,或者如果资源服务器必须能够独立于授权服务器启动,那么也可以提供"),r("code",[e._v("jwk-set-uri")]),e._v(":")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("spring:\n security:\n oauth2:\n resourceserver:\n jwt:\n issuer-uri: https://idp.example.com\n jwk-set-uri: https://idp.example.com/.well-known/jwks.json\n")])])]),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("JWK集URI不是标准化的,但通常可以在授权服务器的文档中找到。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("p",[e._v("因此,资源服务器不会在启动时对授权服务器进行ping。我们仍然指定"),r("code",[e._v("issuer-uri")]),e._v(",以便Resource Server仍然在传入的JWTS上验证"),r("code",[e._v("iss")]),e._v("声明。")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("也可以在"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-jwkseturi-dsl"}},[e._v("DSL")]),e._v("上直接提供此属性。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("h2",{attrs:{id:"覆盖或替换boot-auto配置"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#覆盖或替换boot-auto配置"}},[e._v("#")]),e._v(" 覆盖或替换Boot Auto配置")]),e._v(" "),r("p",[e._v("有两个"),r("code",[e._v("@Bean")]),e._v("s, Spring boot代表资源服务器生成。")]),e._v(" "),r("p",[e._v("第一个是将应用程序配置为资源服务器的"),r("code",[e._v("WebSecurityConfigurerAdapter")]),e._v("。当包含"),r("code",[e._v("spring-security-oauth2-jose")]),e._v("时,这个"),r("code",[e._v("WebSecurityConfigurerAdapter")]),e._v("看起来是这样的:")]),e._v(" "),r("p",[e._v("例1.默认的JWT配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt { }\n }\n }\n}\n")])])]),r("p",[e._v("如果应用程序不公开"),r("code",[e._v("WebSecurityConfigurerAdapter")]),e._v(" Bean,那么 Spring 引导将公开上面的默认引导。")]),e._v(" "),r("p",[e._v("替换它就像在应用程序中公开 Bean 一样简单:")]),e._v(" "),r("p",[e._v("例2.自定义JWT配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\npublic class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {\n protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(oauth2 -> oauth2\n .jwt(jwt -> jwt\n .jwtAuthenticationConverter(myConverter())\n )\n );\n }\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\nclass MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {\n override fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize("/messages/**", hasAuthority("SCOPE_message:read"))\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt {\n jwtAuthenticationConverter = myConverter()\n }\n }\n }\n }\n}\n')])])]),r("p",[e._v("对于任何以"),r("code",[e._v("/messages/")]),e._v("开头的URL,上面要求"),r("code",[e._v("message:read")]),e._v("的范围。")]),e._v(" "),r("p",[r("code",[e._v("oauth2ResourceServer")]),e._v("DSL上的方法也将覆盖或替换自动配置。")]),e._v(" "),r("p",[e._v("例如,第二个"),r("code",[e._v("@Bean")]),e._v(" Spring 引导创建了一个"),r("code",[e._v("JwtDecoder")]),e._v(",它[将"),r("code",[e._v("String")]),e._v("令牌解码为"),r("code",[e._v("Jwt")]),e._v("的验证实例](#OAuth2Resourceserver-jwt-architecture-jwtdecoder):")]),e._v(" "),r("p",[e._v("例3. JWT解码器")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder() {\n return JwtDecoders.fromIssuerLocation(issuerUri);\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return JwtDecoders.fromIssuerLocation(issuerUri)\n}\n")])])]),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("调用"),r("code",[e._v("[JwtDecoders#fromIssuerLocation](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/JwtDecoders.html#fromIssuerLocation-java.lang.String-)")]),e._v("是调用提供程序配置或授权服务器元数据端点以派生JWK集URI的目的。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("p",[e._v("如果应用程序不公开"),r("code",[e._v("JwtDecoder")]),e._v(" Bean,那么 Spring 引导将公开上面的默认引导。")]),e._v(" "),r("p",[e._v("并且其配置可以使用"),r("code",[e._v("jwkSetUri()")]),e._v("重写或使用"),r("code",[e._v("decoder()")]),e._v("替换。")]),e._v(" "),r("p",[e._v("或者,如果根本不使用 Spring boot,那么这两个组件--过滤器链和"),r("code",[e._v("JwtDecoder")]),e._v("都可以用XML指定。")]),e._v(" "),r("p",[e._v("过滤链是这样指定的:")]),e._v(" "),r("p",[e._v("例4.默认的JWT配置")]),e._v(" "),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n\n')])])]),r("p",[e._v("而"),r("code",[e._v("JwtDecoder")]),e._v("就像这样:")]),e._v(" "),r("p",[e._v("例5. JWT解码器")]),e._v(" "),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n\n')])])]),r("h3",{attrs:{id:""}},[r("a",{staticClass:"header-anchor",attrs:{href:"#"}},[e._v("#")]),e._v(" `")]),e._v(" "),r("p",[e._v("可以配置授权服务器的JWK集URI"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-jwkseturi"}},[e._v("作为配置属性")]),e._v(",也可以在DSL中提供它:")]),e._v(" "),r("p",[e._v("例6. JWK设置URI配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\npublic class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {\n protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(oauth2 -> oauth2\n .jwt(jwt -> jwt\n .jwkSetUri("https://idp.example.com/.well-known/jwks.json")\n )\n );\n }\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\nclass DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {\n override fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt {\n jwkSetUri = "https://idp.example.com/.well-known/jwks.json"\n }\n }\n }\n }\n}\n')])])]),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n\n')])])]),r("p",[e._v("使用"),r("code",[e._v("jwkSetUri()")]),e._v("优先于任何配置属性。")]),e._v(" "),r("h3",{attrs:{id:"-2"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#-2"}},[e._v("#")]),e._v(" `")]),e._v(" "),r("p",[e._v("比"),r("code",[e._v("jwkSetUri()")]),e._v("更强大的是"),r("code",[e._v("decoder()")]),e._v(",它将完全取代["),r("code",[e._v("JwtDecoder")]),e._v("](#OAuth2Resourceserver-jwt-architecture-jwtdecoder)的任何引导自动配置:")]),e._v(" "),r("p",[e._v("例7. JWT解码器配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@EnableWebSecurity\npublic class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter {\n protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(oauth2 -> oauth2\n .jwt(jwt -> jwt\n .decoder(myCustomDecoder())\n )\n );\n }\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@EnableWebSecurity\nclass DirectlyConfiguredJwtDecoder : WebSecurityConfigurerAdapter() {\n override fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt {\n jwtDecoder = myCustomDecoder()\n }\n }\n }\n }\n}\n")])])]),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n\n')])])]),r("p",[e._v("当需要更深的配置时,比如"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-validation"}},[e._v("validation")]),e._v("、"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-claimsetmapping"}},[e._v("mapping")]),e._v("或"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-timeouts"}},[e._v("请求超时")]),e._v(",这是很方便的。")]),e._v(" "),r("h3",{attrs:{id:"曝光jwtdecoder-bean"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#曝光jwtdecoder-bean"}},[e._v("#")]),e._v(" 曝光"),r("code",[e._v("JwtDecoder``@Bean")])]),e._v(" "),r("p",[e._v("或者,暴露["),r("code",[e._v("JwtDecoder")]),e._v("](#OAuth2Resourceserver-JWT-Architecture-JWTDecoder)"),r("code",[e._v("@Bean")]),e._v("具有与"),r("code",[e._v("decoder()")]),e._v("相同的效果:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()\n}\n")])])]),r("h2",{attrs:{id:"配置可信算法"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置可信算法"}},[e._v("#")]),e._v(" 配置可信算法")]),e._v(" "),r("p",[e._v("默认情况下,"),r("code",[e._v("NimbusJwtDecoder")]),e._v("以及资源服务器将仅使用"),r("code",[e._v("RS256")]),e._v("信任和验证令牌。")]),e._v(" "),r("p",[e._v("你可以通过"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-boot-algorithm"}},[e._v("Spring Boot")]),e._v("、"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-decoder-builder"}},[e._v("NimbusJWTDecoder Builder")]),e._v("或从"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-decoder-jwk-response"}},[e._v("JWK SET响应")]),e._v("进行自定义。")]),e._v(" "),r("h3",{attrs:{id:"通过-spring-引导"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#通过-spring-引导"}},[e._v("#")]),e._v(" 通过 Spring 引导")]),e._v(" "),r("p",[e._v("设置算法的最简单方法是作为一个属性:")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("spring:\n security:\n oauth2:\n resourceserver:\n jwt:\n jws-algorithm: RS512\n jwk-set-uri: https://idp.example.org/.well-known/jwks.json\n")])])]),r("h3",{attrs:{id:"使用构建器"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#使用构建器"}},[e._v("#")]),e._v(" 使用构建器")]),e._v(" "),r("p",[e._v("不过,要获得更大的功率,我们可以使用带有"),r("code",[e._v("NimbusJwtDecoder")]),e._v("的建造器:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithm(RS512).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithm(RS512).build()\n}\n")])])]),r("p",[e._v("多次调用"),r("code",[e._v("jwsAlgorithm")]),e._v("将配置"),r("code",[e._v("NimbusJwtDecoder")]),e._v("来信任多个算法,如下所示:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()\n}\n")])])]),r("p",[e._v("或者,你可以调用"),r("code",[e._v("jwsAlgorithms")]),e._v(":")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithms(algorithms -> {\n algorithms.add(RS512);\n algorithms.add(ES512);\n }).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)\n .jwsAlgorithms {\n it.add(RS512)\n it.add(ES512)\n }.build()\n}\n")])])]),r("h3",{attrs:{id:"来自jwk-set响应"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#来自jwk-set响应"}},[e._v("#")]),e._v(" 来自JWK SET响应")]),e._v(" "),r("p",[e._v("Spring 由于Security的JWT支持是基于Nimbus的,所以你也可以使用它的所有优秀功能。")]),e._v(" "),r("p",[e._v("例如,Nimbus有一个"),r("code",[e._v("JWSKeySelector")]),e._v("实现,该实现将基于JWK设置的URI响应来选择一组算法。你可以使用它生成"),r("code",[e._v("NimbusJwtDecoder")]),e._v(",如下所示:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder() {\n // makes a request to the JWK Set endpoint\n JWSKeySelector jwsKeySelector =\n JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);\n\n DefaultJWTProcessor jwtProcessor =\n new DefaultJWTProcessor<>();\n jwtProcessor.setJWSKeySelector(jwsKeySelector);\n\n return new NimbusJwtDecoder(jwtProcessor);\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n // makes a request to the JWK Set endpoint\n val jwsKeySelector: JWSKeySelector = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl)\n val jwtProcessor: DefaultJWTProcessor = DefaultJWTProcessor()\n jwtProcessor.jwsKeySelector = jwsKeySelector\n return NimbusJwtDecoder(jwtProcessor)\n}\n")])])]),r("h2",{attrs:{id:"信任单一的非对称密钥"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#信任单一的非对称密钥"}},[e._v("#")]),e._v(" 信任单一的非对称密钥")]),e._v(" "),r("p",[e._v("比支持具有JWK设置端点的资源服务器更简单的方法是对RSA公钥进行硬编码。公钥可以通过"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-decoder-public-key-boot"}},[e._v("Spring Boot")]),e._v("或"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-decoder-public-key-builder"}},[e._v("使用构建器")]),e._v("提供。")]),e._v(" "),r("h3",{attrs:{id:"通过-spring-引导-2"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#通过-spring-引导-2"}},[e._v("#")]),e._v(" 通过 Spring 引导")]),e._v(" "),r("p",[e._v("通过 Spring 引导指定一个键非常简单。密钥的位置可以这样指定:")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("spring:\n security:\n oauth2:\n resourceserver:\n jwt:\n public-key-location: classpath:my-key.pub\n")])])]),r("p",[e._v("或者,为了允许更复杂的查找,你可以对"),r("code",[e._v("RsaKeyConversionServicePostProcessor")]),e._v("进行后处理:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nBeanFactoryPostProcessor conversionServiceCustomizer() {\n return beanFactory ->\n beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)\n .setResourceLoader(new CustomResourceLoader());\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun conversionServiceCustomizer(): BeanFactoryPostProcessor {\n return BeanFactoryPostProcessor { beanFactory ->\n beanFactory.getBean()\n .setResourceLoader(CustomResourceLoader())\n }\n}\n")])])]),r("p",[e._v("指定你的密钥的位置:")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("key.location: hfds://my-key.pub\n")])])]),r("p",[e._v("然后自动连接该值:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Value("${key.location}")\nRSAPublicKey key;\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Value("\\${key.location}")\nval key: RSAPublicKey? = null\n')])])]),r("h3",{attrs:{id:"使用构建器-2"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#使用构建器-2"}},[e._v("#")]),e._v(" 使用构建器")]),e._v(" "),r("p",[e._v("要直接连接"),r("code",[e._v("RSAPublicKey")]),e._v(",只需使用适当的"),r("code",[e._v("NimbusJwtDecoder")]),e._v("构建器,如下所示:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withPublicKey(this.key).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withPublicKey(this.key).build()\n}\n")])])]),r("h2",{attrs:{id:"信任单一的对称密钥"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#信任单一的对称密钥"}},[e._v("#")]),e._v(" 信任单一的对称密钥")]),e._v(" "),r("p",[e._v("使用单一的对称密钥也很简单。你可以简单地在"),r("code",[e._v("SecretKey")]),e._v("中加载,并使用适当的"),r("code",[e._v("NimbusJwtDecoder")]),e._v("构建器,如下所示:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder() {\n return NimbusJwtDecoder.withSecretKey(this.key).build();\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n return NimbusJwtDecoder.withSecretKey(key).build()\n}\n")])])]),r("h2",{attrs:{id:"配置授权"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置授权"}},[e._v("#")]),e._v(" 配置授权")]),e._v(" "),r("p",[e._v("从OAuth2.0授权服务器发出的JWT通常具有"),r("code",[e._v("scope")]),e._v("或"),r("code",[e._v("scp")]),e._v("属性,指示已授予的范围(或权限),例如:")]),e._v(" "),r("p",[r("code",[e._v('{ …​, "scope" : "messages contacts"}')])]),e._v(" "),r("p",[e._v("在这种情况下,Resource Server将尝试强制将这些作用域放入一个已授予权限的列表中,并在每个作用域前加上字符串“scope_”。")]),e._v(" "),r("p",[e._v("这意味着,要使用从JWT派生的作用域来保护端点或方法,相应的表达式应该包括以下前缀:")]),e._v(" "),r("p",[e._v("例8.授权配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\npublic class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {\n protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")\n .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);\n }\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@EnableWebSecurity\nclass DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {\n override fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize("/contacts/**", hasAuthority("SCOPE_contacts"))\n authorize("/messages/**", hasAuthority("SCOPE_messages"))\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt { }\n }\n }\n }\n}\n')])])]),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n \n\n')])])]),r("p",[e._v("或类似于方法安全性:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@PreAuthorize(\"hasAuthority('SCOPE_messages')\")\npublic List getMessages(...) {}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@PreAuthorize(\"hasAuthority('SCOPE_messages')\")\nfun getMessages(): List { }\n")])])]),r("h3",{attrs:{id:"手动提取权限"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#手动提取权限"}},[e._v("#")]),e._v(" 手动提取权限")]),e._v(" "),r("p",[e._v("然而,在许多情况下,这种默认设置是不够的。例如,一些授权服务器不使用"),r("code",[e._v("scope")]),e._v("属性,而是具有自己的自定义属性。或者,在其他时候,资源服务器可能需要将属性或属性的组合调整为内在化的权限。")]),e._v(" "),r("p",[e._v("为此, Spring Security附带"),r("code",[e._v("JwtAuthenticationConverter")]),e._v(",它负责[将"),r("code",[e._v("Jwt")]),e._v("转换为"),r("code",[e._v("Authentication")]),e._v("](#OAuth2Resourceserver-JWT-Architecture-JWTAutoThenticationConverter)。默认情况下, Spring 安全性将用"),r("code",[e._v("JwtAuthenticationProvider")]),e._v("的默认实例连接"),r("code",[e._v("JwtAuthenticationConverter")]),e._v("。")]),e._v(" "),r("p",[e._v("作为配置"),r("code",[e._v("JwtAuthenticationConverter")]),e._v("的一部分,你可以提供一个附属转换器,将其从"),r("code",[e._v("Jwt")]),e._v("转换为授予权限的"),r("code",[e._v("Collection")]),e._v("。")]),e._v(" "),r("p",[e._v("假设你的授权服务器在一个名为"),r("code",[e._v("authorities")]),e._v("的自定义声明中与权威机构通信。在这种情况下,你可以配置["),r("code",[e._v("JwtAuthenticationConverter")]),e._v("](#OAuth2ResourceServer-JWT-Architecture-JWTAutoThenticationConverter)应该检查的声明,如下所示:")]),e._v(" "),r("p",[e._v("例9.当局声称配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\npublic JwtAuthenticationConverter jwtAuthenticationConverter() {\n JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();\n grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");\n\n JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();\n jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);\n return jwtAuthenticationConverter;\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\nfun jwtAuthenticationConverter(): JwtAuthenticationConverter {\n val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()\n grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")\n\n val jwtAuthenticationConverter = JwtAuthenticationConverter()\n jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)\n return jwtAuthenticationConverter\n}\n')])])]),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n \n\n\n\n \n\n\n\n \n\n')])])]),r("p",[e._v("你也可以将权限前缀配置为不同的。你可以将它更改为"),r("code",[e._v("ROLE_")]),e._v(",而不是在每个权限前加上"),r("code",[e._v("SCOPE_")]),e._v(",就像这样:")]),e._v(" "),r("p",[e._v("例10.权限前缀配置")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\npublic JwtAuthenticationConverter jwtAuthenticationConverter() {\n JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();\n grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");\n\n JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();\n jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);\n return jwtAuthenticationConverter;\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\nfun jwtAuthenticationConverter(): JwtAuthenticationConverter {\n val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()\n grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")\n\n val jwtAuthenticationConverter = JwtAuthenticationConverter()\n jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)\n return jwtAuthenticationConverter\n}\n')])])]),r("p",[e._v("XML")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('\n \n \n \n \n \n\n\n\n \n\n\n\n \n\n')])])]),r("p",[e._v("或者,你可以通过调用"),r("code",[e._v('JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")')]),e._v("来完全删除前缀。")]),e._v(" "),r("p",[e._v("为了具有更大的灵活性,DSL支持用实现"),r("code",[e._v("Converter")]),e._v("的任何类完全替换转换器:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("static class CustomAuthenticationConverter implements Converter {\n public AbstractAuthenticationToken convert(Jwt jwt) {\n return new CustomAuthenticationToken(jwt);\n }\n}\n\n// ...\n\n@EnableWebSecurity\npublic class CustomAuthenticationConverterConfig extends WebSecurityConfigurerAdapter {\n protected void configure(HttpSecurity http) {\n http\n .authorizeHttpRequests(authorize -> authorize\n .anyRequest().authenticated()\n )\n .oauth2ResourceServer(oauth2 -> oauth2\n .jwt(jwt -> jwt\n .jwtAuthenticationConverter(new CustomAuthenticationConverter())\n )\n );\n }\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("internal class CustomAuthenticationConverter : Converter {\n override fun convert(jwt: Jwt): AbstractAuthenticationToken {\n return CustomAuthenticationToken(jwt)\n }\n}\n\n// ...\n\n@EnableWebSecurity\nclass CustomAuthenticationConverterConfig : WebSecurityConfigurerAdapter() {\n override fun configure(http: HttpSecurity) {\n http {\n authorizeRequests {\n authorize(anyRequest, authenticated)\n }\n oauth2ResourceServer {\n jwt {\n jwtAuthenticationConverter = CustomAuthenticationConverter()\n }\n }\n }\n }\n}\n")])])]),r("h2",{attrs:{id:"配置验证"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置验证"}},[e._v("#")]),e._v(" 配置验证")]),e._v(" "),r("p",[e._v("使用"),r("a",{attrs:{href:"#oauth2resourceserver-jwt-minimalconfiguration"}},[e._v("minimal Spring Boot configuration")]),e._v("(表示授权服务器的发行者URI),Resource Server将默认验证"),r("code",[e._v("iss")]),e._v("声明以及"),r("code",[e._v("exp")]),e._v("和"),r("code",[e._v("nbf")]),e._v("时间戳声明。")]),e._v(" "),r("p",[e._v("在需要定制验证的情况下,Resource Server附带两个标准验证器,并且还接受定制的"),r("code",[e._v("OAuth2TokenValidator")]),e._v("实例。")]),e._v(" "),r("h3",{attrs:{id:"自定义时间戳验证"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#自定义时间戳验证"}},[e._v("#")]),e._v(" 自定义时间戳验证")]),e._v(" "),r("p",[e._v("JWT通常有一个有效窗口,窗口的开始在"),r("code",[e._v("nbf")]),e._v("索赔中指示,结束在"),r("code",[e._v("exp")]),e._v("索赔中指示。")]),e._v(" "),r("p",[e._v("然而,每个服务器都可能经历时钟漂移,这可能导致令牌在一台服务器上出现过期,而不是在另一台服务器上出现。随着分布式系统中协作服务器数量的增加,这可能会导致一些实现令人心烦。")]),e._v(" "),r("p",[e._v("Resource Server使用"),r("code",[e._v("JwtTimestampValidator")]),e._v("来验证令牌的有效性窗口,并且可以将其配置为"),r("code",[e._v("clockSkew")]),e._v("以缓解上述问题:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)\n JwtDecoders.fromIssuerLocation(issuerUri);\n\n OAuth2TokenValidator withClockSkew = new DelegatingOAuth2TokenValidator<>(\n new JwtTimestampValidator(Duration.ofSeconds(60)),\n new JwtIssuerValidator(issuerUri));\n\n jwtDecoder.setJwtValidator(withClockSkew);\n\n return jwtDecoder;\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder\n\n val withClockSkew: OAuth2TokenValidator = DelegatingOAuth2TokenValidator(\n JwtTimestampValidator(Duration.ofSeconds(60)),\n JwtIssuerValidator(issuerUri))\n\n jwtDecoder.setJwtValidator(withClockSkew)\n\n return jwtDecoder\n}\n")])])]),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("默认情况下,Resource Server配置的时钟偏差为60秒。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("h3",{attrs:{id:"配置自定义验证器"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置自定义验证器"}},[e._v("#")]),e._v(" 配置自定义验证器")]),e._v(" "),r("p",[e._v("使用"),r("code",[e._v("OAuth2TokenValidator")]),e._v("API添加"),r("code",[e._v("aud")]),e._v("声明的检查很简单:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('OAuth2TokenValidator audienceValidator() {\n return new JwtClaimValidator>(AUD, aud -> aud.contains("messaging"));\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('fun audienceValidator(): OAuth2TokenValidator {\n return JwtClaimValidator>(AUD) { aud -> aud.contains("messaging") }\n}\n')])])]),r("p",[e._v("或者,为了获得更多的控制,你可以实现自己的"),r("code",[e._v("OAuth2TokenValidator")]),e._v(":")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('static class AudienceValidator implements OAuth2TokenValidator {\n OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);\n\n @Override\n public OAuth2TokenValidatorResult validate(Jwt jwt) {\n if (jwt.getAudience().contains("messaging")) {\n return OAuth2TokenValidatorResult.success();\n } else {\n return OAuth2TokenValidatorResult.failure(error);\n }\n }\n}\n\n// ...\n\nOAuth2TokenValidator audienceValidator() {\n return new AudienceValidator();\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('internal class AudienceValidator : OAuth2TokenValidator {\n var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)\n\n override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {\n return if (jwt.audience.contains("messaging")) {\n OAuth2TokenValidatorResult.success()\n } else {\n OAuth2TokenValidatorResult.failure(error)\n }\n }\n}\n\n// ...\n\nfun audienceValidator(): OAuth2TokenValidator {\n return AudienceValidator()\n}\n')])])]),r("p",[e._v("然后,要添加到资源服务器中,需要指定["),r("code",[e._v("JwtDecoder")]),e._v("](#OAuth2Resourceserver-jwt-architecture-jwtdecoder)实例:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)\n JwtDecoders.fromIssuerLocation(issuerUri);\n\n OAuth2TokenValidator audienceValidator = audienceValidator();\n OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);\n OAuth2TokenValidator withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);\n\n jwtDecoder.setJwtValidator(withAudience);\n\n return jwtDecoder;\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder\n\n val audienceValidator = audienceValidator()\n val withIssuer: OAuth2TokenValidator = JwtValidators.createDefaultWithIssuer(issuerUri)\n val withAudience: OAuth2TokenValidator = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)\n\n jwtDecoder.setJwtValidator(withAudience)\n\n return jwtDecoder\n}\n")])])]),r("h2",{attrs:{id:"配置索赔集映射"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置索赔集映射"}},[e._v("#")]),e._v(" 配置索赔集映射")]),e._v(" "),r("p",[e._v("Spring 安全性使用"),r("a",{attrs:{href:"https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home",target:"_blank",rel:"noopener noreferrer"}},[e._v("Nimbus"),r("OutboundLink")],1),e._v("库来解析JWTS并验证其签名。因此, Spring 安全性取决于Nimbus对每个字段值的解释以及如何将每个字段值强制为 Java 类型。")]),e._v(" "),r("p",[e._v("例如,因为Nimbus保持 Java 7兼容,所以它不使用"),r("code",[e._v("Instant")]),e._v("来表示时间戳字段。")]),e._v(" "),r("p",[e._v("而且完全有可能使用不同的库或用于JWT处理,这可能会做出自己的强制决策,需要进行调整。")]),e._v(" "),r("p",[e._v("或者,非常简单地说,出于特定于域的原因,资源服务器可能希望从JWT中添加或删除声明。")]),e._v(" "),r("p",[e._v("出于这些目的,Resource Server支持用"),r("code",[e._v("MappedJwtClaimSetConverter")]),e._v("映射JWT索赔集。")]),e._v(" "),r("h3",{attrs:{id:"定制单个索赔的转换"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#定制单个索赔的转换"}},[e._v("#")]),e._v(" 定制单个索赔的转换")]),e._v(" "),r("p",[e._v("默认情况下,"),r("code",[e._v("MappedJwtClaimSetConverter")]),e._v("将尝试强制将声明转换为以下类型:")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th",[e._v("Claim")]),e._v(" "),r("th",[e._v("Java 类型")])])]),e._v(" "),r("tbody",[r("tr",[r("td",[r("code",[e._v("aud")])]),e._v(" "),r("td",[r("code",[e._v("Collection")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("exp")])]),e._v(" "),r("td",[r("code",[e._v("Instant")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("iat")])]),e._v(" "),r("td",[r("code",[e._v("Instant")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("iss")])]),e._v(" "),r("td",[r("code",[e._v("String")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("jti")])]),e._v(" "),r("td",[r("code",[e._v("String")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("nbf")])]),e._v(" "),r("td",[r("code",[e._v("Instant")])])]),e._v(" "),r("tr",[r("td",[r("code",[e._v("sub")])]),e._v(" "),r("td",[r("code",[e._v("String")])])])])]),e._v(" "),r("p",[e._v("可以使用"),r("code",[e._v("MappedJwtClaimSetConverter.withDefaults")]),e._v("配置单个索赔的转换策略:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\nJwtDecoder jwtDecoder() {\n NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();\n\n MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter\n .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));\n jwtDecoder.setClaimSetConverter(converter);\n\n return jwtDecoder;\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\nfun jwtDecoder(): JwtDecoder {\n val jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()\n\n val converter = MappedJwtClaimSetConverter\n .withDefaults(mapOf("sub" to this::lookupUserIdBySub))\n jwtDecoder.setClaimSetConverter(converter)\n\n return jwtDecoder\n}\n')])])]),r("p",[e._v("这将保留所有的默认值,除了它将覆盖"),r("code",[e._v("sub")]),e._v("的默认索赔转换器。")]),e._v(" "),r("h3",{attrs:{id:"增加索赔"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#增加索赔"}},[e._v("#")]),e._v(" 增加索赔")]),e._v(" "),r("p",[r("code",[e._v("MappedJwtClaimSetConverter")]),e._v("还可以用于添加自定义声明,例如,用于适应现有系统:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter { "value" }))\n')])])]),r("h3",{attrs:{id:"删除索赔"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#删除索赔"}},[e._v("#")]),e._v(" 删除索赔")]),e._v(" "),r("p",[e._v("删除声明也很简单,使用相同的API:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter { null }))\n')])])]),r("h3",{attrs:{id:"重新命名索赔"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#重新命名索赔"}},[e._v("#")]),e._v(" 重新命名索赔")]),e._v(" "),r("p",[e._v("在更复杂的场景中,例如一次查询多个声明或重命名一个声明,Resource Server接受实现"),r("code",[e._v("Converter, Map>")]),e._v("的任何类:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('public class UsernameSubClaimAdapter implements Converter, Map> {\n private final MappedJwtClaimSetConverter delegate =\n MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());\n\n public Map convert(Map claims) {\n Map convertedClaims = this.delegate.convert(claims);\n\n String username = (String) convertedClaims.get("user_name");\n convertedClaims.put("sub", username);\n\n return convertedClaims;\n }\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('class UsernameSubClaimAdapter : Converter, Map> {\n private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())\n override fun convert(claims: Map): Map {\n val convertedClaims = delegate.convert(claims)\n val username = convertedClaims["user_name"] as String\n convertedClaims["sub"] = username\n return convertedClaims\n }\n}\n')])])]),r("p",[e._v("然后,实例可以像正常情况一样提供:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nJwtDecoder jwtDecoder() {\n NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();\n jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());\n return jwtDecoder;\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(): JwtDecoder {\n val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()\n jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())\n return jwtDecoder\n}\n")])])]),r("h2",{attrs:{id:"配置超时"}},[r("a",{staticClass:"header-anchor",attrs:{href:"#配置超时"}},[e._v("#")]),e._v(" 配置超时")]),e._v(" "),r("p",[e._v("默认情况下,Resource Server使用30秒的连接和套接字超时来与授权服务器进行协调。")]),e._v(" "),r("p",[e._v("在某些情况下,这可能太短了。此外,它没有考虑到更复杂的模式,比如后退和发现。")]),e._v(" "),r("p",[e._v("要调整资源服务器连接到授权服务器的方式,"),r("code",[e._v("NimbusJwtDecoder")]),e._v("接受"),r("code",[e._v("RestOperations")]),e._v("的实例:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\npublic JwtDecoder jwtDecoder(RestTemplateBuilder builder) {\n RestOperations rest = builder\n .setConnectTimeout(Duration.ofSeconds(60))\n .setReadTimeout(Duration.ofSeconds(60))\n .build();\n\n NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build();\n return jwtDecoder;\n}\n")])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v("@Bean\nfun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {\n val rest: RestOperations = builder\n .setConnectTimeout(Duration.ofSeconds(60))\n .setReadTimeout(Duration.ofSeconds(60))\n .build()\n return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build()\n}\n")])])]),r("p",[e._v("另外,默认情况下,Resource Server会在内存中缓存授权服务器的JWK设置5分钟,你可能需要对其进行调整。此外,它没有考虑更复杂的缓存模式,比如驱逐或使用共享缓存。")]),e._v(" "),r("p",[e._v("要调整资源服务器缓存JWK集的方式,"),r("code",[e._v("NimbusJwtDecoder")]),e._v("接受"),r("code",[e._v("Cache")]),e._v("的实例:")]),e._v(" "),r("p",[e._v("Java")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\npublic JwtDecoder jwtDecoder(CacheManager cacheManager) {\n return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)\n .cache(cacheManager.getCache("jwks"))\n .build();\n}\n')])])]),r("p",[e._v("Kotlin")]),e._v(" "),r("div",{staticClass:"language- extra-class"},[r("pre",{pre:!0,attrs:{class:"language-text"}},[r("code",[e._v('@Bean\nfun jwtDecoder(cacheManager: CacheManager): JwtDecoder {\n return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)\n .cache(cacheManager.getCache("jwks"))\n .build()\n}\n')])])]),r("p",[e._v("当给定一个"),r("code",[e._v("Cache")]),e._v("时,资源服务器将使用JWK设置的URI作为键,并使用JWK设置的JSON作为值。")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("Spring 不是缓存提供程序,因此你需要确保包含适当的依赖项,比如"),r("code",[e._v("spring-boot-starter-cache")]),e._v("和你最喜欢的缓存提供程序。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("table",[r("thead",[r("tr",[r("th"),e._v(" "),r("th",[e._v("不管是套接字超时还是缓存超时,你可能希望直接使用Nimbus。要做到这一点,请记住"),r("br"),e._v("附带一个构造函数,该构造函数接受Nimbus的"),r("code",[e._v("JWTProcessor")]),e._v("。")])])]),e._v(" "),r("tbody")]),e._v(" "),r("p",[r("RouterLink",{attrs:{to:"/spring-security/index.html"}},[e._v("OAuth2资源服务器")]),r("RouterLink",{attrs:{to:"/spring-security/opaque-token.html"}},[e._v("不透明令牌")])],1)])}),[],!1,null,null,null);t.default=n.exports}}]);