204.2db6ba93.js 40.0 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1
(window.webpackJsonp=window.webpackJsonp||[]).push([[204],{634:function(e,t,a){"use strict";a.r(t);var r=a(56),i=Object(r.a)({},(function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[a("h1",{attrs:{id:"oauth-2-0-resource-server-jwt"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#oauth-2-0-resource-server-jwt"}},[e._v("#")]),e._v(" OAuth 2.0 Resource Server JWT")]),e._v(" "),a("h2",{attrs:{id:"minimal-dependencies-for-jwt"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#minimal-dependencies-for-jwt"}},[e._v("#")]),e._v(" Minimal Dependencies for JWT")]),e._v(" "),a("p",[e._v("Most Resource Server support is collected into "),a("code",[e._v("spring-security-oauth2-resource-server")]),e._v(".\nHowever, the support for decoding and verifying JWTs is in "),a("code",[e._v("spring-security-oauth2-jose")]),e._v(", meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens.")]),e._v(" "),a("h2",{attrs:{id:"minimal-configuration-for-jwts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#minimal-configuration-for-jwts"}},[e._v("#")]),e._v(" Minimal Configuration for JWTs")]),e._v(" "),a("p",[e._v("When using "),a("a",{attrs:{href:"https://spring.io/projects/spring-boot",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Boot"),a("OutboundLink")],1),e._v(", configuring an application as a resource server consists of two basic steps.\nFirst, include the needed dependencies and second, indicate the location of the authorization server.")]),e._v(" "),a("h3",{attrs:{id:"specifying-the-authorization-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#specifying-the-authorization-server"}},[e._v("#")]),e._v(" Specifying the Authorization Server")]),e._v(" "),a("p",[e._v("In a Spring Boot application, to specify which authorization server to use, simply do:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring:\n  security:\n    oauth2:\n      resourceserver:\n        jwt:\n          issuer-uri: https://idp.example.com/issuer\n")])])]),a("p",[e._v("Where "),a("code",[e._v("[https://idp.example.com/issuer](https://idp.example.com/issuer)")]),e._v(" is the value contained in the "),a("code",[e._v("iss")]),e._v(" claim for JWT tokens that the authorization server will issue.\nResource Server will use this property to further self-configure, discover the authorization server’s public keys, and subsequently validate incoming JWTs.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("To use the "),a("code",[e._v("issuer-uri")]),e._v(" property, it must also be true that one of "),a("code",[e._v("[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)")]),e._v(", "),a("code",[e._v("[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)")]),e._v(", or "),a("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(" is a supported endpoint for the authorization server."),a("br"),e._v("This endpoint is referred to as a "),a("a",{attrs:{href:"https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig",target:"_blank",rel:"noopener noreferrer"}},[e._v("Provider Configuration"),a("OutboundLink")],1),e._v(" endpoint or a "),a("a",{attrs:{href:"https://tools.ietf.org/html/rfc8414#section-3",target:"_blank",rel:"noopener noreferrer"}},[e._v("Authorization Server Metadata"),a("OutboundLink")],1),e._v(" endpoint.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("And that’s it!")]),e._v(" "),a("h3",{attrs:{id:"startup-expectations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#startup-expectations"}},[e._v("#")]),e._v(" Startup Expectations")]),e._v(" "),a("p",[e._v("When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens.")]),e._v(" "),a("p",[e._v("It achieves this through a deterministic startup process:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the "),a("code",[e._v("jwks_url")]),e._v(" property")])]),e._v(" "),a("li",[a("p",[e._v("Configure the validation strategy to query "),a("code",[e._v("jwks_url")]),e._v(" for valid public keys")])]),e._v(" "),a("li",[a("p",[e._v("Configure the validation strategy to validate each JWTs "),a("code",[e._v("iss")]),e._v(" claim against "),a("code",[e._v("[https://idp.example.com](https://idp.example.com)")]),e._v(".")])])]),e._v(" "),a("p",[e._v("A consequence of this process is that the authorization server must be up and receiving requests in order for Resource Server to successfully start up.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"runtime-expectations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#runtime-expectations"}},[e._v("#")]),e._v(" Runtime Expectations")]),e._v(" "),a("p",[e._v("Once the application is started up, Resource Server will attempt to process any request containing an "),a("code",[e._v("Authorization: Bearer")]),e._v(" header:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("GET / HTTP/1.1\nAuthorization: Bearer some-token-value # Resource Server will process this\n")])])]),a("p",[e._v("So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.")]),e._v(" "),a("p",[e._v("Given a well-formed JWT, Resource Server will:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Validate its signature against a public key obtained from the "),a("code",[e._v("jwks_url")]),e._v(" endpoint during startup and matched against the JWTs header")])]),e._v(" "),a("li",[a("p",[e._v("Validate the JWTs "),a("code",[e._v("exp")]),e._v(" and "),a("code",[e._v("nbf")]),e._v(" timestamps and the JWTs "),a("code",[e._v("iss")]),e._v(" claim, and")])]),e._v(" "),a("li",[a("p",[e._v("Map each scope to an authority with the prefix "),a("code",[e._v("SCOPE_")]),e._v(".")])])]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate the JWT tokens.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The resulting "),a("code",[e._v("Authentication#getPrincipal")]),e._v(", by default, is a Spring Security "),a("code",[e._v("Jwt")]),e._v(" object, and "),a("code",[e._v("Authentication#getName")]),e._v(" maps to the JWT’s "),a("code",[e._v("sub")]),e._v(" property, if one is present.")]),e._v(" "),a("p",[e._v("From here, consider jumping to:")]),e._v(" "),a("p",[a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-jwkseturi"}},[e._v("How to Configure without Tying Resource Server startup to an authorization server’s availability")])]),e._v(" "),a("p",[a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-sansboot"}},[e._v("How to Configure without Spring Boot")])]),e._v(" "),a("h3",{attrs:{id:"specifying-the-authorization-server-jwk-set-uri-directly"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#specifying-the-authorization-server-jwk-set-uri-directly"}},[e._v("#")]),e._v(" Specifying the Authorization Server JWK Set Uri Directly")]),e._v(" "),a("p",[e._v("If the authorization server doesn’t support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, then the "),a("code",[e._v("jwk-set-uri")]),e._v(" can be supplied as well:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("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")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The JWK Set uri is not standardized, but can typically be found in the authorization server’s documentation")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Consequently, Resource Server will not ping the authorization server at startup.\nWe still specify the "),a("code",[e._v("issuer-uri")]),e._v(" so that Resource Server still validates the "),a("code",[e._v("iss")]),e._v(" claim on incoming JWTs.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("This property can also be supplied directly on the "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-jwkseturi-dsl"}},[e._v("DSL")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"overriding-or-replacing-boot-auto-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#overriding-or-replacing-boot-auto-configuration"}},[e._v("#")]),e._v(" Overriding or Replacing Boot Auto Configuration")]),e._v(" "),a("p",[e._v("There are two "),a("code",[e._v("@Bean")]),e._v("s that Spring Boot generates on Resource Server’s behalf.")]),e._v(" "),a("p",[e._v("The first is a "),a("code",[e._v("SecurityWebFilterChain")]),e._v(" that configures the app as a resource server. When including "),a("code",[e._v("spring-security-oauth2-jose")]),e._v(", this "),a("code",[e._v("SecurityWebFilterChain")]),e._v(" looks like:")]),e._v(" "),a("p",[e._v("Example 1. Resource Server SecurityWebFilterChain")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)\n\treturn http.build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt { }\n        }\n    }\n}\n")])])]),a("p",[e._v("If the application doesn’t expose a "),a("code",[e._v("SecurityWebFilterChain")]),e._v(" bean, then Spring Boot will expose the above default one.")]),e._v(" "),a("p",[e._v("Replacing this is as simple as exposing the bean within the application:")]),e._v(" "),a("p",[e._v("Example 2. Replacing SecurityWebFilterChain")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.pathMatchers("/message/**").hasAuthority("SCOPE_message:read")\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(oauth2 -> oauth2\n\t\t\t.jwt(withDefaults())\n\t\t);\n\treturn http.build();\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize("/message/**", hasAuthority("SCOPE_message:read"))\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt { }\n        }\n    }\n}\n')])])]),a("p",[e._v("The above requires the scope of "),a("code",[e._v("message:read")]),e._v(" for any URL that starts with "),a("code",[e._v("/messages/")]),e._v(".")]),e._v(" "),a("p",[e._v("Methods on the "),a("code",[e._v("oauth2ResourceServer")]),e._v(" DSL will also override or replace auto configuration.")]),e._v(" "),a("p",[e._v("For example, the second "),a("code",[e._v("@Bean")]),e._v(" Spring Boot creates is a "),a("code",[e._v("ReactiveJwtDecoder")]),e._v(", which decodes "),a("code",[e._v("String")]),e._v(" tokens into validated instances of "),a("code",[e._v("Jwt")]),e._v(":")]),e._v(" "),a("p",[e._v("Example 3. ReactiveJwtDecoder")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\npublic ReactiveJwtDecoder jwtDecoder() {\n    return ReactiveJwtDecoders.fromIssuerLocation(issuerUri);\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Calling "),a("code",[e._v("[ReactiveJwtDecoders#fromIssuerLocation](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-)")]),e._v(" is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri."),a("br"),e._v("If the application doesn’t expose a "),a("code",[e._v("ReactiveJwtDecoder")]),e._v(" bean, then Spring Boot will expose the above default one.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("And its configuration can be overridden using "),a("code",[e._v("jwkSetUri()")]),e._v(" or replaced using "),a("code",[e._v("decoder()")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:""}},[a("a",{staticClass:"header-anchor",attrs:{href:"#"}},[e._v("#")]),e._v(" `")]),e._v(" "),a("p",[e._v("An authorization server’s JWK Set Uri can be configured "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-jwkseturi"}},[e._v("as a configuration property")]),e._v(" or it can be supplied in the DSL:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(oauth2 -> oauth2\n\t\t\t.jwt(jwt -> jwt\n\t\t\t\t.jwkSetUri("https://idp.example.com/.well-known/jwks.json")\n\t\t\t)\n\t\t);\n\treturn http.build();\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt {\n                jwkSetUri = "https://idp.example.com/.well-known/jwks.json"\n            }\n        }\n    }\n}\n')])])]),a("p",[e._v("Using "),a("code",[e._v("jwkSetUri()")]),e._v(" takes precedence over any configuration property.")]),e._v(" "),a("h4",{attrs:{id:"-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#-2"}},[e._v("#")]),e._v(" `")]),e._v(" "),a("p",[e._v("More powerful than "),a("code",[e._v("jwkSetUri()")]),e._v(" is "),a("code",[e._v("decoder()")]),e._v(", which will completely replace any Boot auto configuration of "),a("code",[e._v("JwtDecoder")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(oauth2 -> oauth2\n\t\t\t.jwt(jwt -> jwt\n\t\t\t\t.decoder(myCustomDecoder())\n\t\t\t)\n\t\t);\n    return http.build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt {\n                jwtDecoder = myCustomDecoder()\n            }\n        }\n    }\n}\n")])])]),a("p",[e._v("This is handy when deeper configuration, like "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-validation"}},[e._v("validation")]),e._v(", is necessary.")]),e._v(" "),a("h4",{attrs:{id:"exposing-a-reactivejwtdecoder-bean"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#exposing-a-reactivejwtdecoder-bean"}},[e._v("#")]),e._v(" Exposing a "),a("code",[e._v("ReactiveJwtDecoder")]),e._v(" "),a("code",[e._v("@Bean")])]),e._v(" "),a("p",[e._v("Or, exposing a "),a("code",[e._v("ReactiveJwtDecoder")]),e._v(" "),a("code",[e._v("@Bean")]),e._v(" has the same effect as "),a("code",[e._v("decoder()")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\npublic ReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)\n}\n")])])]),a("h2",{attrs:{id:"configuring-trusted-algorithms"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#configuring-trusted-algorithms"}},[e._v("#")]),e._v(" Configuring Trusted Algorithms")]),e._v(" "),a("p",[e._v("By default, "),a("code",[e._v("NimbusReactiveJwtDecoder")]),e._v(", and hence Resource Server, will only trust and verify tokens using "),a("code",[e._v("RS256")]),e._v(".")]),e._v(" "),a("p",[e._v("You can customize this via "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-boot-algorithm"}},[e._v("Spring Boot")]),e._v(" or "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-decoder-builder"}},[e._v("the NimbusJwtDecoder builder")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"via-spring-boot"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#via-spring-boot"}},[e._v("#")]),e._v(" Via Spring Boot")]),e._v(" "),a("p",[e._v("The simplest way to set the algorithm is as a property:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("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")])])]),a("h3",{attrs:{id:"using-a-builder"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#using-a-builder"}},[e._v("#")]),e._v(" Using a Builder")]),e._v(" "),a("p",[e._v("For greater power, though, we can use a builder that ships with "),a("code",[e._v("NimbusReactiveJwtDecoder")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithm(RS512).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithm(RS512).build()\n}\n")])])]),a("p",[e._v("Calling "),a("code",[e._v("jwsAlgorithm")]),e._v(" more than once will configure "),a("code",[e._v("NimbusReactiveJwtDecoder")]),e._v(" to trust more than one algorithm, like so:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()\n}\n")])])]),a("p",[e._v("Or, you can call "),a("code",[e._v("jwsAlgorithms")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithms(algorithms -> {\n                    algorithms.add(RS512);\n                    algorithms.add(ES512);\n            }).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)\n            .jwsAlgorithms {\n                it.add(RS512)\n                it.add(ES512)\n            }\n            .build()\n}\n")])])]),a("h3",{attrs:{id:"trusting-a-single-asymmetric-key"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#trusting-a-single-asymmetric-key"}},[e._v("#")]),e._v(" Trusting a Single Asymmetric Key")]),e._v(" "),a("p",[e._v("Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.\nThe public key can be provided via "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-decoder-public-key-boot"}},[e._v("Spring Boot")]),e._v(" or by "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-decoder-public-key-builder"}},[e._v("Using a Builder")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"via-spring-boot-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#via-spring-boot-2"}},[e._v("#")]),e._v(" Via Spring Boot")]),e._v(" "),a("p",[e._v("Specifying a key via Spring Boot is quite simple.\nThe key’s location can be specified like so:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring:\n  security:\n    oauth2:\n      resourceserver:\n        jwt:\n          public-key-location: classpath:my-key.pub\n")])])]),a("p",[e._v("Or, to allow for a more sophisticated lookup, you can post-process the "),a("code",[e._v("RsaKeyConversionServicePostProcessor")]),e._v(":")]),e._v(" "),a("p",[e._v("Example 4. BeanFactoryPostProcessor")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nBeanFactoryPostProcessor conversionServiceCustomizer() {\n    return beanFactory ->\n        beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)\n                .setResourceLoader(new CustomResourceLoader());\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun conversionServiceCustomizer(): BeanFactoryPostProcessor {\n    return BeanFactoryPostProcessor { beanFactory: ConfigurableListableBeanFactory ->\n        beanFactory.getBean<RsaKeyConversionServicePostProcessor>()\n                .setResourceLoader(CustomResourceLoader())\n    }\n}\n")])])]),a("p",[e._v("Specify your key’s location:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("key.location: hfds://my-key.pub\n")])])]),a("p",[e._v("And then autowire the value:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Value("${key.location}")\nRSAPublicKey key;\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Value("\\${key.location}")\nval key: RSAPublicKey? = null\n')])])]),a("h4",{attrs:{id:"using-a-builder-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#using-a-builder-2"}},[e._v("#")]),e._v(" Using a Builder")]),e._v(" "),a("p",[e._v("To wire an "),a("code",[e._v("RSAPublicKey")]),e._v(" directly, you can simply use the appropriate "),a("code",[e._v("NimbusReactiveJwtDecoder")]),e._v(" builder, like so:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\npublic ReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withPublicKey(this.key).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return NimbusReactiveJwtDecoder.withPublicKey(key).build()\n}\n")])])]),a("h3",{attrs:{id:"trusting-a-single-symmetric-key"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#trusting-a-single-symmetric-key"}},[e._v("#")]),e._v(" Trusting a Single Symmetric Key")]),e._v(" "),a("p",[e._v("Using a single symmetric key is also simple.\nYou can simply load in your "),a("code",[e._v("SecretKey")]),e._v(" and use the appropriate "),a("code",[e._v("NimbusReactiveJwtDecoder")]),e._v(" builder, like so:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\npublic ReactiveJwtDecoder jwtDecoder() {\n    return NimbusReactiveJwtDecoder.withSecretKey(this.key).build();\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()\n}\n")])])]),a("h3",{attrs:{id:"configuring-authorization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#configuring-authorization"}},[e._v("#")]),e._v(" Configuring Authorization")]),e._v(" "),a("p",[e._v("A JWT that is issued from an OAuth 2.0 Authorization Server will typically either have a "),a("code",[e._v("scope")]),e._v(" or "),a("code",[e._v("scp")]),e._v(" attribute, indicating the scopes (or authorities) it’s been granted, for example:")]),e._v(" "),a("p",[a("code",[e._v('{ …​, "scope" : "messages contacts"}')])]),e._v(" "),a("p",[e._v('When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_".')]),e._v(" "),a("p",[e._v("This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")\n\t\t\t.mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt);\n    return http.build();\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize("/contacts/**", hasAuthority("SCOPE_contacts"))\n            authorize("/messages/**", hasAuthority("SCOPE_messages"))\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt { }\n        }\n    }\n}\n')])])]),a("p",[e._v("Or similarly with method security:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasAuthority('SCOPE_messages')\")\npublic Flux<Message> getMessages(...) {}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasAuthority('SCOPE_messages')\")\nfun getMessages(): Flux<Message> { }\n")])])]),a("h4",{attrs:{id:"extracting-authorities-manually"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#extracting-authorities-manually"}},[e._v("#")]),e._v(" Extracting Authorities Manually")]),e._v(" "),a("p",[e._v("However, there are a number of circumstances where this default is insufficient.\nFor example, some authorization servers don’t use the "),a("code",[e._v("scope")]),e._v(" attribute, but instead have their own custom attribute.\nOr, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.")]),e._v(" "),a("p",[e._v("To this end, the DSL exposes "),a("code",[e._v("jwtAuthenticationConverter()")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {\n\thttp\n\t\t.authorizeExchange(exchanges -> exchanges\n\t\t\t.anyExchange().authenticated()\n\t\t)\n\t\t.oauth2ResourceServer(oauth2 -> oauth2\n\t\t\t.jwt(jwt -> jwt\n\t\t\t\t.jwtAuthenticationConverter(grantedAuthoritiesExtractor())\n\t\t\t)\n\t\t);\n\treturn http.build();\n}\n\nConverter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {\n    JwtAuthenticationConverter jwtAuthenticationConverter =\n            new JwtAuthenticationConverter();\n    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter\n            (new GrantedAuthoritiesExtractor());\n    return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {\n    return http {\n        authorizeExchange {\n            authorize(anyExchange, authenticated)\n        }\n        oauth2ResourceServer {\n            jwt {\n                jwtAuthenticationConverter = grantedAuthoritiesExtractor()\n            }\n        }\n    }\n}\n\nfun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {\n    val jwtAuthenticationConverter = JwtAuthenticationConverter()\n    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor())\n    return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)\n}\n")])])]),a("p",[e._v("which is responsible for converting a "),a("code",[e._v("Jwt")]),e._v(" into an "),a("code",[e._v("Authentication")]),e._v(".\nAs part of its configuration, we can supply a subsidiary converter to go from "),a("code",[e._v("Jwt")]),e._v(" to a "),a("code",[e._v("Collection")]),e._v(" of granted authorities.")]),e._v(" "),a("p",[e._v("That final converter might be something like "),a("code",[e._v("GrantedAuthoritiesExtractor")]),e._v(" below:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('static class GrantedAuthoritiesExtractor\n        implements Converter<Jwt, Collection<GrantedAuthority>> {\n\n    public Collection<GrantedAuthority> convert(Jwt jwt) {\n        Collection<?> authorities = (Collection<?>)\n                jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList());\n\n        return authorities.stream()\n                .map(Object::toString)\n                .map(SimpleGrantedAuthority::new)\n                .collect(Collectors.toList());\n    }\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {\n    override fun convert(jwt: Jwt): Collection<GrantedAuthority> {\n        val authorities: List<Any> = jwt.claims\n                .getOrDefault("mycustomclaim", emptyList<Any>()) as List<Any>\n        return authorities\n                .map { it.toString() }\n                .map { SimpleGrantedAuthority(it) }\n    }\n}\n')])])]),a("p",[e._v("For more flexibility, the DSL supports entirely replacing the converter with any class that implements "),a("code",[e._v("Converter<Jwt, Mono<AbstractAuthenticationToken>>")]),e._v(":")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {\n    public AbstractAuthenticationToken convert(Jwt jwt) {\n        return Mono.just(jwt).map(this::doConversion);\n    }\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {\n    override fun convert(jwt: Jwt): Mono<AbstractAuthenticationToken> {\n        return Mono.just(jwt).map(this::doConversion)\n    }\n}\n")])])]),a("h3",{attrs:{id:"configuring-validation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#configuring-validation"}},[e._v("#")]),e._v(" Configuring Validation")]),e._v(" "),a("p",[e._v("Using "),a("a",{attrs:{href:"#webflux-oauth2resourceserver-jwt-minimalconfiguration"}},[e._v("minimal Spring Boot configuration")]),e._v(", indicating the authorization server’s issuer uri, Resource Server will default to verifying the "),a("code",[e._v("iss")]),e._v(" claim as well as the "),a("code",[e._v("exp")]),e._v(" and "),a("code",[e._v("nbf")]),e._v(" timestamp claims.")]),e._v(" "),a("p",[e._v("In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom "),a("code",[e._v("OAuth2TokenValidator")]),e._v(" instances.")]),e._v(" "),a("h4",{attrs:{id:"customizing-timestamp-validation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#customizing-timestamp-validation"}},[e._v("#")]),e._v(" Customizing Timestamp Validation")]),e._v(" "),a("p",[e._v("JWT’s typically have a window of validity, with the start of the window indicated in the "),a("code",[e._v("nbf")]),e._v(" claim and the end indicated in the "),a("code",[e._v("exp")]),e._v(" claim.")]),e._v(" "),a("p",[e._v("However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.\nThis can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.")]),e._v(" "),a("p",[e._v("Resource Server uses "),a("code",[e._v("JwtTimestampValidator")]),e._v(" to verify a token’s validity window, and it can be configured with a "),a("code",[e._v("clockSkew")]),e._v(" to alleviate the above problem:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nReactiveJwtDecoder jwtDecoder() {\n     NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)\n             ReactiveJwtDecoders.fromIssuerLocation(issuerUri);\n\n     OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(\n            new JwtTimestampValidator(Duration.ofSeconds(60)),\n            new IssuerValidator(issuerUri));\n\n     jwtDecoder.setJwtValidator(withClockSkew);\n\n     return jwtDecoder;\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder\n    val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(\n            JwtTimestampValidator(Duration.ofSeconds(60)),\n            JwtIssuerValidator(issuerUri))\n    jwtDecoder.setJwtValidator(withClockSkew)\n    return jwtDecoder\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("By default, Resource Server configures a clock skew of 60 seconds.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"configuring-a-custom-validator"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#configuring-a-custom-validator"}},[e._v("#")]),e._v(" Configuring a Custom Validator")]),e._v(" "),a("p",[e._v("Adding a check for the "),a("code",[e._v("aud")]),e._v(" claim is simple with the "),a("code",[e._v("OAuth2TokenValidator")]),e._v(" API:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('public class AudienceValidator implements OAuth2TokenValidator<Jwt> {\n    OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);\n\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')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class AudienceValidator : OAuth2TokenValidator<Jwt> {\n    var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null)\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')])])]),a("p",[e._v("Then, to add into a resource server, it’s a matter of specifying the "),a("code",[e._v("ReactiveJwtDecoder")]),e._v(" instance:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nReactiveJwtDecoder jwtDecoder() {\n    NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)\n            ReactiveJwtDecoders.fromIssuerLocation(issuerUri);\n\n    OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();\n    OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);\n    OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);\n\n    jwtDecoder.setJwtValidator(withAudience);\n\n    return jwtDecoder;\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@Bean\nfun jwtDecoder(): ReactiveJwtDecoder {\n    val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder\n    val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidator()\n    val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)\n    val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)\n    jwtDecoder.setJwtValidator(withAudience)\n    return jwtDecoder\n}\n")])])]),a("p",[a("RouterLink",{attrs:{to:"/en/spring-security/index.html"}},[e._v("OAuth2 Resource Server")]),a("RouterLink",{attrs:{to:"/en/spring-security/opaque-token.html"}},[e._v("Opaque Token")])],1)])}),[],!1,null,null,null);t.default=i.exports}}]);