Compare commits
No commits in common. "master" and "0.0.2" have entirely different histories.
3
.github/ISSUE_TEMPLATE/config.yml
vendored
3
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -3,3 +3,6 @@ contact_links:
|
|||||||
- name: Community Support
|
- name: Community Support
|
||||||
url: https://stackoverflow.com/questions/tagged/spring-security
|
url: https://stackoverflow.com/questions/tagged/spring-security
|
||||||
about: Please ask and answer questions on StackOverflow with the tag `spring-security`.
|
about: Please ask and answer questions on StackOverflow with the tag `spring-security`.
|
||||||
|
- name: Security Issues
|
||||||
|
url: https://pivotal.io/security#reporting
|
||||||
|
about: Please report security vulnerabilities here.
|
||||||
|
5
Jenkinsfile
vendored
5
Jenkinsfile
vendored
@ -32,14 +32,13 @@ try {
|
|||||||
checkout scm
|
checkout scm
|
||||||
sh "git clean -dfx"
|
sh "git clean -dfx"
|
||||||
try {
|
try {
|
||||||
withCredentials([ARTIFACTORY_CREDENTIALS,
|
withCredentials([GRADLE_ENTERPRISE_CACHE_USER,
|
||||||
GRADLE_ENTERPRISE_CACHE_USER,
|
|
||||||
GRADLE_ENTERPRISE_SECRET_ACCESS_KEY]) {
|
GRADLE_ENTERPRISE_SECRET_ACCESS_KEY]) {
|
||||||
withEnv([jdkEnv(),
|
withEnv([jdkEnv(),
|
||||||
"GRADLE_ENTERPRISE_CACHE_USERNAME=${GRADLE_ENTERPRISE_CACHE_USERNAME}",
|
"GRADLE_ENTERPRISE_CACHE_USERNAME=${GRADLE_ENTERPRISE_CACHE_USERNAME}",
|
||||||
"GRADLE_ENTERPRISE_CACHE_PASSWORD=${GRADLE_ENTERPRISE_CACHE_PASSWORD}",
|
"GRADLE_ENTERPRISE_CACHE_PASSWORD=${GRADLE_ENTERPRISE_CACHE_PASSWORD}",
|
||||||
"GRADLE_ENTERPRISE_ACCESS_KEY=${GRADLE_ENTERPRISE_ACCESS_KEY}"]) {
|
"GRADLE_ENTERPRISE_ACCESS_KEY=${GRADLE_ENTERPRISE_ACCESS_KEY}"]) {
|
||||||
sh "./gradlew check -PartifactoryUsername=$ARTIFACTORY_USERNAME -PartifactoryPassword=$ARTIFACTORY_PASSWORD --stacktrace"
|
sh "./gradlew check --stacktrace"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch(Exception e) {
|
} catch(Exception e) {
|
||||||
|
@ -17,8 +17,6 @@ This project uses https://www.zenhub.com/[ZenHub] to prioritize the feature road
|
|||||||
The project board can be accessed https://app.zenhub.com/workspaces/authorization-server-5e8f3182b5e8f5841bfc4902/board?repos=248032165[here].
|
The project board can be accessed https://app.zenhub.com/workspaces/authorization-server-5e8f3182b5e8f5841bfc4902/board?repos=248032165[here].
|
||||||
It is recommended to install the ZenHub https://www.zenhub.com/extension[browser extension] as it integrates natively within GitHub's user interface.
|
It is recommended to install the ZenHub https://www.zenhub.com/extension[browser extension] as it integrates natively within GitHub's user interface.
|
||||||
|
|
||||||
The completed and upcoming feature list can be viewed in the https://github.com/spring-projects-experimental/spring-authorization-server/wiki/Feature-List[wiki].
|
|
||||||
|
|
||||||
== Getting Started
|
== Getting Started
|
||||||
The first place to start is to read the https://tools.ietf.org/html/rfc6749[OAuth 2.0 Authorization Framework] to gain an in-depth understanding on how to build an Authorization Server.
|
The first place to start is to read the https://tools.ietf.org/html/rfc6749[OAuth 2.0 Authorization Framework] to gain an in-depth understanding on how to build an Authorization Server.
|
||||||
It is a critically important first step as the implementation must conform to the specification defined in the OAuth 2.0 Authorization Framework and the https://github.com/spring-projects-experimental/spring-authorization-server/wiki/OAuth-2.0-Specifications[related specifications].
|
It is a critically important first step as the implementation must conform to the specification defined in the OAuth 2.0 Authorization Framework and the https://github.com/spring-projects-experimental/spring-authorization-server/wiki/OAuth-2.0-Specifications[related specifications].
|
||||||
@ -45,7 +43,7 @@ This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code
|
|||||||
By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
|
By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
|
||||||
|
|
||||||
== Downloading Artifacts
|
== Downloading Artifacts
|
||||||
See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Artifacts[downloading Spring artifacts] for Maven repository information.
|
See https://github.com/spring-projects/spring-framework/wiki/Downloading-Spring-artifacts[downloading Spring artifacts] for Maven repository information.
|
||||||
|
|
||||||
== Building from Source
|
== Building from Source
|
||||||
Spring Authorization Server uses a https://gradle.org[Gradle]-based build system.
|
Spring Authorization Server uses a https://gradle.org[Gradle]-based build system.
|
||||||
|
12
build.gradle
12
build.gradle
@ -1,19 +1,11 @@
|
|||||||
buildscript {
|
buildscript {
|
||||||
dependencies {
|
dependencies {
|
||||||
classpath 'io.spring.gradle:spring-build-conventions:0.0.37'
|
classpath 'io.spring.gradle:spring-build-conventions:0.0.33.RELEASE'
|
||||||
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
|
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
|
||||||
classpath 'io.spring.nohttp:nohttp-gradle:0.0.5.RELEASE'
|
classpath 'io.spring.nohttp:nohttp-gradle:0.0.5.RELEASE'
|
||||||
}
|
}
|
||||||
repositories {
|
repositories {
|
||||||
maven {
|
maven { url 'https://repo.spring.io/plugins-snapshot' }
|
||||||
url = 'https://repo.spring.io/plugins-snapshot'
|
|
||||||
if (project.hasProperty('artifactoryUsername')) {
|
|
||||||
credentials {
|
|
||||||
username "$artifactoryUsername"
|
|
||||||
password "$artifactoryPassword"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
maven { url 'https://plugins.gradle.org/m2/' }
|
maven { url 'https://plugins.gradle.org/m2/' }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
3
docs/manual/gradle/dependency-locks/archives.lockfile
Normal file
3
docs/manual/gradle/dependency-locks/archives.lockfile
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,4 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.4.2.RELEASE
|
3
docs/manual/gradle/dependency-locks/compile.lockfile
Normal file
3
docs/manual/gradle/dependency-locks/compile.lockfile
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
3
docs/manual/gradle/dependency-locks/compileOnly.lockfile
Normal file
3
docs/manual/gradle/dependency-locks/compileOnly.lockfile
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
3
docs/manual/gradle/dependency-locks/default.lockfile
Normal file
3
docs/manual/gradle/dependency-locks/default.lockfile
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,4 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
io.spring.docresources:spring-doc-resources:0.2.1.RELEASE
|
3
docs/manual/gradle/dependency-locks/runtime.lockfile
Normal file
3
docs/manual/gradle/dependency-locks/runtime.lockfile
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
13
docs/manual/gradle/dependency-locks/testCompile.lockfile
Normal file
13
docs/manual/gradle/dependency-locks/testCompile.lockfile
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
@ -0,0 +1,13 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
13
docs/manual/gradle/dependency-locks/testRuntime.lockfile
Normal file
13
docs/manual/gradle/dependency-locks/testRuntime.lockfile
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
@ -0,0 +1,13 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
@ -31,7 +31,3 @@ def resolvedVersions(Configuration configuration) {
|
|||||||
.collectEntries { [(it.name + "-version"): it.moduleVersion.id.version] }
|
.collectEntries { [(it.name + "-version"): it.moduleVersion.id.version] }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
repositories {
|
|
||||||
maven { url "https://repo.spring.io/release" }
|
|
||||||
}
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
version=0.1.1-SNAPSHOT
|
version=0.0.2
|
||||||
springBootVersion=2.4.3
|
springBootVersion=2.4.0-M3
|
||||||
org.gradle.jvmargs=-Xmx3g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError
|
org.gradle.jvmargs=-Xmx3g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError
|
||||||
org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
org.gradle.caching=true
|
org.gradle.caching=true
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
if (!project.hasProperty("springVersion")) {
|
if (!project.hasProperty("springVersion")) {
|
||||||
ext.springVersion = "5.3.3"
|
ext.springVersion = "5.2.+"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!project.hasProperty("springSecurityVersion")) {
|
if (!project.hasProperty("springSecurityVersion")) {
|
||||||
ext.springSecurityVersion = "5.4.5"
|
ext.springSecurityVersion = "5.4.+"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!project.hasProperty("reactorVersion")) {
|
if (!project.hasProperty("reactorVersion")) {
|
||||||
ext.reactorVersion = "2020.0.3"
|
ext.reactorVersion = "Dysprosium-SR+"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!project.hasProperty("locksDisabled")) {
|
if (!project.hasProperty("locksDisabled")) {
|
||||||
@ -21,16 +21,47 @@ dependencyManagement {
|
|||||||
mavenBom "org.springframework:spring-framework-bom:$springVersion"
|
mavenBom "org.springframework:spring-framework-bom:$springVersion"
|
||||||
mavenBom "org.springframework.security:spring-security-bom:$springSecurityVersion"
|
mavenBom "org.springframework.security:spring-security-bom:$springSecurityVersion"
|
||||||
mavenBom "io.projectreactor:reactor-bom:$reactorVersion"
|
mavenBom "io.projectreactor:reactor-bom:$reactorVersion"
|
||||||
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.0"
|
mavenBom "com.fasterxml.jackson:jackson-bom:2.+"
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
dependency "javax.servlet:javax.servlet-api:4.0.1"
|
dependency "com.nimbusds:oauth2-oidc-sdk:latest.release"
|
||||||
dependency 'junit:junit:4.13.1'
|
dependency "com.nimbusds:nimbus-jose-jwt:latest.release"
|
||||||
dependency 'org.assertj:assertj-core:3.18.1'
|
dependency "javax.servlet:javax.servlet-api:4.+"
|
||||||
dependency 'org.mockito:mockito-core:3.6.28'
|
dependency 'junit:junit:latest.release'
|
||||||
dependency "com.squareup.okhttp3:mockwebserver:3.14.9"
|
dependency 'org.assertj:assertj-core:latest.release'
|
||||||
dependency "com.squareup.okhttp3:okhttp:3.14.9"
|
dependency 'org.mockito:mockito-core:latest.release'
|
||||||
dependency "com.jayway.jsonpath:json-path:2.4.0"
|
dependency "com.squareup.okhttp3:mockwebserver:3.+"
|
||||||
|
dependency "com.squareup.okhttp3:okhttp:3.+"
|
||||||
|
dependency "com.jayway.jsonpath:json-path:2.+"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
NOTE:
|
||||||
|
The latest `reactor-netty` dependency was split into `reactor-netty-core` and `reactor-netty-http`,
|
||||||
|
which resulted in the snapshot build to fail. The below configuration fixes it.
|
||||||
|
|
||||||
|
Reference:
|
||||||
|
- https://github.com/spring-projects/spring-security/issues/8909
|
||||||
|
- https://github.com/reactor/reactor-netty/issues/739#issuecomment-667047117
|
||||||
|
*/
|
||||||
|
if (reactorVersion.startsWith('20')) {
|
||||||
|
if (reactorVersion.endsWith('SNAPSHOT') || reactorVersion.endsWith('+')) {
|
||||||
|
ext.reactorLatestVersion = "latest.integration"
|
||||||
|
} else {
|
||||||
|
ext.reactorLatestVersion = "latest.release"
|
||||||
|
}
|
||||||
|
configurations {
|
||||||
|
all {
|
||||||
|
resolutionStrategy {
|
||||||
|
eachDependency { DependencyResolveDetails details ->
|
||||||
|
if (details.requested.name == 'reactor-netty') {
|
||||||
|
details.useTarget("${details.requested.group}:reactor-netty-http:${reactorLatestVersion}")
|
||||||
|
details.because("reactor-netty is now split into reactor-netty-core and reactor-netty-http")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,23 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
antlr:antlr:2.7.7
|
||||||
|
ch.qos.logback:logback-classic:1.2.3
|
||||||
|
ch.qos.logback:logback-core:1.2.3
|
||||||
|
com.google.code.findbugs:jsr305:3.0.2
|
||||||
|
com.google.errorprone:error_prone_annotations:2.2.0
|
||||||
|
com.google.guava:failureaccess:1.0.1
|
||||||
|
com.google.guava:guava:27.1-jre
|
||||||
|
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
|
||||||
|
com.google.j2objc:j2objc-annotations:1.1
|
||||||
|
com.puppycrawl.tools:checkstyle:8.22
|
||||||
|
commons-beanutils:commons-beanutils:1.9.3
|
||||||
|
commons-collections:commons-collections:3.2.2
|
||||||
|
info.picocli:picocli:3.9.6
|
||||||
|
io.spring.javaformat:spring-javaformat-checkstyle:0.0.15
|
||||||
|
io.spring.nohttp:nohttp-checkstyle:0.0.3.RELEASE
|
||||||
|
io.spring.nohttp:nohttp:0.0.3.RELEASE
|
||||||
|
net.sf.saxon:Saxon-HE:9.9.1-3
|
||||||
|
org.antlr:antlr4-runtime:4.7.2
|
||||||
|
org.checkerframework:checker-qual:2.5.2
|
||||||
|
org.codehaus.mojo:animal-sniffer-annotations:1.17
|
@ -0,0 +1,21 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
@ -0,0 +1,21 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,21 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
@ -0,0 +1,4 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
org.jacoco:org.jacoco.agent:0.8.5
|
@ -0,0 +1,11 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
org.jacoco:org.jacoco.agent:0.8.5
|
||||||
|
org.jacoco:org.jacoco.ant:0.8.5
|
||||||
|
org.jacoco:org.jacoco.core:0.8.5
|
||||||
|
org.jacoco:org.jacoco.report:0.8.5
|
||||||
|
org.ow2.asm:asm-analysis:7.2
|
||||||
|
org.ow2.asm:asm-commons:7.2
|
||||||
|
org.ow2.asm:asm-tree:7.2
|
||||||
|
org.ow2.asm:asm:7.2
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,4 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
javax.servlet:javax.servlet-api:4.0.1
|
@ -0,0 +1,21 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
@ -0,0 +1,21 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,36 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.jayway.jsonpath:json-path:2.4.0
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
net.minidev:accessors-smart:1.2
|
||||||
|
net.minidev:json-smart:2.3
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.ow2.asm:asm:5.0.4
|
||||||
|
org.slf4j:slf4j-api:1.7.25
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-test:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-webmvc:5.2.9.RELEASE
|
@ -0,0 +1,36 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.jayway.jsonpath:json-path:2.4.0
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
net.minidev:accessors-smart:1.2
|
||||||
|
net.minidev:json-smart:2.3
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.ow2.asm:asm:5.0.4
|
||||||
|
org.slf4j:slf4j-api:1.7.25
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-test:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-webmvc:5.2.9.RELEASE
|
@ -0,0 +1,3 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
@ -0,0 +1,36 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.jayway.jsonpath:json-path:2.4.0
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
net.minidev:accessors-smart:1.2
|
||||||
|
net.minidev:json-smart:2.3
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.ow2.asm:asm:5.0.4
|
||||||
|
org.slf4j:slf4j-api:1.7.25
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-test:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-webmvc:5.2.9.RELEASE
|
@ -0,0 +1,36 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.jayway.jsonpath:json-path:2.4.0
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
net.minidev:accessors-smart:1.2
|
||||||
|
net.minidev:json-smart:2.3
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.ow2.asm:asm:5.0.4
|
||||||
|
org.slf4j:slf4j-api:1.7.25
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-test:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-webmvc:5.2.9.RELEASE
|
@ -0,0 +1,36 @@
|
|||||||
|
# This is a Gradle generated file for dependency locking.
|
||||||
|
# Manual edits can break the build and are not advised.
|
||||||
|
# This file is expected to be part of source control.
|
||||||
|
com.fasterxml.jackson.core:jackson-annotations:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-core:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson.core:jackson-databind:2.12.0-rc1
|
||||||
|
com.fasterxml.jackson:jackson-bom:2.12.0-rc1
|
||||||
|
com.github.stephenc.jcip:jcip-annotations:1.0-1
|
||||||
|
com.jayway.jsonpath:json-path:2.4.0
|
||||||
|
com.nimbusds:nimbus-jose-jwt:9.0.1
|
||||||
|
junit:junit:4.13.1
|
||||||
|
net.bytebuddy:byte-buddy-agent:1.10.15
|
||||||
|
net.bytebuddy:byte-buddy:1.10.15
|
||||||
|
net.minidev:accessors-smart:1.2
|
||||||
|
net.minidev:json-smart:2.3
|
||||||
|
org.assertj:assertj-core:3.17.2
|
||||||
|
org.hamcrest:hamcrest-core:1.3
|
||||||
|
org.mockito:mockito-core:3.5.13
|
||||||
|
org.objenesis:objenesis:3.1
|
||||||
|
org.ow2.asm:asm:5.0.4
|
||||||
|
org.slf4j:slf4j-api:1.7.25
|
||||||
|
org.springframework.security:spring-security-config:5.4.1
|
||||||
|
org.springframework.security:spring-security-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-core:5.4.1
|
||||||
|
org.springframework.security:spring-security-oauth2-jose:5.4.1
|
||||||
|
org.springframework.security:spring-security-test:5.4.1
|
||||||
|
org.springframework.security:spring-security-web:5.4.1
|
||||||
|
org.springframework:spring-aop:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-beans:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-context:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-core:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-expression:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-jcl:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-test:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-web:5.2.9.RELEASE
|
||||||
|
org.springframework:spring-webmvc:5.2.9.RELEASE
|
@ -20,5 +20,5 @@ dependencies {
|
|||||||
}
|
}
|
||||||
|
|
||||||
jacoco {
|
jacoco {
|
||||||
toolVersion = '0.8.6'
|
toolVersion = '0.8.5'
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -17,44 +17,21 @@ package org.springframework.security.config.annotation.web.configuration;
|
|||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.Ordered;
|
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
|
|
||||||
import org.springframework.security.web.SecurityFilterChain;
|
|
||||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@link Configuration} for OAuth 2.0 Authorization Server support.
|
* {@link Configuration} for OAuth 2.0 Authorization Server support.
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2AuthorizationServerConfigurer
|
|
||||||
*/
|
*/
|
||||||
@Configuration(proxyBeanMethods = false)
|
@Configuration(proxyBeanMethods = false)
|
||||||
public class OAuth2AuthorizationServerConfiguration {
|
public class OAuth2AuthorizationServerConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
public WebSecurityConfigurer<WebSecurity> defaultOAuth2AuthorizationServerSecurity() {
|
||||||
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
|
return new OAuth2AuthorizationServerSecurity();
|
||||||
applyDefaultSecurity(http);
|
|
||||||
return http.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
public static void applyDefaultSecurity(HttpSecurity http) throws Exception {
|
|
||||||
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
|
|
||||||
new OAuth2AuthorizationServerConfigurer<>();
|
|
||||||
RequestMatcher endpointsMatcher = authorizationServerConfigurer
|
|
||||||
.getEndpointsMatcher();
|
|
||||||
|
|
||||||
http
|
|
||||||
.requestMatcher(endpointsMatcher)
|
|
||||||
.authorizeRequests(authorizeRequests ->
|
|
||||||
authorizeRequests.anyRequest().authenticated()
|
|
||||||
)
|
|
||||||
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
|
|
||||||
.apply(authorizationServerConfigurer);
|
|
||||||
}
|
|
||||||
// @formatter:on
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,58 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package org.springframework.security.config.annotation.web.configuration;
|
||||||
|
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
|
||||||
|
import org.springframework.security.web.util.matcher.OrRequestMatcher;
|
||||||
|
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||||
|
|
||||||
|
import static org.springframework.security.config.Customizer.withDefaults;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link WebSecurityConfigurerAdapter} providing default security configuration for OAuth 2.0 Authorization Server.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
|
*/
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
|
public class OAuth2AuthorizationServerSecurity extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
applyDefaultConfiguration(http);
|
||||||
|
}
|
||||||
|
|
||||||
|
// @formatter:off
|
||||||
|
public static void applyDefaultConfiguration(HttpSecurity http) throws Exception {
|
||||||
|
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer =
|
||||||
|
new OAuth2AuthorizationServerConfigurer<>();
|
||||||
|
RequestMatcher[] endpointMatchers = authorizationServerConfigurer
|
||||||
|
.getEndpointMatchers().toArray(new RequestMatcher[0]);
|
||||||
|
|
||||||
|
http
|
||||||
|
.requestMatcher(new OrRequestMatcher(endpointMatchers))
|
||||||
|
.authorizeRequests(authorizeRequests ->
|
||||||
|
authorizeRequests.anyRequest().authenticated()
|
||||||
|
)
|
||||||
|
.formLogin(withDefaults())
|
||||||
|
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointMatchers))
|
||||||
|
.apply(authorizationServerConfigurer);
|
||||||
|
}
|
||||||
|
// @formatter:on
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,86 +15,66 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
|
package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization;
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
|
||||||
import com.nimbusds.jose.proc.SecurityContext;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.BeanFactoryUtils;
|
import org.springframework.beans.factory.BeanFactoryUtils;
|
||||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
|
||||||
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
|
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
|
||||||
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.core.ResolvableType;
|
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
|
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
|
import org.springframework.security.crypto.keys.KeyManager;
|
||||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
import org.springframework.security.oauth2.jose.jws.NimbusJwsEncoder;
|
||||||
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
|
|
||||||
import org.springframework.security.oauth2.jwt.NimbusJwsEncoder;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
|
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
|
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
|
||||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationProvider;
|
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationProvider;
|
||||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationProvider;
|
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationProvider;
|
||||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2RefreshTokenAuthenticationProvider;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2TokenRevocationAuthenticationProvider;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||||
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
|
import org.springframework.security.oauth2.server.authorization.web.JwkSetEndpointFilter;
|
||||||
import org.springframework.security.oauth2.server.authorization.oidc.web.OidcProviderConfigurationEndpointFilter;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.web.NimbusJwkSetEndpointFilter;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
|
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
|
||||||
import org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter;
|
import org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter;
|
||||||
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
|
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
|
||||||
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter;
|
|
||||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
|
||||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||||
import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint;
|
|
||||||
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
|
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
|
||||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
|
||||||
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
||||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
|
||||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||||
import org.springframework.security.web.util.matcher.OrRequestMatcher;
|
import org.springframework.security.web.util.matcher.OrRequestMatcher;
|
||||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Authorization Server support.
|
* An {@link AbstractHttpConfigurer} for OAuth 2.0 Authorization Server support.
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see AbstractHttpConfigurer
|
* @see AbstractHttpConfigurer
|
||||||
* @see RegisteredClientRepository
|
* @see RegisteredClientRepository
|
||||||
* @see OAuth2AuthorizationService
|
* @see OAuth2AuthorizationService
|
||||||
* @see OAuth2AuthorizationEndpointFilter
|
* @see OAuth2AuthorizationEndpointFilter
|
||||||
* @see OAuth2TokenEndpointFilter
|
* @see OAuth2TokenEndpointFilter
|
||||||
* @see OAuth2TokenRevocationEndpointFilter
|
|
||||||
* @see NimbusJwkSetEndpointFilter
|
|
||||||
* @see OidcProviderConfigurationEndpointFilter
|
|
||||||
* @see OAuth2ClientAuthenticationFilter
|
* @see OAuth2ClientAuthenticationFilter
|
||||||
*/
|
*/
|
||||||
public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBuilder<B>>
|
public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBuilder<B>>
|
||||||
extends AbstractHttpConfigurer<OAuth2AuthorizationServerConfigurer<B>, B> {
|
extends AbstractHttpConfigurer<OAuth2AuthorizationServerConfigurer<B>, B> {
|
||||||
|
|
||||||
private RequestMatcher authorizationEndpointMatcher;
|
private final RequestMatcher authorizationEndpointMatcher = new OrRequestMatcher(
|
||||||
private RequestMatcher tokenEndpointMatcher;
|
new AntPathRequestMatcher(
|
||||||
private RequestMatcher tokenRevocationEndpointMatcher;
|
OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI,
|
||||||
private RequestMatcher jwkSetEndpointMatcher;
|
HttpMethod.GET.name()),
|
||||||
private RequestMatcher oidcProviderConfigurationEndpointMatcher;
|
new AntPathRequestMatcher(
|
||||||
private final RequestMatcher endpointsMatcher = (request) ->
|
OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI,
|
||||||
this.authorizationEndpointMatcher.matches(request) ||
|
HttpMethod.POST.name()));
|
||||||
this.tokenEndpointMatcher.matches(request) ||
|
private final RequestMatcher tokenEndpointMatcher = new AntPathRequestMatcher(
|
||||||
this.tokenRevocationEndpointMatcher.matches(request) ||
|
OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI, HttpMethod.POST.name());
|
||||||
this.jwkSetEndpointMatcher.matches(request) ||
|
private final RequestMatcher jwkSetEndpointMatcher = new AntPathRequestMatcher(
|
||||||
this.oidcProviderConfigurationEndpointMatcher.matches(request);
|
JwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI, HttpMethod.GET.name());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the repository of registered clients.
|
* Sets the repository of registered clients.
|
||||||
@ -121,179 +101,99 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the provider settings.
|
* Sets the key manager.
|
||||||
*
|
*
|
||||||
* @param providerSettings the provider settings
|
* @param keyManager the key manager
|
||||||
* @return the {@link OAuth2AuthorizationServerConfigurer} for further configuration
|
* @return the {@link OAuth2AuthorizationServerConfigurer} for further configuration
|
||||||
*/
|
*/
|
||||||
public OAuth2AuthorizationServerConfigurer<B> providerSettings(ProviderSettings providerSettings) {
|
public OAuth2AuthorizationServerConfigurer<B> keyManager(KeyManager keyManager) {
|
||||||
Assert.notNull(providerSettings, "providerSettings cannot be null");
|
Assert.notNull(keyManager, "keyManager cannot be null");
|
||||||
this.getBuilder().setSharedObject(ProviderSettings.class, providerSettings);
|
this.getBuilder().setSharedObject(KeyManager.class, keyManager);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a {@link RequestMatcher} for the authorization server endpoints.
|
* Returns a {@code List} of {@link RequestMatcher}'s for the authorization server endpoints.
|
||||||
*
|
*
|
||||||
* @return a {@link RequestMatcher} for the authorization server endpoints
|
* @return a {@code List} of {@link RequestMatcher}'s for the authorization server endpoints
|
||||||
*/
|
*/
|
||||||
public RequestMatcher getEndpointsMatcher() {
|
public List<RequestMatcher> getEndpointMatchers() {
|
||||||
return this.endpointsMatcher;
|
return Arrays.asList(this.authorizationEndpointMatcher,
|
||||||
|
this.tokenEndpointMatcher, this.jwkSetEndpointMatcher);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void init(B builder) {
|
public void init(B builder) {
|
||||||
ProviderSettings providerSettings = getProviderSettings(builder);
|
|
||||||
validateProviderSettings(providerSettings);
|
|
||||||
initEndpointMatchers(providerSettings);
|
|
||||||
|
|
||||||
OAuth2ClientAuthenticationProvider clientAuthenticationProvider =
|
OAuth2ClientAuthenticationProvider clientAuthenticationProvider =
|
||||||
new OAuth2ClientAuthenticationProvider(
|
new OAuth2ClientAuthenticationProvider(
|
||||||
getRegisteredClientRepository(builder),
|
getRegisteredClientRepository(builder),
|
||||||
getAuthorizationService(builder));
|
getAuthorizationService(builder));
|
||||||
builder.authenticationProvider(postProcess(clientAuthenticationProvider));
|
builder.authenticationProvider(postProcess(clientAuthenticationProvider));
|
||||||
|
|
||||||
JwtEncoder jwtEncoder = getJwtEncoder(builder);
|
NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(getKeyManager(builder));
|
||||||
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = getJwtCustomizer(builder);
|
|
||||||
|
|
||||||
OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider =
|
OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider =
|
||||||
new OAuth2AuthorizationCodeAuthenticationProvider(
|
new OAuth2AuthorizationCodeAuthenticationProvider(
|
||||||
|
getRegisteredClientRepository(builder),
|
||||||
getAuthorizationService(builder),
|
getAuthorizationService(builder),
|
||||||
jwtEncoder);
|
jwtEncoder);
|
||||||
if (jwtCustomizer != null) {
|
|
||||||
authorizationCodeAuthenticationProvider.setJwtCustomizer(jwtCustomizer);
|
|
||||||
}
|
|
||||||
builder.authenticationProvider(postProcess(authorizationCodeAuthenticationProvider));
|
builder.authenticationProvider(postProcess(authorizationCodeAuthenticationProvider));
|
||||||
|
|
||||||
OAuth2RefreshTokenAuthenticationProvider refreshTokenAuthenticationProvider =
|
|
||||||
new OAuth2RefreshTokenAuthenticationProvider(
|
|
||||||
getAuthorizationService(builder),
|
|
||||||
jwtEncoder);
|
|
||||||
if (jwtCustomizer != null) {
|
|
||||||
refreshTokenAuthenticationProvider.setJwtCustomizer(jwtCustomizer);
|
|
||||||
}
|
|
||||||
builder.authenticationProvider(postProcess(refreshTokenAuthenticationProvider));
|
|
||||||
|
|
||||||
OAuth2ClientCredentialsAuthenticationProvider clientCredentialsAuthenticationProvider =
|
OAuth2ClientCredentialsAuthenticationProvider clientCredentialsAuthenticationProvider =
|
||||||
new OAuth2ClientCredentialsAuthenticationProvider(
|
new OAuth2ClientCredentialsAuthenticationProvider(
|
||||||
getAuthorizationService(builder),
|
getAuthorizationService(builder),
|
||||||
jwtEncoder);
|
jwtEncoder);
|
||||||
if (jwtCustomizer != null) {
|
|
||||||
clientCredentialsAuthenticationProvider.setJwtCustomizer(jwtCustomizer);
|
|
||||||
}
|
|
||||||
builder.authenticationProvider(postProcess(clientCredentialsAuthenticationProvider));
|
builder.authenticationProvider(postProcess(clientCredentialsAuthenticationProvider));
|
||||||
|
|
||||||
OAuth2TokenRevocationAuthenticationProvider tokenRevocationAuthenticationProvider =
|
|
||||||
new OAuth2TokenRevocationAuthenticationProvider(
|
|
||||||
getAuthorizationService(builder));
|
|
||||||
builder.authenticationProvider(postProcess(tokenRevocationAuthenticationProvider));
|
|
||||||
|
|
||||||
ExceptionHandlingConfigurer<B> exceptionHandling = builder.getConfigurer(ExceptionHandlingConfigurer.class);
|
ExceptionHandlingConfigurer<B> exceptionHandling = builder.getConfigurer(ExceptionHandlingConfigurer.class);
|
||||||
if (exceptionHandling != null) {
|
if (exceptionHandling != null) {
|
||||||
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
|
// Register the default AuthenticationEntryPoint for the token endpoint
|
||||||
entryPoints.put(
|
exceptionHandling.defaultAuthenticationEntryPointFor(
|
||||||
new OrRequestMatcher(
|
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED), this.tokenEndpointMatcher);
|
||||||
this.tokenEndpointMatcher,
|
|
||||||
this.tokenRevocationEndpointMatcher),
|
|
||||||
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
|
|
||||||
DelegatingAuthenticationEntryPoint authenticationEntryPoint =
|
|
||||||
new DelegatingAuthenticationEntryPoint(entryPoints);
|
|
||||||
|
|
||||||
// TODO This needs to change as the login page could be customized with a different URL
|
|
||||||
authenticationEntryPoint.setDefaultEntryPoint(
|
|
||||||
new LoginUrlAuthenticationEntryPoint(
|
|
||||||
DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL));
|
|
||||||
|
|
||||||
exceptionHandling.authenticationEntryPoint(authenticationEntryPoint);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void configure(B builder) {
|
public void configure(B builder) {
|
||||||
ProviderSettings providerSettings = getProviderSettings(builder);
|
JwkSetEndpointFilter jwkSetEndpointFilter = new JwkSetEndpointFilter(getKeyManager(builder));
|
||||||
if (providerSettings.issuer() != null) {
|
|
||||||
OidcProviderConfigurationEndpointFilter oidcProviderConfigurationEndpointFilter =
|
|
||||||
new OidcProviderConfigurationEndpointFilter(providerSettings);
|
|
||||||
builder.addFilterBefore(postProcess(oidcProviderConfigurationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
JWKSource<SecurityContext> jwkSource = getJwkSource(builder);
|
|
||||||
NimbusJwkSetEndpointFilter jwkSetEndpointFilter = new NimbusJwkSetEndpointFilter(
|
|
||||||
jwkSource,
|
|
||||||
providerSettings.jwkSetEndpoint());
|
|
||||||
builder.addFilterBefore(postProcess(jwkSetEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
builder.addFilterBefore(postProcess(jwkSetEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
||||||
|
|
||||||
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
|
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationFilter clientAuthenticationFilter =
|
OAuth2ClientAuthenticationFilter clientAuthenticationFilter = new OAuth2ClientAuthenticationFilter(
|
||||||
new OAuth2ClientAuthenticationFilter(
|
authenticationManager, this.tokenEndpointMatcher);
|
||||||
authenticationManager,
|
|
||||||
new OrRequestMatcher(
|
|
||||||
this.tokenEndpointMatcher,
|
|
||||||
this.tokenRevocationEndpointMatcher));
|
|
||||||
builder.addFilterAfter(postProcess(clientAuthenticationFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
builder.addFilterAfter(postProcess(clientAuthenticationFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
||||||
|
|
||||||
OAuth2AuthorizationEndpointFilter authorizationEndpointFilter =
|
OAuth2AuthorizationEndpointFilter authorizationEndpointFilter =
|
||||||
new OAuth2AuthorizationEndpointFilter(
|
new OAuth2AuthorizationEndpointFilter(
|
||||||
getRegisteredClientRepository(builder),
|
getRegisteredClientRepository(builder),
|
||||||
getAuthorizationService(builder),
|
getAuthorizationService(builder));
|
||||||
providerSettings.authorizationEndpoint());
|
|
||||||
builder.addFilterBefore(postProcess(authorizationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
builder.addFilterBefore(postProcess(authorizationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
|
||||||
|
|
||||||
OAuth2TokenEndpointFilter tokenEndpointFilter =
|
OAuth2TokenEndpointFilter tokenEndpointFilter =
|
||||||
new OAuth2TokenEndpointFilter(
|
new OAuth2TokenEndpointFilter(
|
||||||
authenticationManager,
|
authenticationManager,
|
||||||
providerSettings.tokenEndpoint());
|
getAuthorizationService(builder));
|
||||||
builder.addFilterAfter(postProcess(tokenEndpointFilter), FilterSecurityInterceptor.class);
|
builder.addFilterAfter(postProcess(tokenEndpointFilter), FilterSecurityInterceptor.class);
|
||||||
|
|
||||||
OAuth2TokenRevocationEndpointFilter tokenRevocationEndpointFilter =
|
|
||||||
new OAuth2TokenRevocationEndpointFilter(
|
|
||||||
authenticationManager,
|
|
||||||
providerSettings.tokenRevocationEndpoint());
|
|
||||||
builder.addFilterAfter(postProcess(tokenRevocationEndpointFilter), OAuth2TokenEndpointFilter.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void initEndpointMatchers(ProviderSettings providerSettings) {
|
|
||||||
this.authorizationEndpointMatcher = new OrRequestMatcher(
|
|
||||||
new AntPathRequestMatcher(
|
|
||||||
providerSettings.authorizationEndpoint(),
|
|
||||||
HttpMethod.GET.name()),
|
|
||||||
new AntPathRequestMatcher(
|
|
||||||
providerSettings.authorizationEndpoint(),
|
|
||||||
HttpMethod.POST.name()));
|
|
||||||
this.tokenEndpointMatcher = new AntPathRequestMatcher(
|
|
||||||
providerSettings.tokenEndpoint(), HttpMethod.POST.name());
|
|
||||||
this.tokenRevocationEndpointMatcher = new AntPathRequestMatcher(
|
|
||||||
providerSettings.tokenRevocationEndpoint(), HttpMethod.POST.name());
|
|
||||||
this.jwkSetEndpointMatcher = new AntPathRequestMatcher(
|
|
||||||
providerSettings.jwkSetEndpoint(), HttpMethod.GET.name());
|
|
||||||
this.oidcProviderConfigurationEndpointMatcher = new AntPathRequestMatcher(
|
|
||||||
OidcProviderConfigurationEndpointFilter.DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI, HttpMethod.GET.name());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void validateProviderSettings(ProviderSettings providerSettings) {
|
|
||||||
if (providerSettings.issuer() != null) {
|
|
||||||
try {
|
|
||||||
new URI(providerSettings.issuer()).toURL();
|
|
||||||
} catch (Exception ex) {
|
|
||||||
throw new IllegalArgumentException("issuer must be a valid URL", ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepository(B builder) {
|
private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepository(B builder) {
|
||||||
RegisteredClientRepository registeredClientRepository = builder.getSharedObject(RegisteredClientRepository.class);
|
RegisteredClientRepository registeredClientRepository = builder.getSharedObject(RegisteredClientRepository.class);
|
||||||
if (registeredClientRepository == null) {
|
if (registeredClientRepository == null) {
|
||||||
registeredClientRepository = getBean(builder, RegisteredClientRepository.class);
|
registeredClientRepository = getRegisteredClientRepositoryBean(builder);
|
||||||
builder.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
|
builder.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
|
||||||
}
|
}
|
||||||
return registeredClientRepository;
|
return registeredClientRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static <B extends HttpSecurityBuilder<B>> RegisteredClientRepository getRegisteredClientRepositoryBean(B builder) {
|
||||||
|
return builder.getSharedObject(ApplicationContext.class).getBean(RegisteredClientRepository.class);
|
||||||
|
}
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizationService getAuthorizationService(B builder) {
|
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizationService getAuthorizationService(B builder) {
|
||||||
OAuth2AuthorizationService authorizationService = builder.getSharedObject(OAuth2AuthorizationService.class);
|
OAuth2AuthorizationService authorizationService = builder.getSharedObject(OAuth2AuthorizationService.class);
|
||||||
if (authorizationService == null) {
|
if (authorizationService == null) {
|
||||||
authorizationService = getOptionalBean(builder, OAuth2AuthorizationService.class);
|
authorizationService = getAuthorizationServiceBean(builder);
|
||||||
if (authorizationService == null) {
|
if (authorizationService == null) {
|
||||||
authorizationService = new InMemoryOAuth2AuthorizationService();
|
authorizationService = new InMemoryOAuth2AuthorizationService();
|
||||||
}
|
}
|
||||||
@ -302,90 +202,27 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
|
|||||||
return authorizationService;
|
return authorizationService;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>> JwtEncoder getJwtEncoder(B builder) {
|
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizationService getAuthorizationServiceBean(B builder) {
|
||||||
JwtEncoder jwtEncoder = builder.getSharedObject(JwtEncoder.class);
|
Map<String, OAuth2AuthorizationService> authorizationServiceMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
||||||
if (jwtEncoder == null) {
|
builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizationService.class);
|
||||||
jwtEncoder = getOptionalBean(builder, JwtEncoder.class);
|
if (authorizationServiceMap.size() > 1) {
|
||||||
if (jwtEncoder == null) {
|
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizationService.class, authorizationServiceMap.size(),
|
||||||
JWKSource<SecurityContext> jwkSource = getJwkSource(builder);
|
"Expected single matching bean of type '" + OAuth2AuthorizationService.class.getName() + "' but found " +
|
||||||
jwtEncoder = new NimbusJwsEncoder(jwkSource);
|
authorizationServiceMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizationServiceMap.keySet()));
|
||||||
}
|
}
|
||||||
builder.setSharedObject(JwtEncoder.class, jwtEncoder);
|
return (!authorizationServiceMap.isEmpty() ? authorizationServiceMap.values().iterator().next() : null);
|
||||||
}
|
|
||||||
return jwtEncoder;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
private static <B extends HttpSecurityBuilder<B>> KeyManager getKeyManager(B builder) {
|
||||||
private static <B extends HttpSecurityBuilder<B>> JWKSource<SecurityContext> getJwkSource(B builder) {
|
KeyManager keyManager = builder.getSharedObject(KeyManager.class);
|
||||||
JWKSource<SecurityContext> jwkSource = builder.getSharedObject(JWKSource.class);
|
if (keyManager == null) {
|
||||||
if (jwkSource == null) {
|
keyManager = getKeyManagerBean(builder);
|
||||||
ResolvableType type = ResolvableType.forClassWithGenerics(JWKSource.class, SecurityContext.class);
|
builder.setSharedObject(KeyManager.class, keyManager);
|
||||||
jwkSource = getBean(builder, type);
|
|
||||||
builder.setSharedObject(JWKSource.class, jwkSource);
|
|
||||||
}
|
}
|
||||||
return jwkSource;
|
return keyManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
private static <B extends HttpSecurityBuilder<B>> KeyManager getKeyManagerBean(B builder) {
|
||||||
private static <B extends HttpSecurityBuilder<B>> OAuth2TokenCustomizer<JwtEncodingContext> getJwtCustomizer(B builder) {
|
return builder.getSharedObject(ApplicationContext.class).getBean(KeyManager.class);
|
||||||
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = builder.getSharedObject(OAuth2TokenCustomizer.class);
|
|
||||||
if (jwtCustomizer == null) {
|
|
||||||
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
|
|
||||||
jwtCustomizer = getOptionalBean(builder, type);
|
|
||||||
if (jwtCustomizer != null) {
|
|
||||||
builder.setSharedObject(OAuth2TokenCustomizer.class, jwtCustomizer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return jwtCustomizer;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>> ProviderSettings getProviderSettings(B builder) {
|
|
||||||
ProviderSettings providerSettings = builder.getSharedObject(ProviderSettings.class);
|
|
||||||
if (providerSettings == null) {
|
|
||||||
providerSettings = getOptionalBean(builder, ProviderSettings.class);
|
|
||||||
if (providerSettings == null) {
|
|
||||||
providerSettings = new ProviderSettings();
|
|
||||||
}
|
|
||||||
builder.setSharedObject(ProviderSettings.class, providerSettings);
|
|
||||||
}
|
|
||||||
return providerSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>, T> T getBean(B builder, Class<T> type) {
|
|
||||||
return builder.getSharedObject(ApplicationContext.class).getBean(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static <B extends HttpSecurityBuilder<B>, T> T getBean(B builder, ResolvableType type) {
|
|
||||||
ApplicationContext context = builder.getSharedObject(ApplicationContext.class);
|
|
||||||
String[] names = context.getBeanNamesForType(type);
|
|
||||||
if (names.length == 1) {
|
|
||||||
return (T) context.getBean(names[0]);
|
|
||||||
}
|
|
||||||
if (names.length > 1) {
|
|
||||||
throw new NoUniqueBeanDefinitionException(type, names);
|
|
||||||
}
|
|
||||||
throw new NoSuchBeanDefinitionException(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static <B extends HttpSecurityBuilder<B>, T> T getOptionalBean(B builder, Class<T> type) {
|
|
||||||
Map<String, T> beansMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
|
|
||||||
builder.getSharedObject(ApplicationContext.class), type);
|
|
||||||
if (beansMap.size() > 1) {
|
|
||||||
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
|
|
||||||
"Expected single matching bean of type '" + type.getName() + "' but found " +
|
|
||||||
beansMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
|
|
||||||
}
|
|
||||||
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static <B extends HttpSecurityBuilder<B>, T> T getOptionalBean(B builder, ResolvableType type) {
|
|
||||||
ApplicationContext context = builder.getSharedObject(ApplicationContext.class);
|
|
||||||
String[] names = context.getBeanNamesForType(type);
|
|
||||||
if (names.length > 1) {
|
|
||||||
throw new NoUniqueBeanDefinitionException(type, names);
|
|
||||||
}
|
|
||||||
return names.length == 1 ? (T) context.getBean(names[0]) : null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,8 +13,10 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package sample.jose;
|
package org.springframework.security.crypto.keys;
|
||||||
|
|
||||||
|
import javax.crypto.KeyGenerator;
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.security.KeyPair;
|
import java.security.KeyPair;
|
||||||
import java.security.KeyPairGenerator;
|
import java.security.KeyPairGenerator;
|
||||||
@ -23,18 +25,12 @@ import java.security.spec.ECParameterSpec;
|
|||||||
import java.security.spec.ECPoint;
|
import java.security.spec.ECPoint;
|
||||||
import java.security.spec.EllipticCurve;
|
import java.security.spec.EllipticCurve;
|
||||||
|
|
||||||
import javax.crypto.KeyGenerator;
|
|
||||||
import javax.crypto.SecretKey;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.1.0
|
* @since 0.0.1
|
||||||
*/
|
*/
|
||||||
final class KeyGeneratorUtils {
|
final class KeyGeneratorUtils {
|
||||||
|
|
||||||
private KeyGeneratorUtils() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static SecretKey generateSecretKey() {
|
static SecretKey generateSecretKey() {
|
||||||
SecretKey hmacKey;
|
SecretKey hmacKey;
|
||||||
try {
|
try {
|
@ -0,0 +1,58 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package org.springframework.security.crypto.keys;
|
||||||
|
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementations of this interface are responsible for the management of {@link ManagedKey}(s),
|
||||||
|
* e.g. {@code javax.crypto.SecretKey}, {@code java.security.PrivateKey}, {@code java.security.PublicKey}, etc.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
|
* @see ManagedKey
|
||||||
|
*/
|
||||||
|
public interface KeyManager {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the {@link ManagedKey} identified by the provided {@code keyId},
|
||||||
|
* or {@code null} if not found.
|
||||||
|
*
|
||||||
|
* @param keyId the key ID
|
||||||
|
* @return the {@link ManagedKey}, or {@code null} if not found
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
ManagedKey findByKeyId(String keyId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a {@code Set} of {@link ManagedKey}(s) having the provided key {@code algorithm},
|
||||||
|
* or an empty {@code Set} if not found.
|
||||||
|
*
|
||||||
|
* @param algorithm the key algorithm
|
||||||
|
* @return a {@code Set} of {@link ManagedKey}(s), or an empty {@code Set} if not found
|
||||||
|
*/
|
||||||
|
Set<ManagedKey> findByAlgorithm(String algorithm);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a {@code Set} of the {@link ManagedKey}(s).
|
||||||
|
*
|
||||||
|
* @return a {@code Set} of the {@link ManagedKey}(s)
|
||||||
|
*/
|
||||||
|
Set<ManagedKey> getKeys();
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,246 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package org.springframework.security.crypto.keys;
|
||||||
|
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.security.Key;
|
||||||
|
import java.security.PrivateKey;
|
||||||
|
import java.security.PublicKey;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@code java.security.Key} that is managed by a {@link KeyManager}.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
|
* @see KeyManager
|
||||||
|
*/
|
||||||
|
public final class ManagedKey implements Serializable {
|
||||||
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
|
private Key key;
|
||||||
|
private PublicKey publicKey;
|
||||||
|
private String keyId;
|
||||||
|
private Instant activatedOn;
|
||||||
|
private Instant deactivatedOn;
|
||||||
|
|
||||||
|
private ManagedKey() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this is a symmetric key, {@code false} otherwise.
|
||||||
|
*
|
||||||
|
* @return {@code true} if this is a symmetric key, {@code false} otherwise
|
||||||
|
*/
|
||||||
|
public boolean isSymmetric() {
|
||||||
|
return SecretKey.class.isAssignableFrom(this.key.getClass());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this is a asymmetric key, {@code false} otherwise.
|
||||||
|
*
|
||||||
|
* @return {@code true} if this is a asymmetric key, {@code false} otherwise
|
||||||
|
*/
|
||||||
|
public boolean isAsymmetric() {
|
||||||
|
return PrivateKey.class.isAssignableFrom(this.key.getClass());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a type of {@code java.security.Key},
|
||||||
|
* e.g. {@code javax.crypto.SecretKey} or {@code java.security.PrivateKey}.
|
||||||
|
*
|
||||||
|
* @param <T> the type of {@code java.security.Key}
|
||||||
|
* @return the type of {@code java.security.Key}
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T extends Key> T getKey() {
|
||||||
|
return (T) this.key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the {@code java.security.PublicKey} if this is a asymmetric key, {@code null} otherwise.
|
||||||
|
*
|
||||||
|
* @return the {@code java.security.PublicKey} if this is a asymmetric key, {@code null} otherwise
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
public PublicKey getPublicKey() {
|
||||||
|
return this.publicKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the key ID.
|
||||||
|
*
|
||||||
|
* @return the key ID
|
||||||
|
*/
|
||||||
|
public String getKeyId() {
|
||||||
|
return this.keyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the time when this key was activated.
|
||||||
|
*
|
||||||
|
* @return the time when this key was activated
|
||||||
|
*/
|
||||||
|
public Instant getActivatedOn() {
|
||||||
|
return this.activatedOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the time when this key was deactivated, {@code null} if still active.
|
||||||
|
*
|
||||||
|
* @return the time when this key was deactivated, {@code null} if still active
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
public Instant getDeactivatedOn() {
|
||||||
|
return this.deactivatedOn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this key is active, {@code false} otherwise.
|
||||||
|
*
|
||||||
|
* @return {@code true} if this key is active, {@code false} otherwise
|
||||||
|
*/
|
||||||
|
public boolean isActive() {
|
||||||
|
return getDeactivatedOn() == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the key algorithm.
|
||||||
|
*
|
||||||
|
* @return the key algorithm
|
||||||
|
*/
|
||||||
|
public String getAlgorithm() {
|
||||||
|
return this.key.getAlgorithm();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (obj == null || getClass() != obj.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ManagedKey that = (ManagedKey) obj;
|
||||||
|
return Objects.equals(this.keyId, that.keyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(this.keyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a new {@link Builder}, initialized with the provided {@code javax.crypto.SecretKey}.
|
||||||
|
*
|
||||||
|
* @param secretKey the {@code javax.crypto.SecretKey}
|
||||||
|
* @return the {@link Builder}
|
||||||
|
*/
|
||||||
|
public static Builder withSymmetricKey(SecretKey secretKey) {
|
||||||
|
return new Builder(secretKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a new {@link Builder}, initialized with the provided
|
||||||
|
* {@code java.security.PublicKey} and {@code java.security.PrivateKey}.
|
||||||
|
*
|
||||||
|
* @param publicKey the {@code java.security.PublicKey}
|
||||||
|
* @param privateKey the {@code java.security.PrivateKey}
|
||||||
|
* @return the {@link Builder}
|
||||||
|
*/
|
||||||
|
public static Builder withAsymmetricKey(PublicKey publicKey, PrivateKey privateKey) {
|
||||||
|
return new Builder(publicKey, privateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A builder for {@link ManagedKey}.
|
||||||
|
*/
|
||||||
|
public static class Builder {
|
||||||
|
private Key key;
|
||||||
|
private PublicKey publicKey;
|
||||||
|
private String keyId;
|
||||||
|
private Instant activatedOn;
|
||||||
|
private Instant deactivatedOn;
|
||||||
|
|
||||||
|
private Builder(SecretKey secretKey) {
|
||||||
|
Assert.notNull(secretKey, "secretKey cannot be null");
|
||||||
|
this.key = secretKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Builder(PublicKey publicKey, PrivateKey privateKey) {
|
||||||
|
Assert.notNull(publicKey, "publicKey cannot be null");
|
||||||
|
Assert.notNull(privateKey, "privateKey cannot be null");
|
||||||
|
this.key = privateKey;
|
||||||
|
this.publicKey = publicKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the key ID.
|
||||||
|
*
|
||||||
|
* @param keyId the key ID
|
||||||
|
* @return the {@link Builder}
|
||||||
|
*/
|
||||||
|
public Builder keyId(String keyId) {
|
||||||
|
this.keyId = keyId;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the time when this key was activated.
|
||||||
|
*
|
||||||
|
* @param activatedOn the time when this key was activated
|
||||||
|
* @return the {@link Builder}
|
||||||
|
*/
|
||||||
|
public Builder activatedOn(Instant activatedOn) {
|
||||||
|
this.activatedOn = activatedOn;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the time when this key was deactivated.
|
||||||
|
*
|
||||||
|
* @param deactivatedOn the time when this key was deactivated
|
||||||
|
* @return the {@link Builder}
|
||||||
|
*/
|
||||||
|
public Builder deactivatedOn(Instant deactivatedOn) {
|
||||||
|
this.deactivatedOn = deactivatedOn;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a new {@link ManagedKey}.
|
||||||
|
*
|
||||||
|
* @return a {@link ManagedKey}
|
||||||
|
*/
|
||||||
|
public ManagedKey build() {
|
||||||
|
Assert.hasText(this.keyId, "keyId cannot be empty");
|
||||||
|
Assert.notNull(this.activatedOn, "activatedOn cannot be null");
|
||||||
|
|
||||||
|
ManagedKey managedKey = new ManagedKey();
|
||||||
|
managedKey.key = this.key;
|
||||||
|
managedKey.publicKey = this.publicKey;
|
||||||
|
managedKey.keyId = this.keyId;
|
||||||
|
managedKey.activatedOn = this.activatedOn;
|
||||||
|
managedKey.deactivatedOn = this.deactivatedOn;
|
||||||
|
return managedKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,89 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package org.springframework.security.crypto.keys;
|
||||||
|
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import java.security.KeyPair;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateRsaKey;
|
||||||
|
import static org.springframework.security.crypto.keys.KeyGeneratorUtils.generateSecretKey;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An implementation of a {@link KeyManager} that generates the {@link ManagedKey}(s) when constructed.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* <b>NOTE:</b> This implementation should ONLY be used during development/testing.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
|
* @see KeyManager
|
||||||
|
*/
|
||||||
|
public final class StaticKeyGeneratingKeyManager implements KeyManager {
|
||||||
|
private final Map<String, ManagedKey> keys;
|
||||||
|
|
||||||
|
public StaticKeyGeneratingKeyManager() {
|
||||||
|
this.keys = Collections.unmodifiableMap(new HashMap<>(generateKeys()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
@Override
|
||||||
|
public ManagedKey findByKeyId(String keyId) {
|
||||||
|
Assert.hasText(keyId, "keyId cannot be empty");
|
||||||
|
return this.keys.get(keyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<ManagedKey> findByAlgorithm(String algorithm) {
|
||||||
|
Assert.hasText(algorithm, "algorithm cannot be empty");
|
||||||
|
return this.keys.values().stream()
|
||||||
|
.filter(managedKey -> managedKey.getAlgorithm().equals(algorithm))
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<ManagedKey> getKeys() {
|
||||||
|
return new HashSet<>(this.keys.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, ManagedKey> generateKeys() {
|
||||||
|
KeyPair rsaKeyPair = generateRsaKey();
|
||||||
|
ManagedKey rsaManagedKey = ManagedKey.withAsymmetricKey(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate())
|
||||||
|
.keyId(UUID.randomUUID().toString())
|
||||||
|
.activatedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
SecretKey hmacKey = generateSecretKey();
|
||||||
|
ManagedKey secretManagedKey = ManagedKey.withSymmetricKey(hmacKey)
|
||||||
|
.keyId(UUID.randomUUID().toString())
|
||||||
|
.activatedOn(Instant.now())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return Stream.of(rsaManagedKey, secretManagedKey)
|
||||||
|
.collect(Collectors.toMap(ManagedKey::getKeyId, v -> v));
|
||||||
|
}
|
||||||
|
}
|
@ -1,30 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO
|
|
||||||
* This class is temporary and will be removed after upgrading to Spring Security 5.5.0 GA.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see <a target="_blank" href="https://github.com/spring-projects/spring-security/issues/9184">Issue gh-9184</a>
|
|
||||||
*/
|
|
||||||
public interface OAuth2ErrorCodes2 extends OAuth2ErrorCodes {
|
|
||||||
|
|
||||||
String UNSUPPORTED_TOKEN_TYPE = "unsupported_token_type";
|
|
||||||
|
|
||||||
}
|
|
@ -1,40 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO
|
|
||||||
* This class is temporary and will be removed after upgrading to Spring Security 5.5.0 GA.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see <a target="_blank" href="https://github.com/spring-projects/spring-security/pull/9146">Issue gh-9146</a>
|
|
||||||
*/
|
|
||||||
public class OAuth2RefreshToken2 extends OAuth2RefreshToken {
|
|
||||||
private final Instant expiresAt;
|
|
||||||
|
|
||||||
public OAuth2RefreshToken2(String tokenValue, Instant issuedAt, Instant expiresAt) {
|
|
||||||
super(tokenValue, issuedAt);
|
|
||||||
this.expiresAt = expiresAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Instant getExpiresAt() {
|
|
||||||
return this.expiresAt;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,47 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.context;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A facility for holding information associated to a specific context.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
*/
|
|
||||||
public interface Context {
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
<V> V get(Object key);
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
default <V> V get(Class<V> key) {
|
|
||||||
Assert.notNull(key, "key cannot be null");
|
|
||||||
V value = get((Object) key);
|
|
||||||
return key.isInstance(value) ? value : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean hasKey(Object key);
|
|
||||||
|
|
||||||
static Context of(Map<Object, Object> context) {
|
|
||||||
return new DefaultContext(context);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,50 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.context;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
*/
|
|
||||||
final class DefaultContext implements Context {
|
|
||||||
private final Map<Object, Object> context;
|
|
||||||
|
|
||||||
DefaultContext(Map<Object, Object> context) {
|
|
||||||
Assert.notNull(context, "context cannot be null");
|
|
||||||
this.context = Collections.unmodifiableMap(new HashMap<>(context));
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
@Override
|
|
||||||
@Nullable
|
|
||||||
public <V> V get(Object key) {
|
|
||||||
return hasKey(key) ? (V) this.context.get(key) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean hasKey(Object key) {
|
|
||||||
Assert.notNull(key, "key cannot be null");
|
|
||||||
return this.context.containsKey(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.endpoint;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO
|
|
||||||
* This class is temporary and will be removed after upgrading to Spring Security 5.5.0 GA.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see <a target="_blank" href="https://github.com/spring-projects/spring-security/issues/9183">Issue gh-9183</a>
|
|
||||||
*/
|
|
||||||
public interface OAuth2ParameterNames2 extends OAuth2ParameterNames {
|
|
||||||
|
|
||||||
String TOKEN = "token";
|
|
||||||
|
|
||||||
String TOKEN_TYPE_HINT = "token_type_hint";
|
|
||||||
|
|
||||||
}
|
|
@ -1,358 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.oidc;
|
|
||||||
|
|
||||||
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URL;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A representation of an OpenID Provider Configuration Response,
|
|
||||||
* which is returned from an Issuer's Discovery Endpoint,
|
|
||||||
* and contains a set of claims about the OpenID Provider's configuration.
|
|
||||||
* The claims are defined by the OpenID Connect Discovery 1.0 specification.
|
|
||||||
*
|
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see OidcProviderMetadataClaimAccessor
|
|
||||||
* @see <a target="_blank" href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">4.2. OpenID Provider Configuration Response</a>
|
|
||||||
*/
|
|
||||||
public final class OidcProviderConfiguration implements OidcProviderMetadataClaimAccessor, Serializable {
|
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
|
||||||
private final Map<String, Object> claims;
|
|
||||||
|
|
||||||
private OidcProviderConfiguration(Map<String, Object> claims) {
|
|
||||||
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the OpenID Provider Configuration metadata.
|
|
||||||
*
|
|
||||||
* @return a {@code Map} of the metadata values
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> getClaims() {
|
|
||||||
return this.claims;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a new {@link Builder} with empty claims.
|
|
||||||
*
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public static Builder builder() {
|
|
||||||
return new Builder();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a new {@link Builder} with the provided claims.
|
|
||||||
*
|
|
||||||
* @param claims the claims to initialize the builder
|
|
||||||
*/
|
|
||||||
public static Builder withClaims(Map<String, Object> claims) {
|
|
||||||
Assert.notEmpty(claims, "claims cannot be empty");
|
|
||||||
return new Builder()
|
|
||||||
.claims(c -> c.putAll(claims));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helps configure an {@link OidcProviderConfiguration}
|
|
||||||
*/
|
|
||||||
public static class Builder {
|
|
||||||
private final Map<String, Object> claims = new LinkedHashMap<>();
|
|
||||||
|
|
||||||
private Builder() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use this {@code issuer} in the resulting {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param issuer the URL of the OpenID Provider's Issuer Identifier
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder issuer(String issuer) {
|
|
||||||
return claim(OidcProviderMetadataClaimNames.ISSUER, issuer);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use this {@code authorization_endpoint} in the resulting {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param authorizationEndpoint the URL of the OpenID Provider's OAuth 2.0 Authorization Endpoint
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder authorizationEndpoint(String authorizationEndpoint) {
|
|
||||||
return claim(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, authorizationEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use this {@code token_endpoint} in the resulting {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param tokenEndpoint the URL of the OpenID Provider's OAuth 2.0 Token Endpoint
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder tokenEndpoint(String tokenEndpoint) {
|
|
||||||
return claim(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, tokenEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this Authentication Method to the collection of {@code token_endpoint_auth_methods_supported}
|
|
||||||
* in the resulting {@link OidcProviderConfiguration}, OPTIONAL.
|
|
||||||
*
|
|
||||||
* @param authenticationMethod the OAuth 2.0 Authentication Method supported by the Token endpoint
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder tokenEndpointAuthenticationMethod(String authenticationMethod) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED, authenticationMethod);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the Token Endpoint Authentication Method(s) allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param authenticationMethodsConsumer a {@code Consumer} of the Token Endpoint Authentication Method(s)
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder tokenEndpointAuthenticationMethods(Consumer<List<String>> authenticationMethodsConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED, authenticationMethodsConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use this {@code jwks_uri} in the resulting {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param jwkSetUri the URL of the OpenID Provider's JSON Web Key Set document
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder jwkSetUri(String jwkSetUri) {
|
|
||||||
return claim(OidcProviderMetadataClaimNames.JWKS_URI, jwkSetUri);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this Response Type to the collection of {@code response_types_supported} in the resulting
|
|
||||||
* {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param responseType the OAuth 2.0 {@code response_type} value that the OpenID Provider supports
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder responseType(String responseType) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, responseType);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the Response Type(s) allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param responseTypesConsumer a {@code Consumer} of the Response Type(s)
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder responseTypes(Consumer<List<String>> responseTypesConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, responseTypesConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this Grant Type to the collection of {@code grant_types_supported} in the resulting
|
|
||||||
* {@link OidcProviderConfiguration}, OPTIONAL.
|
|
||||||
*
|
|
||||||
* @param grantType the OAuth 2.0 {@code grant_type} value that the OpenID Provider supports
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder grantType(String grantType) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, grantType);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the Grant Type(s) allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param grantTypesConsumer a {@code Consumer} of the Grant Type(s)
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder grantTypes(Consumer<List<String>> grantTypesConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, grantTypesConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this Subject Type to the collection of {@code subject_types_supported} in the resulting
|
|
||||||
* {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param subjectType the Subject Type that the OpenID Provider supports
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder subjectType(String subjectType) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, subjectType);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the Subject Types(s) allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param subjectTypesConsumer a {@code Consumer} of the Subject Types(s)
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder subjectTypes(Consumer<List<String>> subjectTypesConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, subjectTypesConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this Scope to the collection of {@code scopes_supported} in the resulting
|
|
||||||
* {@link OidcProviderConfiguration}, RECOMMENDED.
|
|
||||||
*
|
|
||||||
* @param scope the OAuth 2.0 {@code scope} value that the OpenID Provider supports
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder scope(String scope) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, scope);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the Scopes(s) allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param scopesConsumer a {@code Consumer} of the Scopes(s)
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder scopes(Consumer<List<String>> scopesConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, scopesConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add this {@link JwsAlgorithm JWS} signing algorithm to the collection of {@code id_token_signing_alg_values_supported}
|
|
||||||
* in the resulting {@link OidcProviderConfiguration}, REQUIRED.
|
|
||||||
*
|
|
||||||
* @param signingAlgorithm the {@link JwsAlgorithm JWS} signing algorithm supported for the {@link OidcIdToken ID Token}
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder idTokenSigningAlgorithm(String signingAlgorithm) {
|
|
||||||
addClaimToClaimList(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED, signingAlgorithm);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@code Consumer} of the {@link JwsAlgorithm JWS} signing algorithms for the {@link OidcIdToken ID Token}
|
|
||||||
* allowing the ability to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param signingAlgorithmsConsumer a {@code Consumer} of the {@link JwsAlgorithm JWS} signing algorithms for the {@link OidcIdToken ID Token}
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder idTokenSigningAlgorithms(Consumer<List<String>> signingAlgorithmsConsumer) {
|
|
||||||
acceptClaimValues(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED, signingAlgorithmsConsumer);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use this claim in the resulting {@link OidcProviderConfiguration}.
|
|
||||||
*
|
|
||||||
* @param name the claim name
|
|
||||||
* @param value the claim value
|
|
||||||
* @return the {@link Builder} for further configuration
|
|
||||||
*/
|
|
||||||
public Builder claim(String name, Object value) {
|
|
||||||
Assert.hasText(name, "name cannot be empty");
|
|
||||||
Assert.notNull(value, "value cannot be null");
|
|
||||||
this.claims.put(name, value);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Provides access to every {@link #claim(String, Object)} declared so far with
|
|
||||||
* the possibility to add, replace, or remove.
|
|
||||||
*
|
|
||||||
* @param claimsConsumer a {@code Consumer} of the claims
|
|
||||||
* @return the {@link Builder} for further configurations
|
|
||||||
*/
|
|
||||||
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
|
|
||||||
claimsConsumer.accept(this.claims);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the claims and build the {@link OidcProviderConfiguration}.
|
|
||||||
* <p>
|
|
||||||
* The following claims are REQUIRED:
|
|
||||||
* {@code issuer}, {@code authorization_endpoint}, {@code token_endpoint}, {@code jwks_uri},
|
|
||||||
* {@code response_types_supported} and {@code subject_types_supported}.
|
|
||||||
*
|
|
||||||
* @return the {@link OidcProviderConfiguration}
|
|
||||||
*/
|
|
||||||
public OidcProviderConfiguration build() {
|
|
||||||
validateClaims();
|
|
||||||
return new OidcProviderConfiguration(this.claims);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void validateClaims() {
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.ISSUER), "issuer cannot be null");
|
|
||||||
validateURL(this.claims.get(OidcProviderMetadataClaimNames.ISSUER), "issuer must be a valid URL");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT), "authorizationEndpoint cannot be null");
|
|
||||||
validateURL(this.claims.get(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT), "authorizationEndpoint must be a valid URL");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT), "tokenEndpoint cannot be null");
|
|
||||||
validateURL(this.claims.get(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT), "tokenEndpoint must be a valid URL");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.JWKS_URI), "jwksUri cannot be null");
|
|
||||||
validateURL(this.claims.get(OidcProviderMetadataClaimNames.JWKS_URI), "jwksUri must be a valid URL");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes cannot be null");
|
|
||||||
Assert.isInstanceOf(List.class, this.claims.get(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes must be of type List");
|
|
||||||
Assert.notEmpty((List<?>) this.claims.get(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes cannot be empty");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes cannot be null");
|
|
||||||
Assert.isInstanceOf(List.class, this.claims.get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes must be of type List");
|
|
||||||
Assert.notEmpty((List<?>) this.claims.get(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED), "subjectTypes cannot be empty");
|
|
||||||
Assert.notNull(this.claims.get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms cannot be null");
|
|
||||||
Assert.isInstanceOf(List.class, this.claims.get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms must be of type List");
|
|
||||||
Assert.notEmpty((List<?>) this.claims.get(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED), "idTokenSigningAlgorithms cannot be empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void validateURL(Object url, String errorMessage) {
|
|
||||||
if (URL.class.isAssignableFrom(url.getClass())) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
new URI(url.toString()).toURL();
|
|
||||||
} catch (Exception ex) {
|
|
||||||
throw new IllegalArgumentException(errorMessage, ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private void addClaimToClaimList(String name, String value) {
|
|
||||||
Assert.hasText(name, "name cannot be empty");
|
|
||||||
Assert.notNull(value, "value cannot be null");
|
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
|
||||||
((List<String>) this.claims.get(name)).add(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
|
||||||
Assert.hasText(name, "name cannot be empty");
|
|
||||||
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
|
||||||
List<String> values = (List<String>) this.claims.get(name);
|
|
||||||
valuesConsumer.accept(values);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,130 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.oidc;
|
|
||||||
|
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.ClaimAccessor;
|
|
||||||
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
|
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
|
||||||
|
|
||||||
import java.net.URL;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@link ClaimAccessor} for the "claims" that can be returned
|
|
||||||
* in the OpenID Provider Configuration Response.
|
|
||||||
*
|
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see ClaimAccessor
|
|
||||||
* @see OidcProviderMetadataClaimNames
|
|
||||||
* @see OidcProviderConfiguration
|
|
||||||
* @see <a target="_blank" href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata">3. OpenID Provider Metadata</a>
|
|
||||||
*/
|
|
||||||
public interface OidcProviderMetadataClaimAccessor extends ClaimAccessor {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@code URL} the OpenID Provider asserts as its Issuer Identifier {@code (issuer)}.
|
|
||||||
*
|
|
||||||
* @return the {@code URL} the OpenID Provider asserts as its Issuer Identifier
|
|
||||||
*/
|
|
||||||
default URL getIssuer() {
|
|
||||||
return getClaimAsURL(OidcProviderMetadataClaimNames.ISSUER);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@code URL} of the OAuth 2.0 Authorization Endpoint {@code (authorization_endpoint)}.
|
|
||||||
*
|
|
||||||
* @return the {@code URL} of the OAuth 2.0 Authorization Endpoint
|
|
||||||
*/
|
|
||||||
default URL getAuthorizationEndpoint() {
|
|
||||||
return getClaimAsURL(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@code URL} of the OAuth 2.0 Token Endpoint {@code (token_endpoint)}.
|
|
||||||
*
|
|
||||||
* @return the {@code URL} of the OAuth 2.0 Token Endpoint
|
|
||||||
*/
|
|
||||||
default URL getTokenEndpoint() {
|
|
||||||
return getClaimAsURL(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the client authentication methods supported by the OAuth 2.0 Token Endpoint {@code (token_endpoint_auth_methods_supported)}.
|
|
||||||
*
|
|
||||||
* @return the client authentication methods supported by the OAuth 2.0 Token Endpoint
|
|
||||||
*/
|
|
||||||
default List<String> getTokenEndpointAuthenticationMethods() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@code URL} of the JSON Web Key Set {@code (jwks_uri)}.
|
|
||||||
*
|
|
||||||
* @return the {@code URL} of the JSON Web Key Set
|
|
||||||
*/
|
|
||||||
default URL getJwkSetUri() {
|
|
||||||
return getClaimAsURL(OidcProviderMetadataClaimNames.JWKS_URI);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the OAuth 2.0 {@code response_type} values supported {@code (response_types_supported)}.
|
|
||||||
*
|
|
||||||
* @return the OAuth 2.0 {@code response_type} values supported
|
|
||||||
*/
|
|
||||||
default List<String> getResponseTypes() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the OAuth 2.0 {@code grant_type} values supported {@code (grant_types_supported)}.
|
|
||||||
*
|
|
||||||
* @return the OAuth 2.0 {@code grant_type} values supported
|
|
||||||
*/
|
|
||||||
default List<String> getGrantTypes() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Subject Identifier types supported {@code (subject_types_supported)}.
|
|
||||||
*
|
|
||||||
* @return the Subject Identifier types supported
|
|
||||||
*/
|
|
||||||
default List<String> getSubjectTypes() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the OAuth 2.0 {@code scope} values supported {@code (scopes_supported)}.
|
|
||||||
*
|
|
||||||
* @return the OAuth 2.0 {@code scope} values supported
|
|
||||||
*/
|
|
||||||
default List<String> getScopes() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link JwsAlgorithm JWS} signing algorithms supported for the {@link OidcIdToken ID Token}
|
|
||||||
* to encode the claims in a {@link Jwt} {@code (id_token_signing_alg_values_supported)}.
|
|
||||||
*
|
|
||||||
* @return the {@link JwsAlgorithm JWS} signing algorithms supported for the {@link OidcIdToken ID Token}
|
|
||||||
*/
|
|
||||||
default List<String> getIdTokenSigningAlgorithms() {
|
|
||||||
return getClaimAsStringList(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,80 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.oidc;
|
|
||||||
|
|
||||||
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The names of the "claims" defined by OpenID Connect Discovery 1.0 that can be returned
|
|
||||||
* in the OpenID Provider Configuration Response.
|
|
||||||
*
|
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see <a target="_blank" href="https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata">3. OpenID Provider Metadata</a>
|
|
||||||
*/
|
|
||||||
public interface OidcProviderMetadataClaimNames {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code issuer} - the {@code URL} the OpenID Provider asserts as its Issuer Identifier
|
|
||||||
*/
|
|
||||||
String ISSUER = "issuer";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code authorization_endpoint} - the {@code URL} of the OAuth 2.0 Authorization Endpoint
|
|
||||||
*/
|
|
||||||
String AUTHORIZATION_ENDPOINT = "authorization_endpoint";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code token_endpoint} - the {@code URL} of the OAuth 2.0 Token Endpoint
|
|
||||||
*/
|
|
||||||
String TOKEN_ENDPOINT = "token_endpoint";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code token_endpoint_auth_methods_supported} - the client authentication methods supported by the OAuth 2.0 Token Endpoint
|
|
||||||
*/
|
|
||||||
String TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED = "token_endpoint_auth_methods_supported";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code jwks_uri} - the {@code URL} of the JSON Web Key Set
|
|
||||||
*/
|
|
||||||
String JWKS_URI = "jwks_uri";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code response_types_supported} - the OAuth 2.0 {@code response_type} values supported
|
|
||||||
*/
|
|
||||||
String RESPONSE_TYPES_SUPPORTED = "response_types_supported";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code grant_types_supported} - the OAuth 2.0 {@code grant_type} values supported
|
|
||||||
*/
|
|
||||||
String GRANT_TYPES_SUPPORTED = "grant_types_supported";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code subject_types_supported} - the Subject Identifier types supported
|
|
||||||
*/
|
|
||||||
String SUBJECT_TYPES_SUPPORTED = "subject_types_supported";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code scopes_supported} - the OAuth 2.0 {@code scope} values supported
|
|
||||||
*/
|
|
||||||
String SCOPES_SUPPORTED = "scopes_supported";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@code id_token_signing_alg_values_supported} - the {@link JwsAlgorithm JWS} signing algorithms supported for the {@link OidcIdToken ID Token}
|
|
||||||
*/
|
|
||||||
String ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED = "id_token_signing_alg_values_supported";
|
|
||||||
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2002-2018 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.oidc.http.converter;
|
|
||||||
|
|
||||||
import org.springframework.http.converter.GenericHttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.HttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.json.GsonHttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
|
||||||
import org.springframework.util.ClassUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TODO
|
|
||||||
* This class is a straight copy from Spring Security.
|
|
||||||
* It should be consolidated when merging this codebase into Spring Security.
|
|
||||||
*
|
|
||||||
* Utility methods for {@link HttpMessageConverter}'s.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 5.1
|
|
||||||
*/
|
|
||||||
final class HttpMessageConverters {
|
|
||||||
|
|
||||||
private static final boolean jackson2Present;
|
|
||||||
|
|
||||||
private static final boolean gsonPresent;
|
|
||||||
|
|
||||||
private static final boolean jsonbPresent;
|
|
||||||
|
|
||||||
static {
|
|
||||||
ClassLoader classLoader = HttpMessageConverters.class.getClassLoader();
|
|
||||||
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)
|
|
||||||
&& ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
|
|
||||||
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
|
|
||||||
jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader);
|
|
||||||
}
|
|
||||||
|
|
||||||
private HttpMessageConverters() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static GenericHttpMessageConverter<Object> getJsonMessageConverter() {
|
|
||||||
if (jackson2Present) {
|
|
||||||
return new MappingJackson2HttpMessageConverter();
|
|
||||||
}
|
|
||||||
if (gsonPresent) {
|
|
||||||
return new GsonHttpMessageConverter();
|
|
||||||
}
|
|
||||||
if (jsonbPresent) {
|
|
||||||
return new JsonbHttpMessageConverter();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,161 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.core.oidc.http.converter;
|
|
||||||
|
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
|
||||||
import org.springframework.core.convert.TypeDescriptor;
|
|
||||||
import org.springframework.core.convert.converter.Converter;
|
|
||||||
import org.springframework.http.HttpInputMessage;
|
|
||||||
import org.springframework.http.HttpOutputMessage;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.converter.AbstractHttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.GenericHttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.HttpMessageConverter;
|
|
||||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
|
||||||
import org.springframework.http.converter.HttpMessageNotWritableException;
|
|
||||||
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
|
|
||||||
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
|
|
||||||
import org.springframework.security.oauth2.core.oidc.OidcProviderConfiguration;
|
|
||||||
import org.springframework.security.oauth2.core.oidc.OidcProviderMetadataClaimNames;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import java.net.URL;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A {@link HttpMessageConverter} for an {@link OidcProviderConfiguration OpenID Provider Configuration Response}.
|
|
||||||
*
|
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see AbstractHttpMessageConverter
|
|
||||||
* @see OidcProviderConfiguration
|
|
||||||
*/
|
|
||||||
public class OidcProviderConfigurationHttpMessageConverter
|
|
||||||
extends AbstractHttpMessageConverter<OidcProviderConfiguration> {
|
|
||||||
|
|
||||||
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP =
|
|
||||||
new ParameterizedTypeReference<Map<String, Object>>() {};
|
|
||||||
|
|
||||||
private final GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters.getJsonMessageConverter();
|
|
||||||
|
|
||||||
private Converter<Map<String, Object>, OidcProviderConfiguration> providerConfigurationConverter = new OidcProviderConfigurationConverter();
|
|
||||||
private Converter<OidcProviderConfiguration, Map<String, Object>> providerConfigurationParametersConverter = OidcProviderConfiguration::getClaims;
|
|
||||||
|
|
||||||
public OidcProviderConfigurationHttpMessageConverter() {
|
|
||||||
super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected boolean supports(Class<?> clazz) {
|
|
||||||
return OidcProviderConfiguration.class.isAssignableFrom(clazz);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
protected OidcProviderConfiguration readInternal(Class<? extends OidcProviderConfiguration> clazz, HttpInputMessage inputMessage)
|
|
||||||
throws HttpMessageNotReadableException {
|
|
||||||
try {
|
|
||||||
Map<String, Object> providerConfigurationParameters =
|
|
||||||
(Map<String, Object>) this.jsonMessageConverter.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
|
|
||||||
return this.providerConfigurationConverter.convert(providerConfigurationParameters);
|
|
||||||
} catch (Exception ex) {
|
|
||||||
throw new HttpMessageNotReadableException(
|
|
||||||
"An error occurred reading the OpenID Provider Configuration: " + ex.getMessage(), ex, inputMessage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void writeInternal(OidcProviderConfiguration providerConfiguration, HttpOutputMessage outputMessage)
|
|
||||||
throws HttpMessageNotWritableException {
|
|
||||||
try {
|
|
||||||
Map<String, Object> providerConfigurationResponseParameters =
|
|
||||||
this.providerConfigurationParametersConverter.convert(providerConfiguration);
|
|
||||||
this.jsonMessageConverter.write(
|
|
||||||
providerConfigurationResponseParameters,
|
|
||||||
STRING_OBJECT_MAP.getType(),
|
|
||||||
MediaType.APPLICATION_JSON,
|
|
||||||
outputMessage
|
|
||||||
);
|
|
||||||
} catch (Exception ex) {
|
|
||||||
throw new HttpMessageNotWritableException(
|
|
||||||
"An error occurred writing the OpenID Provider Configuration: " + ex.getMessage(), ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link Converter} used for converting the OpenID Provider Configuration parameters
|
|
||||||
* to an {@link OidcProviderConfiguration}.
|
|
||||||
*
|
|
||||||
* @param providerConfigurationConverter the {@link Converter} used for converting to an
|
|
||||||
* {@link OidcProviderConfiguration}
|
|
||||||
*/
|
|
||||||
public final void setProviderConfigurationConverter(Converter<Map<String, Object>, OidcProviderConfiguration> providerConfigurationConverter) {
|
|
||||||
Assert.notNull(providerConfigurationConverter, "providerConfigurationConverter cannot be null");
|
|
||||||
this.providerConfigurationConverter = providerConfigurationConverter;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link Converter} used for converting the {@link OidcProviderConfiguration} to a
|
|
||||||
* {@code Map} representation of the OpenID Provider Configuration.
|
|
||||||
*
|
|
||||||
* @param providerConfigurationParametersConverter the {@link Converter} used for converting to a
|
|
||||||
* {@code Map} representation of the OpenID Provider Configuration
|
|
||||||
*/
|
|
||||||
public final void setProviderConfigurationParametersConverter(
|
|
||||||
Converter<OidcProviderConfiguration, Map<String, Object>> providerConfigurationParametersConverter) {
|
|
||||||
Assert.notNull(providerConfigurationParametersConverter, "providerConfigurationParametersConverter cannot be null");
|
|
||||||
this.providerConfigurationParametersConverter = providerConfigurationParametersConverter;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class OidcProviderConfigurationConverter implements Converter<Map<String, Object>, OidcProviderConfiguration> {
|
|
||||||
private static final ClaimConversionService CLAIM_CONVERSION_SERVICE = ClaimConversionService.getSharedInstance();
|
|
||||||
private static final TypeDescriptor OBJECT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);
|
|
||||||
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
|
|
||||||
private static final TypeDescriptor URL_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(URL.class);
|
|
||||||
private final ClaimTypeConverter claimTypeConverter;
|
|
||||||
|
|
||||||
private OidcProviderConfigurationConverter() {
|
|
||||||
Converter<Object, ?> collectionStringConverter = getConverter(
|
|
||||||
TypeDescriptor.collection(Collection.class, STRING_TYPE_DESCRIPTOR));
|
|
||||||
Converter<Object, ?> urlConverter = getConverter(URL_TYPE_DESCRIPTOR);
|
|
||||||
|
|
||||||
Map<String, Converter<Object, ?>> claimConverters = new HashMap<>();
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.ISSUER, urlConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.AUTHORIZATION_ENDPOINT, urlConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT, urlConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED, collectionStringConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.JWKS_URI, urlConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED, collectionStringConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.GRANT_TYPES_SUPPORTED, collectionStringConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED, collectionStringConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED, collectionStringConverter);
|
|
||||||
claimConverters.put(OidcProviderMetadataClaimNames.SCOPES_SUPPORTED, collectionStringConverter);
|
|
||||||
this.claimTypeConverter = new ClaimTypeConverter(claimConverters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public OidcProviderConfiguration convert(Map<String, Object> source) {
|
|
||||||
Map<String, Object> parsedClaims = this.claimTypeConverter.convert(source);
|
|
||||||
return OidcProviderConfiguration.withClaims(parsedClaims).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
|
||||||
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,19 +13,30 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.jwt;
|
package org.springframework.security.oauth2.jose;
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
|
||||||
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.net.URL;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.ALG;
|
||||||
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.CRIT;
|
||||||
import org.springframework.util.Assert;
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.CTY;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.JKU;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.JWK;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.KID;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.TYP;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.X5C;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.X5T;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.X5T_S256;
|
||||||
|
import static org.springframework.security.oauth2.jose.JoseHeaderNames.X5U;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The JOSE header is a JSON object representing the header parameters of a JSON Web Token,
|
* The JOSE header is a JSON object representing the header parameters of a JSON Web Token,
|
||||||
@ -44,16 +55,16 @@ public final class JoseHeader {
|
|||||||
private final Map<String, Object> headers;
|
private final Map<String, Object> headers;
|
||||||
|
|
||||||
private JoseHeader(Map<String, Object> headers) {
|
private JoseHeader(Map<String, Object> headers) {
|
||||||
this.headers = Collections.unmodifiableMap(new HashMap<>(headers));
|
this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the {@link JwsAlgorithm JWS algorithm} used to digitally sign the JWS.
|
* Returns the JWS algorithm used to digitally sign the JWS.
|
||||||
*
|
*
|
||||||
* @return the JWS algorithm
|
* @return the JWS algorithm
|
||||||
*/
|
*/
|
||||||
public JwsAlgorithm getJwsAlgorithm() {
|
public JwsAlgorithm getJwsAlgorithm() {
|
||||||
return getHeader(JoseHeaderNames.ALG);
|
return getHeader(ALG);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -62,8 +73,8 @@ public final class JoseHeader {
|
|||||||
*
|
*
|
||||||
* @return the JWK Set URL
|
* @return the JWK Set URL
|
||||||
*/
|
*/
|
||||||
public URL getJwkSetUri() {
|
public String getJwkSetUri() {
|
||||||
return getHeader(JoseHeaderNames.JKU);
|
return getHeader(JKU);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -73,7 +84,7 @@ public final class JoseHeader {
|
|||||||
* @return the JSON Web Key
|
* @return the JSON Web Key
|
||||||
*/
|
*/
|
||||||
public Map<String, Object> getJwk() {
|
public Map<String, Object> getJwk() {
|
||||||
return getHeader(JoseHeaderNames.JWK);
|
return getHeader(JWK);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -82,7 +93,7 @@ public final class JoseHeader {
|
|||||||
* @return the key ID
|
* @return the key ID
|
||||||
*/
|
*/
|
||||||
public String getKeyId() {
|
public String getKeyId() {
|
||||||
return getHeader(JoseHeaderNames.KID);
|
return getHeader(KID);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -91,8 +102,8 @@ public final class JoseHeader {
|
|||||||
*
|
*
|
||||||
* @return the X.509 URL
|
* @return the X.509 URL
|
||||||
*/
|
*/
|
||||||
public URL getX509Uri() {
|
public String getX509Uri() {
|
||||||
return getHeader(JoseHeaderNames.X5U);
|
return getHeader(X5U);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -102,7 +113,7 @@ public final class JoseHeader {
|
|||||||
* @return the X.509 certificate chain
|
* @return the X.509 certificate chain
|
||||||
*/
|
*/
|
||||||
public List<String> getX509CertificateChain() {
|
public List<String> getX509CertificateChain() {
|
||||||
return getHeader(JoseHeaderNames.X5C);
|
return getHeader(X5C);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -112,7 +123,7 @@ public final class JoseHeader {
|
|||||||
* @return the X.509 certificate SHA-1 thumbprint
|
* @return the X.509 certificate SHA-1 thumbprint
|
||||||
*/
|
*/
|
||||||
public String getX509SHA1Thumbprint() {
|
public String getX509SHA1Thumbprint() {
|
||||||
return getHeader(JoseHeaderNames.X5T);
|
return getHeader(X5T);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -122,7 +133,7 @@ public final class JoseHeader {
|
|||||||
* @return the X.509 certificate SHA-256 thumbprint
|
* @return the X.509 certificate SHA-256 thumbprint
|
||||||
*/
|
*/
|
||||||
public String getX509SHA256Thumbprint() {
|
public String getX509SHA256Thumbprint() {
|
||||||
return getHeader(JoseHeaderNames.X5T_S256);
|
return getHeader(X5T_S256);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -132,7 +143,7 @@ public final class JoseHeader {
|
|||||||
* @return the critical headers
|
* @return the critical headers
|
||||||
*/
|
*/
|
||||||
public Set<String> getCritical() {
|
public Set<String> getCritical() {
|
||||||
return getHeader(JoseHeaderNames.CRIT);
|
return getHeader(CRIT);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -141,7 +152,7 @@ public final class JoseHeader {
|
|||||||
* @return the type header
|
* @return the type header
|
||||||
*/
|
*/
|
||||||
public String getType() {
|
public String getType() {
|
||||||
return getHeader(JoseHeaderNames.TYP);
|
return getHeader(TYP);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -150,7 +161,7 @@ public final class JoseHeader {
|
|||||||
* @return the content type header
|
* @return the content type header
|
||||||
*/
|
*/
|
||||||
public String getContentType() {
|
public String getContentType() {
|
||||||
return getHeader(JoseHeaderNames.CTY);
|
return getHeader(CTY);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -175,15 +186,6 @@ public final class JoseHeader {
|
|||||||
return (T) getHeaders().get(name);
|
return (T) getHeaders().get(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a new {@link Builder}.
|
|
||||||
*
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public static Builder builder() {
|
|
||||||
return new Builder();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a new {@link Builder}, initialized with the provided {@link JwsAlgorithm}.
|
* Returns a new {@link Builder}, initialized with the provided {@link JwsAlgorithm}.
|
||||||
*
|
*
|
||||||
@ -207,15 +209,12 @@ public final class JoseHeader {
|
|||||||
/**
|
/**
|
||||||
* A builder for {@link JoseHeader}.
|
* A builder for {@link JoseHeader}.
|
||||||
*/
|
*/
|
||||||
public static final class Builder {
|
public static class Builder {
|
||||||
private final Map<String, Object> headers = new HashMap<>();
|
private final Map<String, Object> headers = new LinkedHashMap<>();
|
||||||
|
|
||||||
private Builder() {
|
|
||||||
}
|
|
||||||
|
|
||||||
private Builder(JwsAlgorithm jwsAlgorithm) {
|
private Builder(JwsAlgorithm jwsAlgorithm) {
|
||||||
Assert.notNull(jwsAlgorithm, "jwsAlgorithm cannot be null");
|
Assert.notNull(jwsAlgorithm, "jwsAlgorithm cannot be null");
|
||||||
header(JoseHeaderNames.ALG, jwsAlgorithm);
|
header(ALG, jwsAlgorithm);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Builder(JoseHeader headers) {
|
private Builder(JoseHeader headers) {
|
||||||
@ -223,16 +222,6 @@ public final class JoseHeader {
|
|||||||
this.headers.putAll(headers.getHeaders());
|
this.headers.putAll(headers.getHeaders());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link JwsAlgorithm JWS algorithm} used to digitally sign the JWS.
|
|
||||||
*
|
|
||||||
* @param jwsAlgorithm the JWS algorithm
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public Builder jwsAlgorithm(JwsAlgorithm jwsAlgorithm) {
|
|
||||||
return header(JoseHeaderNames.ALG, jwsAlgorithm);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the JWK Set URL that refers to the resource of a set of JSON-encoded public keys,
|
* Sets the JWK Set URL that refers to the resource of a set of JSON-encoded public keys,
|
||||||
* one of which corresponds to the key used to digitally sign the JWS or encrypt the JWE.
|
* one of which corresponds to the key used to digitally sign the JWS or encrypt the JWE.
|
||||||
@ -241,7 +230,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder jwkSetUri(String jwkSetUri) {
|
public Builder jwkSetUri(String jwkSetUri) {
|
||||||
return header(JoseHeaderNames.JKU, jwkSetUri);
|
return header(JKU, jwkSetUri);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -252,7 +241,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder jwk(Map<String, Object> jwk) {
|
public Builder jwk(Map<String, Object> jwk) {
|
||||||
return header(JoseHeaderNames.JWK, jwk);
|
return header(JWK, jwk);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -262,7 +251,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder keyId(String keyId) {
|
public Builder keyId(String keyId) {
|
||||||
return header(JoseHeaderNames.KID, keyId);
|
return header(KID, keyId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -273,7 +262,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder x509Uri(String x509Uri) {
|
public Builder x509Uri(String x509Uri) {
|
||||||
return header(JoseHeaderNames.X5U, x509Uri);
|
return header(X5U, x509Uri);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -284,7 +273,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder x509CertificateChain(List<String> x509CertificateChain) {
|
public Builder x509CertificateChain(List<String> x509CertificateChain) {
|
||||||
return header(JoseHeaderNames.X5C, x509CertificateChain);
|
return header(X5C, x509CertificateChain);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -295,7 +284,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder x509SHA1Thumbprint(String x509SHA1Thumbprint) {
|
public Builder x509SHA1Thumbprint(String x509SHA1Thumbprint) {
|
||||||
return header(JoseHeaderNames.X5T, x509SHA1Thumbprint);
|
return header(X5T, x509SHA1Thumbprint);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -306,7 +295,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder x509SHA256Thumbprint(String x509SHA256Thumbprint) {
|
public Builder x509SHA256Thumbprint(String x509SHA256Thumbprint) {
|
||||||
return header(JoseHeaderNames.X5T_S256, x509SHA256Thumbprint);
|
return header(X5T_S256, x509SHA256Thumbprint);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -317,7 +306,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder critical(Set<String> headerNames) {
|
public Builder critical(Set<String> headerNames) {
|
||||||
return header(JoseHeaderNames.CRIT, headerNames);
|
return header(CRIT, headerNames);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -327,7 +316,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder type(String type) {
|
public Builder type(String type) {
|
||||||
return header(JoseHeaderNames.TYP, type);
|
return header(TYP, type);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -337,7 +326,7 @@ public final class JoseHeader {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder contentType(String contentType) {
|
public Builder contentType(String contentType) {
|
||||||
return header(JoseHeaderNames.CTY, contentType);
|
return header(CTY, contentType);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -373,19 +362,7 @@ public final class JoseHeader {
|
|||||||
*/
|
*/
|
||||||
public JoseHeader build() {
|
public JoseHeader build() {
|
||||||
Assert.notEmpty(this.headers, "headers cannot be empty");
|
Assert.notEmpty(this.headers, "headers cannot be empty");
|
||||||
convertAsURL(JoseHeaderNames.JKU);
|
|
||||||
convertAsURL(JoseHeaderNames.X5U);
|
|
||||||
return new JoseHeader(this.headers);
|
return new JoseHeader(this.headers);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void convertAsURL(String header) {
|
|
||||||
Object value = this.headers.get(header);
|
|
||||||
if (value != null) {
|
|
||||||
URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class);
|
|
||||||
Assert.isTrue(convertedValue != null,
|
|
||||||
() -> "Unable to convert header '" + header + "' of type '" + value.getClass() + "' to URL.");
|
|
||||||
this.headers.put(header, convertedValue);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,7 +13,7 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.jwt;
|
package org.springframework.security.oauth2.jose;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Registered Header Parameter Names defined by the JSON Web Token (JWT),
|
* The Registered Header Parameter Names defined by the JSON Web Token (JWT),
|
||||||
@ -28,72 +28,69 @@ package org.springframework.security.oauth2.jwt;
|
|||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JWS JOSE Header</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JWS JOSE Header</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-4">JWE JOSE Header</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-4">JWE JOSE Header</a>
|
||||||
*/
|
*/
|
||||||
public final class JoseHeaderNames {
|
public interface JoseHeaderNames {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code alg} - the algorithm header identifies the cryptographic algorithm used to secure a JWS or JWE
|
* {@code alg} - the algorithm header identifies the cryptographic algorithm used to secure a JWS or JWE
|
||||||
*/
|
*/
|
||||||
public static final String ALG = "alg";
|
String ALG = "alg";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code jku} - the JWK Set URL header is a URI that refers to a resource for a set of JSON-encoded public keys,
|
* {@code jku} - the JWK Set URL header is a URI that refers to a resource for a set of JSON-encoded public keys,
|
||||||
* one of which corresponds to the key used to digitally sign a JWS or encrypt a JWE
|
* one of which corresponds to the key used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String JKU = "jku";
|
String JKU = "jku";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code jwk} - the JSON Web Key header is the public key that corresponds to the key
|
* {@code jwk} - the JSON Web Key header is the public key that corresponds to the key
|
||||||
* used to digitally sign a JWS or encrypt a JWE
|
* used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String JWK = "jwk";
|
String JWK = "jwk";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code kid} - the key ID header is a hint indicating which key was used to secure a JWS or JWE
|
* {@code kid} - the key ID header is a hint indicating which key was used to secure a JWS or JWE
|
||||||
*/
|
*/
|
||||||
public static final String KID = "kid";
|
String KID = "kid";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code x5u} - the X.509 URL header is a URI that refers to a resource for the X.509 public key certificate
|
* {@code x5u} - the X.509 URL header is a URI that refers to a resource for the X.509 public key certificate
|
||||||
* or certificate chain corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
* or certificate chain corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String X5U = "x5u";
|
String X5U = "x5u";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code x5c} - the X.509 certificate chain header contains the X.509 public key certificate
|
* {@code x5c} - the X.509 certificate chain header contains the X.509 public key certificate
|
||||||
* or certificate chain corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
* or certificate chain corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String X5C = "x5c";
|
String X5C = "x5c";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code x5t} - the X.509 certificate SHA-1 thumbprint header is a base64url-encoded SHA-1 thumbprint (a.k.a. digest)
|
* {@code x5t} - the X.509 certificate SHA-1 thumbprint header is a base64url-encoded SHA-1 thumbprint (a.k.a. digest)
|
||||||
* of the DER encoding of the X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
* of the DER encoding of the X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String X5T = "x5t";
|
String X5T = "x5t";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code x5t#S256} - the X.509 certificate SHA-256 thumbprint header is a base64url-encoded SHA-256 thumbprint (a.k.a. digest)
|
* {@code x5t#S256} - the X.509 certificate SHA-256 thumbprint header is a base64url-encoded SHA-256 thumbprint (a.k.a. digest)
|
||||||
* of the DER encoding of the X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
* of the DER encoding of the X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt a JWE
|
||||||
*/
|
*/
|
||||||
public static final String X5T_S256 = "x5t#S256";
|
String X5T_S256 = "x5t#S256";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code typ} - the type header is used by JWS/JWE applications to declare the media type of a JWS/JWE
|
* {@code typ} - the type header is used by JWS/JWE applications to declare the media type of a JWS/JWE
|
||||||
*/
|
*/
|
||||||
public static final String TYP = "typ";
|
String TYP = "typ";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code cty} - the content type header is used by JWS/JWE applications to declare the media type
|
* {@code cty} - the content type header is used by JWS/JWE applications to declare the media type
|
||||||
* of the secured content (the payload)
|
* of the secured content (the payload)
|
||||||
*/
|
*/
|
||||||
public static final String CTY = "cty";
|
String CTY = "cty";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code crit} - the critical header indicates that extensions to the JWS/JWE/JWA specifications
|
* {@code crit} - the critical header indicates that extensions to the JWS/JWE/JWA specifications
|
||||||
* are being used that MUST be understood and processed
|
* are being used that MUST be understood and processed
|
||||||
*/
|
*/
|
||||||
public static final String CRIT = "crit";
|
String CRIT = "crit";
|
||||||
|
|
||||||
private JoseHeaderNames() {
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,47 +13,52 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.jwt;
|
package org.springframework.security.oauth2.jose.jws;
|
||||||
|
|
||||||
import java.net.URL;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import com.nimbusds.jose.JOSEException;
|
import com.nimbusds.jose.JOSEException;
|
||||||
import com.nimbusds.jose.JOSEObjectType;
|
import com.nimbusds.jose.JOSEObjectType;
|
||||||
import com.nimbusds.jose.JWSAlgorithm;
|
import com.nimbusds.jose.JWSAlgorithm;
|
||||||
import com.nimbusds.jose.JWSHeader;
|
import com.nimbusds.jose.JWSHeader;
|
||||||
import com.nimbusds.jose.JWSSigner;
|
import com.nimbusds.jose.JWSSigner;
|
||||||
import com.nimbusds.jose.KeySourceException;
|
import com.nimbusds.jose.KeyLengthException;
|
||||||
import com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory;
|
import com.nimbusds.jose.crypto.MACSigner;
|
||||||
|
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||||
import com.nimbusds.jose.jwk.JWK;
|
import com.nimbusds.jose.jwk.JWK;
|
||||||
import com.nimbusds.jose.jwk.JWKMatcher;
|
|
||||||
import com.nimbusds.jose.jwk.JWKSelector;
|
|
||||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
|
||||||
import com.nimbusds.jose.proc.SecurityContext;
|
|
||||||
import com.nimbusds.jose.produce.JWSSignerFactory;
|
|
||||||
import com.nimbusds.jose.util.Base64;
|
import com.nimbusds.jose.util.Base64;
|
||||||
import com.nimbusds.jose.util.Base64URL;
|
import com.nimbusds.jose.util.Base64URL;
|
||||||
import com.nimbusds.jwt.JWTClaimsSet;
|
import com.nimbusds.jwt.JWTClaimsSet;
|
||||||
import com.nimbusds.jwt.SignedJWT;
|
import com.nimbusds.jwt.SignedJWT;
|
||||||
|
|
||||||
import net.minidev.json.JSONObject;
|
|
||||||
import org.springframework.core.convert.converter.Converter;
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
import org.springframework.security.crypto.keys.KeyManager;
|
||||||
|
import org.springframework.security.crypto.keys.ManagedKey;
|
||||||
|
import org.springframework.security.oauth2.jose.JoseHeader;
|
||||||
|
import org.springframework.security.oauth2.jose.JoseHeaderNames;
|
||||||
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||||
|
import org.springframework.security.oauth2.jwt.JwtEncodingException;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.security.PrivateKey;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An implementation of a {@link JwtEncoder} that encodes a JSON Web Token (JWT) using the
|
* An implementation of a {@link JwtEncoder} that encodes a JSON Web Token (JWT)
|
||||||
* JSON Web Signature (JWS) Compact Serialization format. The private/secret key used for
|
* using the JSON Web Signature (JWS) Compact Serialization format.
|
||||||
* signing the JWS is supplied by the {@code com.nimbusds.jose.jwk.source.JWKSource}
|
* The private/secret key used for signing the JWS is obtained
|
||||||
* provided via the constructor.
|
* from the {@link KeyManager} supplied via the constructor.
|
||||||
*
|
*
|
||||||
* <p>
|
* <p>
|
||||||
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK.
|
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK.
|
||||||
@ -61,38 +66,42 @@ import org.springframework.util.StringUtils;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see JwtEncoder
|
* @see JwtEncoder
|
||||||
* @see com.nimbusds.jose.jwk.source.JWKSource
|
* @see KeyManager
|
||||||
* @see com.nimbusds.jose.jwk.JWK
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token (JWT)</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature (JWS)</a>
|
||||||
* (JWT)</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS Compact Serialization</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
|
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus JOSE + JWT SDK</a>
|
||||||
* (JWS)</a>
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS
|
|
||||||
* Compact Serialization</a>
|
|
||||||
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus
|
|
||||||
* JOSE + JWT SDK</a>
|
|
||||||
*/
|
*/
|
||||||
public final class NimbusJwsEncoder implements JwtEncoder {
|
public final class NimbusJwsEncoder implements JwtEncoder {
|
||||||
|
private static final String ENCODING_ERROR_MESSAGE_TEMPLATE =
|
||||||
private static final String ENCODING_ERROR_MESSAGE_TEMPLATE = "An error occurred while attempting to encode the Jwt: %s";
|
"An error occurred while attempting to encode the Jwt: %s";
|
||||||
|
private static final String RSA_KEY_TYPE = "RSA";
|
||||||
private static final Converter<JoseHeader, JWSHeader> JWS_HEADER_CONVERTER = new JwsHeaderConverter();
|
private static final String EC_KEY_TYPE = "EC";
|
||||||
|
private static final Map<JwsAlgorithm, String> jcaKeyAlgorithmMappings = new HashMap<JwsAlgorithm, String>() {
|
||||||
private static final Converter<JwtClaimsSet, JWTClaimsSet> JWT_CLAIMS_SET_CONVERTER = new JwtClaimsSetConverter();
|
{
|
||||||
|
put(MacAlgorithm.HS256, "HmacSHA256");
|
||||||
private static final JWSSignerFactory JWS_SIGNER_FACTORY = new DefaultJWSSignerFactory();
|
put(MacAlgorithm.HS384, "HmacSHA384");
|
||||||
|
put(MacAlgorithm.HS512, "HmacSHA512");
|
||||||
private final Map<JWK, JWSSigner> jwsSigners = new ConcurrentHashMap<>();
|
put(SignatureAlgorithm.RS256, RSA_KEY_TYPE);
|
||||||
|
put(SignatureAlgorithm.RS384, RSA_KEY_TYPE);
|
||||||
private final JWKSource<SecurityContext> jwkSource;
|
put(SignatureAlgorithm.RS512, RSA_KEY_TYPE);
|
||||||
|
put(SignatureAlgorithm.ES256, EC_KEY_TYPE);
|
||||||
|
put(SignatureAlgorithm.ES384, EC_KEY_TYPE);
|
||||||
|
put(SignatureAlgorithm.ES512, EC_KEY_TYPE);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
private static final Converter<JoseHeader, JWSHeader> jwsHeaderConverter = new JwsHeaderConverter();
|
||||||
|
private static final Converter<JwtClaimsSet, JWTClaimsSet> jwtClaimsSetConverter = new JwtClaimsSetConverter();
|
||||||
|
private final KeyManager keyManager;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a {@code NimbusJwsEncoder} using the provided parameters.
|
* Constructs a {@code NimbusJwsEncoder} using the provided parameters.
|
||||||
* @param jwkSource the {@code com.nimbusds.jose.jwk.source.JWKSource}
|
*
|
||||||
|
* @param keyManager the key manager
|
||||||
*/
|
*/
|
||||||
public NimbusJwsEncoder(JWKSource<SecurityContext> jwkSource) {
|
public NimbusJwsEncoder(KeyManager keyManager) {
|
||||||
Assert.notNull(jwkSource, "jwkSource cannot be null");
|
Assert.notNull(keyManager, "keyManager cannot be null");
|
||||||
this.jwkSource = jwkSource;
|
this.keyManager = keyManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -100,79 +109,84 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
Assert.notNull(headers, "headers cannot be null");
|
Assert.notNull(headers, "headers cannot be null");
|
||||||
Assert.notNull(claims, "claims cannot be null");
|
Assert.notNull(claims, "claims cannot be null");
|
||||||
|
|
||||||
JWK jwk = selectJwk(headers);
|
ManagedKey managedKey = selectKey(headers);
|
||||||
if (jwk == null) {
|
if (managedKey == null) {
|
||||||
throw new JwtEncodingException(
|
throw new JwtEncodingException(String.format(
|
||||||
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
|
ENCODING_ERROR_MESSAGE_TEMPLATE,
|
||||||
}
|
"Unsupported key for algorithm '" + headers.getJwsAlgorithm().getName() + "'"));
|
||||||
else if (!StringUtils.hasText(jwk.getKeyID())) {
|
}
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
|
||||||
"The \"kid\" (key ID) from the selected JWK cannot be empty"));
|
JWSSigner jwsSigner;
|
||||||
|
if (managedKey.isAsymmetric()) {
|
||||||
|
if (!managedKey.getAlgorithm().equals(RSA_KEY_TYPE)) {
|
||||||
|
throw new JwtEncodingException(String.format(
|
||||||
|
ENCODING_ERROR_MESSAGE_TEMPLATE,
|
||||||
|
"Unsupported key type '" + managedKey.getAlgorithm() + "'"));
|
||||||
|
}
|
||||||
|
PrivateKey privateKey = managedKey.getKey();
|
||||||
|
jwsSigner = new RSASSASigner(privateKey);
|
||||||
|
} else {
|
||||||
|
SecretKey secretKey = managedKey.getKey();
|
||||||
|
try {
|
||||||
|
jwsSigner = new MACSigner(secretKey);
|
||||||
|
} catch (KeyLengthException ex) {
|
||||||
|
throw new JwtEncodingException(String.format(
|
||||||
|
ENCODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
headers = JoseHeader.from(headers)
|
headers = JoseHeader.from(headers)
|
||||||
.type(JOSEObjectType.JWT.getType())
|
.type(JOSEObjectType.JWT.getType())
|
||||||
.keyId(jwk.getKeyID())
|
.keyId(managedKey.getKeyId())
|
||||||
.build();
|
.build();
|
||||||
|
JWSHeader jwsHeader = jwsHeaderConverter.convert(headers);
|
||||||
|
|
||||||
claims = JwtClaimsSet.from(claims)
|
claims = JwtClaimsSet.from(claims)
|
||||||
.id(UUID.randomUUID().toString())
|
.id(UUID.randomUUID().toString())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
JWTClaimsSet jwtClaimsSet = jwtClaimsSetConverter.convert(claims);
|
||||||
|
|
||||||
JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers);
|
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet);
|
||||||
JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
|
|
||||||
|
|
||||||
JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> {
|
|
||||||
try {
|
try {
|
||||||
return JWS_SIGNER_FACTORY.createJWSSigner(key);
|
signedJWT.sign(jwsSigner);
|
||||||
|
} catch (JOSEException ex) {
|
||||||
|
throw new JwtEncodingException(String.format(
|
||||||
|
ENCODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
|
||||||
}
|
}
|
||||||
catch (JOSEException ex) {
|
String jws = signedJWT.serialize();
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
|
||||||
"Failed to create a JWS Signer -> " + ex.getMessage()), ex);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
|
return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(),
|
||||||
try {
|
headers.getHeaders(), claims.getClaims());
|
||||||
signedJwt.sign(jwsSigner);
|
|
||||||
}
|
|
||||||
catch (JOSEException ex) {
|
|
||||||
throw new JwtEncodingException(
|
|
||||||
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
|
|
||||||
}
|
|
||||||
String jws = signedJwt.serialize();
|
|
||||||
|
|
||||||
return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private JWK selectJwk(JoseHeader headers) {
|
private ManagedKey selectKey(JoseHeader headers) {
|
||||||
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(headers.getJwsAlgorithm().getName());
|
JwsAlgorithm jwsAlgorithm = headers.getJwsAlgorithm();
|
||||||
JWSHeader jwsHeader = new JWSHeader(jwsAlgorithm);
|
String keyAlgorithm = jcaKeyAlgorithmMappings.get(jwsAlgorithm);
|
||||||
JWKSelector jwkSelector = new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
|
if (!StringUtils.hasText(keyAlgorithm)) {
|
||||||
|
return null;
|
||||||
List<JWK> jwks;
|
|
||||||
try {
|
|
||||||
jwks = this.jwkSource.get(jwkSelector, null);
|
|
||||||
}
|
|
||||||
catch (KeySourceException ex) {
|
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
|
||||||
"Failed to select a JWK signing key -> " + ex.getMessage()), ex);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (jwks.size() > 1) {
|
Set<ManagedKey> matchingKeys = this.keyManager.findByAlgorithm(keyAlgorithm);
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
if (CollectionUtils.isEmpty(matchingKeys)) {
|
||||||
"Found multiple JWK signing keys for algorithm '" + jwsAlgorithm.getName() + "'"));
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return !jwks.isEmpty() ? jwks.get(0) : null;
|
return matchingKeys.stream()
|
||||||
|
.filter(ManagedKey::isActive)
|
||||||
|
.max(this::mostRecentActivated)
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int mostRecentActivated(ManagedKey managedKey1, ManagedKey managedKey2) {
|
||||||
|
return managedKey1.getActivatedOn().isAfter(managedKey2.getActivatedOn()) ? 1 : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class JwsHeaderConverter implements Converter<JoseHeader, JWSHeader> {
|
private static class JwsHeaderConverter implements Converter<JoseHeader, JWSHeader> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JWSHeader convert(JoseHeader headers) {
|
public JWSHeader convert(JoseHeader headers) {
|
||||||
JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(headers.getJwsAlgorithm().getName()));
|
JWSHeader.Builder builder = new JWSHeader.Builder(
|
||||||
|
JWSAlgorithm.parse(headers.getJwsAlgorithm().getName()));
|
||||||
|
|
||||||
Set<String> critical = headers.getCritical();
|
Set<String> critical = headers.getCritical();
|
||||||
if (!CollectionUtils.isEmpty(critical)) {
|
if (!CollectionUtils.isEmpty(critical)) {
|
||||||
@ -184,24 +198,24 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
builder.contentType(contentType);
|
builder.contentType(contentType);
|
||||||
}
|
}
|
||||||
|
|
||||||
URL jwkSetUri = headers.getJwkSetUri();
|
String jwkSetUri = headers.getJwkSetUri();
|
||||||
if (jwkSetUri != null) {
|
if (StringUtils.hasText(jwkSetUri)) {
|
||||||
try {
|
try {
|
||||||
builder.jwkURL(jwkSetUri.toURI());
|
builder.jwkURL(new URI(jwkSetUri));
|
||||||
}
|
} catch (Exception ex) {
|
||||||
catch (Exception ex) {
|
throw new JwtEncodingException(String.format(
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
ENCODING_ERROR_MESSAGE_TEMPLATE,
|
||||||
"Failed to convert '" + JoseHeaderNames.JKU + "' JOSE header to a URI"), ex);
|
"Failed to convert '" + JoseHeaderNames.JKU + "' JOSE header"), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> jwk = headers.getJwk();
|
Map<String, Object> jwk = headers.getJwk();
|
||||||
if (!CollectionUtils.isEmpty(jwk)) {
|
if (!CollectionUtils.isEmpty(jwk)) {
|
||||||
try {
|
try {
|
||||||
builder.jwk(JWK.parse(new JSONObject(jwk)));
|
builder.jwk(JWK.parse(jwk));
|
||||||
}
|
} catch (Exception ex) {
|
||||||
catch (Exception ex) {
|
throw new JwtEncodingException(String.format(
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
ENCODING_ERROR_MESSAGE_TEMPLATE,
|
||||||
"Failed to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
|
"Failed to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -218,7 +232,10 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
|
|
||||||
List<String> x509CertificateChain = headers.getX509CertificateChain();
|
List<String> x509CertificateChain = headers.getX509CertificateChain();
|
||||||
if (!CollectionUtils.isEmpty(x509CertificateChain)) {
|
if (!CollectionUtils.isEmpty(x509CertificateChain)) {
|
||||||
builder.x509CertChain(x509CertificateChain.stream().map(Base64::new).collect(Collectors.toList()));
|
builder.x509CertChain(
|
||||||
|
x509CertificateChain.stream()
|
||||||
|
.map(Base64::new)
|
||||||
|
.collect(Collectors.toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
|
String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
|
||||||
@ -231,19 +248,19 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
|
builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
|
||||||
}
|
}
|
||||||
|
|
||||||
URL x509Uri = headers.getX509Uri();
|
String x509Uri = headers.getX509Uri();
|
||||||
if (x509Uri != null) {
|
if (StringUtils.hasText(x509Uri)) {
|
||||||
try {
|
try {
|
||||||
builder.x509CertURL(x509Uri.toURI());
|
builder.x509CertURL(new URI(x509Uri));
|
||||||
}
|
} catch (Exception ex) {
|
||||||
catch (Exception ex) {
|
throw new JwtEncodingException(String.format(
|
||||||
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
|
ENCODING_ERROR_MESSAGE_TEMPLATE,
|
||||||
"Failed to convert '" + JoseHeaderNames.X5U + "' JOSE header to a URI"), ex);
|
"Failed to convert '" + JoseHeaderNames.X5U + "' JOSE header"), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> customHeaders = headers.getHeaders().entrySet().stream()
|
Map<String, Object> customHeaders = headers.getHeaders().entrySet().stream()
|
||||||
.filter((header) -> !JWSHeader.getRegisteredParameterNames().contains(header.getKey()))
|
.filter(header -> !JWSHeader.getRegisteredParameterNames().contains(header.getKey()))
|
||||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
if (!CollectionUtils.isEmpty(customHeaders)) {
|
if (!CollectionUtils.isEmpty(customHeaders)) {
|
||||||
builder.customParams(customHeaders);
|
builder.customParams(customHeaders);
|
||||||
@ -251,7 +268,6 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
|
|
||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class JwtClaimsSetConverter implements Converter<JwtClaimsSet, JWTClaimsSet> {
|
private static class JwtClaimsSetConverter implements Converter<JwtClaimsSet, JWTClaimsSet> {
|
||||||
@ -296,7 +312,7 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> customClaims = claims.getClaims().entrySet().stream()
|
Map<String, Object> customClaims = claims.getClaims().entrySet().stream()
|
||||||
.filter((claim) -> !JWTClaimsSet.getRegisteredNames().contains(claim.getKey()))
|
.filter(claim -> !JWTClaimsSet.getRegisteredNames().contains(claim.getKey()))
|
||||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
if (!CollectionUtils.isEmpty(customClaims)) {
|
if (!CollectionUtils.isEmpty(customClaims)) {
|
||||||
customClaims.forEach(builder::claim);
|
customClaims.forEach(builder::claim);
|
||||||
@ -304,7 +320,5 @@ public final class NimbusJwsEncoder implements JwtEncoder {
|
|||||||
|
|
||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,14 +15,23 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.jwt;
|
package org.springframework.security.oauth2.jwt;
|
||||||
|
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import org.springframework.util.Assert;
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.AUD;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.EXP;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.IAT;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.JTI;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.NBF;
|
||||||
|
import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@link Jwt JWT} Claims Set is a JSON object representing the claims conveyed by a JSON Web Token.
|
* The {@link Jwt JWT} Claims Set is a JSON object representing the claims conveyed by a JSON Web Token.
|
||||||
@ -38,7 +47,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
private final Map<String, Object> claims;
|
private final Map<String, Object> claims;
|
||||||
|
|
||||||
private JwtClaimsSet(Map<String, Object> claims) {
|
private JwtClaimsSet(Map<String, Object> claims) {
|
||||||
this.claims = Collections.unmodifiableMap(new HashMap<>(claims));
|
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -51,7 +60,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
*
|
*
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public static Builder builder() {
|
public static Builder withClaims() {
|
||||||
return new Builder();
|
return new Builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,8 +77,8 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
/**
|
/**
|
||||||
* A builder for {@link JwtClaimsSet}.
|
* A builder for {@link JwtClaimsSet}.
|
||||||
*/
|
*/
|
||||||
public static final class Builder {
|
public static class Builder {
|
||||||
private final Map<String, Object> claims = new HashMap<>();
|
private final Map<String, Object> claims = new LinkedHashMap<>();
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
@ -85,8 +94,8 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @param issuer the issuer identifier
|
* @param issuer the issuer identifier
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder issuer(String issuer) {
|
public Builder issuer(URL issuer) {
|
||||||
return claim(JwtClaimNames.ISS, issuer);
|
return claim(ISS, issuer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -96,7 +105,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder subject(String subject) {
|
public Builder subject(String subject) {
|
||||||
return claim(JwtClaimNames.SUB, subject);
|
return claim(SUB, subject);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -106,7 +115,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder audience(List<String> audience) {
|
public Builder audience(List<String> audience) {
|
||||||
return claim(JwtClaimNames.AUD, audience);
|
return claim(AUD, audience);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -117,7 +126,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder expiresAt(Instant expiresAt) {
|
public Builder expiresAt(Instant expiresAt) {
|
||||||
return claim(JwtClaimNames.EXP, expiresAt);
|
return claim(EXP, expiresAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -128,7 +137,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder notBefore(Instant notBefore) {
|
public Builder notBefore(Instant notBefore) {
|
||||||
return claim(JwtClaimNames.NBF, notBefore);
|
return claim(NBF, notBefore);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -138,7 +147,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder issuedAt(Instant issuedAt) {
|
public Builder issuedAt(Instant issuedAt) {
|
||||||
return claim(JwtClaimNames.IAT, issuedAt);
|
return claim(IAT, issuedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -148,7 +157,7 @@ public final class JwtClaimsSet implements JwtClaimAccessor {
|
|||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder id(String jti) {
|
public Builder id(String jti) {
|
||||||
return claim(JwtClaimNames.JTI, jti);
|
return claim(JTI, jti);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,6 +15,8 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.jwt;
|
package org.springframework.security.oauth2.jwt;
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.jose.JoseHeader;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementations of this interface are responsible for encoding
|
* Implementations of this interface are responsible for encoding
|
||||||
* a JSON Web Token (JWT) to it's compact claims representation format.
|
* a JSON Web Token (JWT) to it's compact claims representation format.
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,86 +15,44 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
import org.springframework.lang.Nullable;
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link OAuth2AuthorizationService} that stores {@link OAuth2Authorization}'s in-memory.
|
* An {@link OAuth2AuthorizationService} that stores {@link OAuth2Authorization}'s in-memory.
|
||||||
*
|
*
|
||||||
* <p>
|
|
||||||
* <b>NOTE:</b> This implementation should ONLY be used during development/testing.
|
|
||||||
*
|
|
||||||
* @author Krisztian Toth
|
* @author Krisztian Toth
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2AuthorizationService
|
* @see OAuth2AuthorizationService
|
||||||
*/
|
*/
|
||||||
public final class InMemoryOAuth2AuthorizationService implements OAuth2AuthorizationService {
|
public final class InMemoryOAuth2AuthorizationService implements OAuth2AuthorizationService {
|
||||||
private final Map<String, OAuth2Authorization> authorizations = new ConcurrentHashMap<>();
|
private final Map<OAuth2AuthorizationId, OAuth2Authorization> authorizations = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code InMemoryOAuth2AuthorizationService}.
|
|
||||||
*/
|
|
||||||
public InMemoryOAuth2AuthorizationService() {
|
|
||||||
this(Collections.emptyList());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param authorizations the authorization(s)
|
|
||||||
*/
|
|
||||||
public InMemoryOAuth2AuthorizationService(OAuth2Authorization... authorizations) {
|
|
||||||
this(Arrays.asList(authorizations));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param authorizations the authorization(s)
|
|
||||||
*/
|
|
||||||
public InMemoryOAuth2AuthorizationService(List<OAuth2Authorization> authorizations) {
|
|
||||||
Assert.notNull(authorizations, "authorizations cannot be null");
|
|
||||||
authorizations.forEach(authorization -> {
|
|
||||||
Assert.notNull(authorization, "authorization cannot be null");
|
|
||||||
Assert.isTrue(!this.authorizations.containsKey(authorization.getId()),
|
|
||||||
"The authorization must be unique. Found duplicate identifier: " + authorization.getId());
|
|
||||||
this.authorizations.put(authorization.getId(), authorization);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void save(OAuth2Authorization authorization) {
|
public void save(OAuth2Authorization authorization) {
|
||||||
Assert.notNull(authorization, "authorization cannot be null");
|
Assert.notNull(authorization, "authorization cannot be null");
|
||||||
this.authorizations.put(authorization.getId(), authorization);
|
OAuth2AuthorizationId authorizationId = new OAuth2AuthorizationId(
|
||||||
|
authorization.getRegisteredClientId(), authorization.getPrincipalName());
|
||||||
|
this.authorizations.put(authorizationId, authorization);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void remove(OAuth2Authorization authorization) {
|
public void remove(OAuth2Authorization authorization) {
|
||||||
Assert.notNull(authorization, "authorization cannot be null");
|
Assert.notNull(authorization, "authorization cannot be null");
|
||||||
this.authorizations.remove(authorization.getId(), authorization);
|
OAuth2AuthorizationId authorizationId = new OAuth2AuthorizationId(
|
||||||
|
authorization.getRegisteredClientId(), authorization.getPrincipalName());
|
||||||
|
this.authorizations.remove(authorizationId, authorization);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
@Override
|
@Override
|
||||||
public OAuth2Authorization findById(String id) {
|
public OAuth2Authorization findByToken(String token, @Nullable TokenType tokenType) {
|
||||||
Assert.hasText(id, "id cannot be empty");
|
|
||||||
return this.authorizations.get(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
@Override
|
|
||||||
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
|
|
||||||
Assert.hasText(token, "token cannot be empty");
|
Assert.hasText(token, "token cannot be empty");
|
||||||
return this.authorizations.values().stream()
|
return this.authorizations.values().stream()
|
||||||
.filter(authorization -> hasToken(authorization, token, tokenType))
|
.filter(authorization -> hasToken(authorization, token, tokenType))
|
||||||
@ -102,43 +60,44 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
|
|||||||
.orElse(null);
|
.orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean hasToken(OAuth2Authorization authorization, String token, @Nullable OAuth2TokenType tokenType) {
|
private boolean hasToken(OAuth2Authorization authorization, String token, TokenType tokenType) {
|
||||||
if (tokenType == null) {
|
if (OAuth2AuthorizationAttributeNames.STATE.equals(tokenType.getValue())) {
|
||||||
return matchesState(authorization, token) ||
|
return token.equals(authorization.getAttribute(OAuth2AuthorizationAttributeNames.STATE));
|
||||||
matchesAuthorizationCode(authorization, token) ||
|
} else if (TokenType.AUTHORIZATION_CODE.equals(tokenType)) {
|
||||||
matchesAccessToken(authorization, token) ||
|
return token.equals(authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE));
|
||||||
matchesRefreshToken(authorization, token);
|
} else if (TokenType.ACCESS_TOKEN.equals(tokenType)) {
|
||||||
} else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
|
return authorization.getAccessToken() != null &&
|
||||||
return matchesState(authorization, token);
|
authorization.getAccessToken().getTokenValue().equals(token);
|
||||||
} else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
|
|
||||||
return matchesAuthorizationCode(authorization, token);
|
|
||||||
} else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
|
|
||||||
return matchesAccessToken(authorization, token);
|
|
||||||
} else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
|
|
||||||
return matchesRefreshToken(authorization, token);
|
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean matchesState(OAuth2Authorization authorization, String token) {
|
private static class OAuth2AuthorizationId implements Serializable {
|
||||||
return token.equals(authorization.getAttribute(OAuth2ParameterNames.STATE));
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
|
private final String registeredClientId;
|
||||||
|
private final String principalName;
|
||||||
|
|
||||||
|
private OAuth2AuthorizationId(String registeredClientId, String principalName) {
|
||||||
|
this.registeredClientId = registeredClientId;
|
||||||
|
this.principalName = principalName;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean matchesAuthorizationCode(OAuth2Authorization authorization, String token) {
|
@Override
|
||||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode =
|
public boolean equals(Object obj) {
|
||||||
authorization.getToken(OAuth2AuthorizationCode.class);
|
if (this == obj) {
|
||||||
return authorizationCode != null && authorizationCode.getToken().getTokenValue().equals(token);
|
return true;
|
||||||
|
}
|
||||||
|
if (obj == null || getClass() != obj.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
OAuth2AuthorizationId that = (OAuth2AuthorizationId) obj;
|
||||||
|
return Objects.equals(this.registeredClientId, that.registeredClientId) &&
|
||||||
|
Objects.equals(this.principalName, that.principalName);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean matchesAccessToken(OAuth2Authorization authorization, String token) {
|
@Override
|
||||||
OAuth2Authorization.Token<OAuth2AccessToken> accessToken =
|
public int hashCode() {
|
||||||
authorization.getToken(OAuth2AccessToken.class);
|
return Objects.hash(this.registeredClientId, this.principalName);
|
||||||
return accessToken != null && accessToken.getToken().getTokenValue().equals(token);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean matchesRefreshToken(OAuth2Authorization authorization, String token) {
|
|
||||||
OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken =
|
|
||||||
authorization.getToken(OAuth2RefreshToken.class);
|
|
||||||
return refreshToken != null && refreshToken.getToken().getTokenValue().equals(token);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,87 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.oauth2.core.context.Context;
|
|
||||||
import org.springframework.security.oauth2.jwt.JoseHeader;
|
|
||||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see OAuth2TokenContext
|
|
||||||
* @see JoseHeader.Builder
|
|
||||||
* @see JwtClaimsSet.Builder
|
|
||||||
*/
|
|
||||||
public final class JwtEncodingContext implements OAuth2TokenContext {
|
|
||||||
private final Context context;
|
|
||||||
|
|
||||||
private JwtEncodingContext(Map<Object, Object> context) {
|
|
||||||
this.context = Context.of(context);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
@Override
|
|
||||||
public <V> V get(Object key) {
|
|
||||||
return this.context.get(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean hasKey(Object key) {
|
|
||||||
return this.context.hasKey(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
public JoseHeader.Builder getHeaders() {
|
|
||||||
return get(JoseHeader.Builder.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public JwtClaimsSet.Builder getClaims() {
|
|
||||||
return get(JwtClaimsSet.Builder.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Builder with(JoseHeader.Builder headersBuilder, JwtClaimsSet.Builder claimsBuilder) {
|
|
||||||
return new Builder(headersBuilder, claimsBuilder);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static final class Builder extends AbstractBuilder<JwtEncodingContext, Builder> {
|
|
||||||
|
|
||||||
private Builder(JoseHeader.Builder headersBuilder, JwtClaimsSet.Builder claimsBuilder) {
|
|
||||||
Assert.notNull(headersBuilder, "headersBuilder cannot be null");
|
|
||||||
Assert.notNull(claimsBuilder, "claimsBuilder cannot be null");
|
|
||||||
put(JoseHeader.Builder.class, headersBuilder);
|
|
||||||
put(JwtClaimsSet.Builder.class, claimsBuilder);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Builder headers(Consumer<JoseHeader.Builder> headersConsumer) {
|
|
||||||
headersConsumer.accept(get(JoseHeader.Builder.class));
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Builder claims(Consumer<JwtClaimsSet.Builder> claimsConsumer) {
|
|
||||||
claimsConsumer.accept(get(JwtClaimsSet.Builder.class));
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public JwtEncodingContext build() {
|
|
||||||
return new JwtEncodingContext(this.context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,68 +15,39 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken2;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A representation of an OAuth 2.0 Authorization, which holds state related to the authorization granted
|
* A representation of an OAuth 2.0 Authorization,
|
||||||
* to a {@link #getRegisteredClientId() client}, by the {@link #getPrincipalName() resource owner}
|
* which holds state related to the authorization granted to the {@link #getRegisteredClientId() client}
|
||||||
* or itself in the case of the {@code client_credentials} grant type.
|
* by the {@link #getPrincipalName() resource owner}.
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Krisztian Toth
|
* @author Krisztian Toth
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see RegisteredClient
|
* @see RegisteredClient
|
||||||
* @see AuthorizationGrantType
|
|
||||||
* @see AbstractOAuth2Token
|
|
||||||
* @see OAuth2AccessToken
|
* @see OAuth2AccessToken
|
||||||
* @see OAuth2RefreshToken
|
|
||||||
*/
|
*/
|
||||||
public class OAuth2Authorization implements Serializable {
|
public class OAuth2Authorization implements Serializable {
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
|
|
||||||
/**
|
|
||||||
* The name of the {@link #getAttribute(String) attribute} used for the authorized scope(s).
|
|
||||||
* The value of the attribute is of type {@code Set<String>}.
|
|
||||||
*/
|
|
||||||
public static final String AUTHORIZED_SCOPE_ATTRIBUTE_NAME =
|
|
||||||
OAuth2Authorization.class.getName().concat(".AUTHORIZED_SCOPE");
|
|
||||||
|
|
||||||
private String id;
|
|
||||||
private String registeredClientId;
|
private String registeredClientId;
|
||||||
private String principalName;
|
private String principalName;
|
||||||
private AuthorizationGrantType authorizationGrantType;
|
private OAuth2AccessToken accessToken;
|
||||||
private Map<Class<? extends AbstractOAuth2Token>, Token<?>> tokens;
|
|
||||||
private Map<String, Object> attributes;
|
private Map<String, Object> attributes;
|
||||||
|
|
||||||
protected OAuth2Authorization() {
|
protected OAuth2Authorization() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the identifier for the authorization.
|
|
||||||
*
|
|
||||||
* @return the identifier for the authorization
|
|
||||||
*/
|
|
||||||
public String getId() {
|
|
||||||
return this.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the identifier for the {@link RegisteredClient#getId() registered client}.
|
* Returns the identifier for the {@link RegisteredClient#getId() registered client}.
|
||||||
*
|
*
|
||||||
@ -87,73 +58,21 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the {@code Principal} name of the resource owner (or client).
|
* Returns the resource owner's {@code Principal} name.
|
||||||
*
|
*
|
||||||
* @return the {@code Principal} name of the resource owner (or client)
|
* @return the resource owner's {@code Principal} name
|
||||||
*/
|
*/
|
||||||
public String getPrincipalName() {
|
public String getPrincipalName() {
|
||||||
return this.principalName;
|
return this.principalName;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the {@link AuthorizationGrantType authorization grant type} used for the authorization.
|
* Returns the {@link OAuth2AccessToken access token} credential.
|
||||||
*
|
*
|
||||||
* @return the {@link AuthorizationGrantType} used for the authorization
|
* @return the {@link OAuth2AccessToken}
|
||||||
*/
|
*/
|
||||||
public AuthorizationGrantType getAuthorizationGrantType() {
|
public OAuth2AccessToken getAccessToken() {
|
||||||
return this.authorizationGrantType;
|
return this.accessToken;
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link Token} of type {@link OAuth2AccessToken}.
|
|
||||||
*
|
|
||||||
* @return the {@link Token} of type {@link OAuth2AccessToken}
|
|
||||||
*/
|
|
||||||
public Token<OAuth2AccessToken> getAccessToken() {
|
|
||||||
return getToken(OAuth2AccessToken.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link Token} of type {@link OAuth2RefreshToken}.
|
|
||||||
*
|
|
||||||
* @return the {@link Token} of type {@link OAuth2RefreshToken}, or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
public Token<OAuth2RefreshToken> getRefreshToken() {
|
|
||||||
return getToken(OAuth2RefreshToken.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link Token} of type {@code tokenType}.
|
|
||||||
*
|
|
||||||
* @param tokenType the token type
|
|
||||||
* @param <T> the type of the token
|
|
||||||
* @return the {@link Token}, or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public <T extends AbstractOAuth2Token> Token<T> getToken(Class<T> tokenType) {
|
|
||||||
Assert.notNull(tokenType, "tokenType cannot be null");
|
|
||||||
Token<?> token = this.tokens.get(tokenType);
|
|
||||||
return token != null ? (Token<T>) token : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link Token} matching the {@code tokenValue}.
|
|
||||||
*
|
|
||||||
* @param tokenValue the token value
|
|
||||||
* @param <T> the type of the token
|
|
||||||
* @return the {@link Token}, or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public <T extends AbstractOAuth2Token> Token<T> getToken(String tokenValue) {
|
|
||||||
Assert.hasText(tokenValue, "tokenValue cannot be empty");
|
|
||||||
Token<?> token = this.tokens.values().stream()
|
|
||||||
.filter(t -> t.getToken().getTokenValue().equals(tokenValue))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
return token != null ? (Token<T>) token : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -170,9 +89,8 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
*
|
*
|
||||||
* @param name the name of the attribute
|
* @param name the name of the attribute
|
||||||
* @param <T> the type of the attribute
|
* @param <T> the type of the attribute
|
||||||
* @return the value of an attribute associated to the authorization, or {@code null} if not available
|
* @return the value of the attribute associated to the authorization, or {@code null} if not available
|
||||||
*/
|
*/
|
||||||
@Nullable
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public <T> T getAttribute(String name) {
|
public <T> T getAttribute(String name) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
@ -188,18 +106,15 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
OAuth2Authorization that = (OAuth2Authorization) obj;
|
OAuth2Authorization that = (OAuth2Authorization) obj;
|
||||||
return Objects.equals(this.id, that.id) &&
|
return Objects.equals(this.registeredClientId, that.registeredClientId) &&
|
||||||
Objects.equals(this.registeredClientId, that.registeredClientId) &&
|
|
||||||
Objects.equals(this.principalName, that.principalName) &&
|
Objects.equals(this.principalName, that.principalName) &&
|
||||||
Objects.equals(this.authorizationGrantType, that.authorizationGrantType) &&
|
Objects.equals(this.accessToken, that.accessToken) &&
|
||||||
Objects.equals(this.tokens, that.tokens) &&
|
|
||||||
Objects.equals(this.attributes, that.attributes);
|
Objects.equals(this.attributes, that.attributes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(this.id, this.registeredClientId, this.principalName,
|
return Objects.hash(this.registeredClientId, this.principalName, this.accessToken, this.attributes);
|
||||||
this.authorizationGrantType, this.tokens, this.attributes);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -214,161 +129,37 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a new {@link Builder}, initialized with the values from the provided {@code OAuth2Authorization}.
|
* Returns a new {@link Builder}, initialized with the values from the provided {@code authorization}.
|
||||||
*
|
*
|
||||||
* @param authorization the {@code OAuth2Authorization} used for initializing the {@link Builder}
|
* @param authorization the authorization used for initializing the {@link Builder}
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public static Builder from(OAuth2Authorization authorization) {
|
public static Builder from(OAuth2Authorization authorization) {
|
||||||
Assert.notNull(authorization, "authorization cannot be null");
|
Assert.notNull(authorization, "authorization cannot be null");
|
||||||
return new Builder(authorization.getRegisteredClientId())
|
return new Builder(authorization.getRegisteredClientId())
|
||||||
.id(authorization.getId())
|
|
||||||
.principalName(authorization.getPrincipalName())
|
.principalName(authorization.getPrincipalName())
|
||||||
.authorizationGrantType(authorization.getAuthorizationGrantType())
|
.accessToken(authorization.getAccessToken())
|
||||||
.tokens(authorization.tokens)
|
|
||||||
.attributes(attrs -> attrs.putAll(authorization.getAttributes()));
|
.attributes(attrs -> attrs.putAll(authorization.getAttributes()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A holder of an OAuth 2.0 Token and it's associated metadata.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
*/
|
|
||||||
public static class Token<T extends AbstractOAuth2Token> implements Serializable {
|
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
|
||||||
protected static final String TOKEN_METADATA_BASE = "metadata.token.";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The name of the metadata that indicates if the token has been invalidated.
|
|
||||||
*/
|
|
||||||
public static final String INVALIDATED_METADATA_NAME = TOKEN_METADATA_BASE.concat("invalidated");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The name of the metadata used for the claims of the token.
|
|
||||||
*/
|
|
||||||
public static final String CLAIMS_METADATA_NAME = TOKEN_METADATA_BASE.concat("claims");
|
|
||||||
|
|
||||||
private final T token;
|
|
||||||
private final Map<String, Object> metadata;
|
|
||||||
|
|
||||||
protected Token(T token) {
|
|
||||||
this(token, defaultMetadata());
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Token(T token, Map<String, Object> metadata) {
|
|
||||||
this.token = token;
|
|
||||||
this.metadata = Collections.unmodifiableMap(metadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the token of type {@link AbstractOAuth2Token}.
|
|
||||||
*
|
|
||||||
* @return the token of type {@link AbstractOAuth2Token}
|
|
||||||
*/
|
|
||||||
public T getToken() {
|
|
||||||
return this.token;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns {@code true} if the token has been invalidated (e.g. revoked).
|
|
||||||
* The default is {@code false}.
|
|
||||||
*
|
|
||||||
* @return {@code true} if the token has been invalidated, {@code false} otherwise
|
|
||||||
*/
|
|
||||||
public boolean isInvalidated() {
|
|
||||||
return Boolean.TRUE.equals(getMetadata(INVALIDATED_METADATA_NAME));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the claims associated to the token.
|
|
||||||
*
|
|
||||||
* @return a {@code Map} of the claims, or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
public Map<String, Object> getClaims() {
|
|
||||||
return getMetadata(CLAIMS_METADATA_NAME);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the metadata associated to the token.
|
|
||||||
*
|
|
||||||
* @param name the name of the metadata
|
|
||||||
* @param <V> the value type of the metadata
|
|
||||||
* @return the value of the metadata, or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public <V> V getMetadata(String name) {
|
|
||||||
Assert.hasText(name, "name cannot be empty");
|
|
||||||
return (V) this.metadata.get(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the metadata associated to the token.
|
|
||||||
*
|
|
||||||
* @return a {@code Map} of the metadata
|
|
||||||
*/
|
|
||||||
public Map<String, Object> getMetadata() {
|
|
||||||
return this.metadata;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected static Map<String, Object> defaultMetadata() {
|
|
||||||
Map<String, Object> metadata = new HashMap<>();
|
|
||||||
metadata.put(INVALIDATED_METADATA_NAME, false);
|
|
||||||
return metadata;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (obj == null || getClass() != obj.getClass()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
Token<?> that = (Token<?>) obj;
|
|
||||||
return Objects.equals(this.token, that.token) &&
|
|
||||||
Objects.equals(this.metadata, that.metadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(this.token, this.metadata);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for {@link OAuth2Authorization}.
|
* A builder for {@link OAuth2Authorization}.
|
||||||
*/
|
*/
|
||||||
public static class Builder implements Serializable {
|
public static class Builder implements Serializable {
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
private String id;
|
private String registeredClientId;
|
||||||
private final String registeredClientId;
|
|
||||||
private String principalName;
|
private String principalName;
|
||||||
private AuthorizationGrantType authorizationGrantType;
|
private OAuth2AccessToken accessToken;
|
||||||
private Map<Class<? extends AbstractOAuth2Token>, Token<?>> tokens = new HashMap<>();
|
private Map<String, Object> attributes = new HashMap<>();
|
||||||
private final Map<String, Object> attributes = new HashMap<>();
|
|
||||||
|
|
||||||
protected Builder(String registeredClientId) {
|
protected Builder(String registeredClientId) {
|
||||||
this.registeredClientId = registeredClientId;
|
this.registeredClientId = registeredClientId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the identifier for the authorization.
|
* Sets the resource owner's {@code Principal} name.
|
||||||
*
|
*
|
||||||
* @param id the identifier for the authorization
|
* @param principalName the resource owner's {@code Principal} name
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public Builder id(String id) {
|
|
||||||
this.id = id;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@code Principal} name of the resource owner (or client).
|
|
||||||
*
|
|
||||||
* @param principalName the {@code Principal} name of the resource owner (or client)
|
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder principalName(String principalName) {
|
public Builder principalName(String principalName) {
|
||||||
@ -377,75 +168,13 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the {@link AuthorizationGrantType authorization grant type} used for the authorization.
|
* Sets the {@link OAuth2AccessToken access token} credential.
|
||||||
*
|
|
||||||
* @param authorizationGrantType the {@link AuthorizationGrantType}
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public Builder authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
|
|
||||||
this.authorizationGrantType = authorizationGrantType;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link OAuth2AccessToken access token}.
|
|
||||||
*
|
*
|
||||||
* @param accessToken the {@link OAuth2AccessToken}
|
* @param accessToken the {@link OAuth2AccessToken}
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder accessToken(OAuth2AccessToken accessToken) {
|
public Builder accessToken(OAuth2AccessToken accessToken) {
|
||||||
return token(accessToken);
|
this.accessToken = accessToken;
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link OAuth2RefreshToken refresh token}.
|
|
||||||
*
|
|
||||||
* @param refreshToken the {@link OAuth2RefreshToken}
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public Builder refreshToken(OAuth2RefreshToken refreshToken) {
|
|
||||||
return token(refreshToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link AbstractOAuth2Token token}.
|
|
||||||
*
|
|
||||||
* @param token the token
|
|
||||||
* @param <T> the type of the token
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public <T extends AbstractOAuth2Token> Builder token(T token) {
|
|
||||||
return token(token, (metadata) -> {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the {@link AbstractOAuth2Token token} and associated metadata.
|
|
||||||
*
|
|
||||||
* @param token the token
|
|
||||||
* @param metadataConsumer a {@code Consumer} of the metadata {@code Map}
|
|
||||||
* @param <T> the type of the token
|
|
||||||
* @return the {@link Builder}
|
|
||||||
*/
|
|
||||||
public <T extends AbstractOAuth2Token> Builder token(T token,
|
|
||||||
Consumer<Map<String, Object>> metadataConsumer) {
|
|
||||||
|
|
||||||
Assert.notNull(token, "token cannot be null");
|
|
||||||
Map<String, Object> metadata = Token.defaultMetadata();
|
|
||||||
Token<?> existingToken = this.tokens.get(token.getClass());
|
|
||||||
if (existingToken != null) {
|
|
||||||
metadata.putAll(existingToken.getMetadata());
|
|
||||||
}
|
|
||||||
metadataConsumer.accept(metadata);
|
|
||||||
Class<? extends AbstractOAuth2Token> tokenClass = token.getClass();
|
|
||||||
if (tokenClass.equals(OAuth2RefreshToken2.class)) {
|
|
||||||
tokenClass = OAuth2RefreshToken.class;
|
|
||||||
}
|
|
||||||
this.tokens.put(tokenClass, new Token<>(token, metadata));
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected final Builder tokens(Map<Class<? extends AbstractOAuth2Token>, Token<?>> tokens) {
|
|
||||||
this.tokens = new HashMap<>(tokens);
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -482,17 +211,11 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
*/
|
*/
|
||||||
public OAuth2Authorization build() {
|
public OAuth2Authorization build() {
|
||||||
Assert.hasText(this.principalName, "principalName cannot be empty");
|
Assert.hasText(this.principalName, "principalName cannot be empty");
|
||||||
Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null");
|
|
||||||
|
|
||||||
OAuth2Authorization authorization = new OAuth2Authorization();
|
OAuth2Authorization authorization = new OAuth2Authorization();
|
||||||
if (!StringUtils.hasText(this.id)) {
|
|
||||||
this.id = UUID.randomUUID().toString();
|
|
||||||
}
|
|
||||||
authorization.id = this.id;
|
|
||||||
authorization.registeredClientId = this.registeredClientId;
|
authorization.registeredClientId = this.registeredClientId;
|
||||||
authorization.principalName = this.principalName;
|
authorization.principalName = this.principalName;
|
||||||
authorization.authorizationGrantType = this.authorizationGrantType;
|
authorization.accessToken = this.accessToken;
|
||||||
authorization.tokens = Collections.unmodifiableMap(this.tokens);
|
|
||||||
authorization.attributes = Collections.unmodifiableMap(this.attributes);
|
authorization.attributes = Collections.unmodifiableMap(this.attributes);
|
||||||
return authorization;
|
return authorization;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,58 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
|
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attributes that may be contained in the
|
||||||
|
* {@link OAuth2Authorization#getAttributes()} {@code Map}.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
|
* @see OAuth2Authorization#getAttributes()
|
||||||
|
*/
|
||||||
|
public interface OAuth2AuthorizationAttributeNames {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attribute used for correlating the user consent request/response.
|
||||||
|
*/
|
||||||
|
String STATE = OAuth2Authorization.class.getName().concat(".STATE");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attribute used for the {@link OAuth2ParameterNames#CODE} parameter.
|
||||||
|
*/
|
||||||
|
String CODE = OAuth2Authorization.class.getName().concat(".CODE");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attribute used for the {@link OAuth2AuthorizationRequest}.
|
||||||
|
*/
|
||||||
|
String AUTHORIZATION_REQUEST = OAuth2Authorization.class.getName().concat(".AUTHORIZATION_REQUEST");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attribute used for the authorized scope(s).
|
||||||
|
*/
|
||||||
|
String AUTHORIZED_SCOPES = OAuth2Authorization.class.getName().concat(".AUTHORIZED_SCOPES");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the attribute used for the attributes/claims of the {@link OAuth2AccessToken}.
|
||||||
|
*/
|
||||||
|
String ACCESS_TOKEN_ATTRIBUTES = OAuth2Authorization.class.getName().concat(".ACCESS_TOKEN_ATTRIBUTES");
|
||||||
|
|
||||||
|
}
|
@ -1,43 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An implementation of an {@link AbstractOAuth2Token}
|
|
||||||
* representing an OAuth 2.0 Authorization Code Grant.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see AbstractOAuth2Token
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
|
|
||||||
*/
|
|
||||||
public class OAuth2AuthorizationCode extends AbstractOAuth2Token {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2AuthorizationCode} using the provided parameters.
|
|
||||||
* @param tokenValue the token value
|
|
||||||
* @param issuedAt the time at which the token was issued
|
|
||||||
* @param expiresAt the time at which the token expires
|
|
||||||
*/
|
|
||||||
public OAuth2AuthorizationCode(String tokenValue, Instant issuedAt, Instant expiresAt) {
|
|
||||||
super(tokenValue, issuedAt, expiresAt);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -16,7 +16,6 @@
|
|||||||
package org.springframework.security.oauth2.server.authorization;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
import org.springframework.lang.Nullable;
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementations of this interface are responsible for the management
|
* Implementations of this interface are responsible for the management
|
||||||
@ -25,7 +24,6 @@ import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2Authorization
|
* @see OAuth2Authorization
|
||||||
* @see OAuth2TokenType
|
|
||||||
*/
|
*/
|
||||||
public interface OAuth2AuthorizationService {
|
public interface OAuth2AuthorizationService {
|
||||||
|
|
||||||
@ -43,25 +41,14 @@ public interface OAuth2AuthorizationService {
|
|||||||
*/
|
*/
|
||||||
void remove(OAuth2Authorization authorization);
|
void remove(OAuth2Authorization authorization);
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link OAuth2Authorization} identified by the provided {@code id},
|
|
||||||
* or {@code null} if not found.
|
|
||||||
*
|
|
||||||
* @param id the authorization identifier
|
|
||||||
* @return the {@link OAuth2Authorization} if found, otherwise {@code null}
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
OAuth2Authorization findById(String id);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the {@link OAuth2Authorization} containing the provided {@code token},
|
* Returns the {@link OAuth2Authorization} containing the provided {@code token},
|
||||||
* or {@code null} if not found.
|
* or {@code null} if not found.
|
||||||
*
|
*
|
||||||
* @param token the token credential
|
* @param token the token credential
|
||||||
* @param tokenType the {@link OAuth2TokenType token type}
|
* @param tokenType the {@link TokenType token type}
|
||||||
* @return the {@link OAuth2Authorization} if found, otherwise {@code null}
|
* @return the {@link OAuth2Authorization} if found, otherwise {@code null}
|
||||||
*/
|
*/
|
||||||
@Nullable
|
OAuth2Authorization findByToken(String token, @Nullable TokenType tokenType);
|
||||||
OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,130 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
import org.springframework.security.oauth2.core.context.Context;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see Context
|
|
||||||
*/
|
|
||||||
public interface OAuth2TokenContext extends Context {
|
|
||||||
|
|
||||||
default RegisteredClient getRegisteredClient() {
|
|
||||||
return get(RegisteredClient.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
default <T extends Authentication> T getPrincipal() {
|
|
||||||
return get(AbstractBuilder.PRINCIPAL_AUTHENTICATION_KEY);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nullable
|
|
||||||
default OAuth2Authorization getAuthorization() {
|
|
||||||
return get(OAuth2Authorization.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
default Set<String> getAuthorizedScopes() {
|
|
||||||
return hasKey(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME) ?
|
|
||||||
get(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME) :
|
|
||||||
Collections.emptySet();
|
|
||||||
}
|
|
||||||
|
|
||||||
default OAuth2TokenType getTokenType() {
|
|
||||||
return get(OAuth2TokenType.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
default AuthorizationGrantType getAuthorizationGrantType() {
|
|
||||||
return get(AuthorizationGrantType.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
default <T extends Authentication> T getAuthorizationGrant() {
|
|
||||||
return get(AbstractBuilder.AUTHORIZATION_GRANT_AUTHENTICATION_KEY);
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract class AbstractBuilder<T extends OAuth2TokenContext, B extends AbstractBuilder<T, B>> {
|
|
||||||
private static final String PRINCIPAL_AUTHENTICATION_KEY =
|
|
||||||
Authentication.class.getName().concat(".PRINCIPAL");
|
|
||||||
private static final String AUTHORIZATION_GRANT_AUTHENTICATION_KEY =
|
|
||||||
Authentication.class.getName().concat(".AUTHORIZATION_GRANT");
|
|
||||||
protected final Map<Object, Object> context = new HashMap<>();
|
|
||||||
|
|
||||||
public B registeredClient(RegisteredClient registeredClient) {
|
|
||||||
return put(RegisteredClient.class, registeredClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B principal(Authentication principal) {
|
|
||||||
return put(PRINCIPAL_AUTHENTICATION_KEY, principal);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B authorization(OAuth2Authorization authorization) {
|
|
||||||
return put(OAuth2Authorization.class, authorization);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B authorizedScopes(Set<String> authorizedScopes) {
|
|
||||||
return put(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B tokenType(OAuth2TokenType tokenType) {
|
|
||||||
return put(OAuth2TokenType.class, tokenType);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
|
|
||||||
return put(AuthorizationGrantType.class, authorizationGrantType);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B authorizationGrant(Authentication authorizationGrant) {
|
|
||||||
return put(AUTHORIZATION_GRANT_AUTHENTICATION_KEY, authorizationGrant);
|
|
||||||
}
|
|
||||||
|
|
||||||
public B put(Object key, Object value) {
|
|
||||||
Assert.notNull(key, "key cannot be null");
|
|
||||||
Assert.notNull(value, "value cannot be null");
|
|
||||||
this.context.put(key, value);
|
|
||||||
return getThis();
|
|
||||||
}
|
|
||||||
|
|
||||||
public B context(Consumer<Map<Object, Object>> contextConsumer) {
|
|
||||||
contextConsumer.accept(this.context);
|
|
||||||
return getThis();
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
protected <V> V get(Object key) {
|
|
||||||
return (V) this.context.get(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
protected B getThis() {
|
|
||||||
return (B) this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract T build();
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,28 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see OAuth2TokenContext
|
|
||||||
*/
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface OAuth2TokenCustomizer<C extends OAuth2TokenContext> {
|
|
||||||
|
|
||||||
void customize(C context);
|
|
||||||
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,40 +13,27 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.core;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Standard token types defined in the OAuth Token Type Hints Registry.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.0.1
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-4.1.2">4.1.2 OAuth Token Type Hints Registry</a>
|
|
||||||
*/
|
*/
|
||||||
public final class OAuth2TokenType implements Serializable {
|
public final class TokenType implements Serializable {
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
public static final OAuth2TokenType ACCESS_TOKEN = new OAuth2TokenType("access_token");
|
public static final TokenType ACCESS_TOKEN = new TokenType("access_token");
|
||||||
public static final OAuth2TokenType REFRESH_TOKEN = new OAuth2TokenType("refresh_token");
|
public static final TokenType AUTHORIZATION_CODE = new TokenType("authorization_code");
|
||||||
private final String value;
|
private final String value;
|
||||||
|
|
||||||
/**
|
public TokenType(String value) {
|
||||||
* Constructs an {@code OAuth2TokenType} using the provided value.
|
|
||||||
*
|
|
||||||
* @param value the value of the token type
|
|
||||||
*/
|
|
||||||
public OAuth2TokenType(String value) {
|
|
||||||
Assert.hasText(value, "value cannot be empty");
|
Assert.hasText(value, "value cannot be empty");
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the value of the token type.
|
|
||||||
*
|
|
||||||
* @return the value of the token type
|
|
||||||
*/
|
|
||||||
public String getValue() {
|
public String getValue() {
|
||||||
return this.value;
|
return this.value;
|
||||||
}
|
}
|
||||||
@ -59,12 +46,12 @@ public final class OAuth2TokenType implements Serializable {
|
|||||||
if (obj == null || this.getClass() != obj.getClass()) {
|
if (obj == null || this.getClass() != obj.getClass()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
OAuth2TokenType that = (OAuth2TokenType) obj;
|
TokenType that = (TokenType) obj;
|
||||||
return getValue().equals(that.getValue());
|
return this.getValue().equals(that.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return getValue().hashCode();
|
return this.getValue().hashCode();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -13,7 +13,7 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.core;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal class used for serialization across Spring Security Authorization Server classes.
|
* Internal class used for serialization across Spring Security Authorization Server classes.
|
||||||
@ -23,8 +23,8 @@ package org.springframework.security.oauth2.core;
|
|||||||
*/
|
*/
|
||||||
public final class Version {
|
public final class Version {
|
||||||
private static final int MAJOR = 0;
|
private static final int MAJOR = 0;
|
||||||
private static final int MINOR = 1;
|
private static final int MINOR = 0;
|
||||||
private static final int PATCH = 1;
|
private static final int PATCH = 2;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global Serialization value for Spring Security Authorization Server classes.
|
* Global Serialization value for Spring Security Authorization Server classes.
|
@ -1,101 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.temporal.ChronoUnit;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
|
||||||
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
|
|
||||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
|
||||||
import org.springframework.security.oauth2.jwt.JoseHeader;
|
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
|
||||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
|
||||||
import org.springframework.util.CollectionUtils;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Utility methods used by the {@link AuthenticationProvider}'s when issuing {@link Jwt}'s.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
*/
|
|
||||||
final class JwtUtils {
|
|
||||||
|
|
||||||
private JwtUtils() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static JoseHeader.Builder headers() {
|
|
||||||
return JoseHeader.withAlgorithm(SignatureAlgorithm.RS256);
|
|
||||||
}
|
|
||||||
|
|
||||||
static JwtClaimsSet.Builder accessTokenClaims(RegisteredClient registeredClient,
|
|
||||||
String issuer, String subject, Set<String> authorizedScopes) {
|
|
||||||
|
|
||||||
Instant issuedAt = Instant.now();
|
|
||||||
Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().accessTokenTimeToLive());
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
|
|
||||||
if (StringUtils.hasText(issuer)) {
|
|
||||||
claimsBuilder.issuer(issuer);
|
|
||||||
}
|
|
||||||
claimsBuilder
|
|
||||||
.subject(subject)
|
|
||||||
.audience(Collections.singletonList(registeredClient.getClientId()))
|
|
||||||
.issuedAt(issuedAt)
|
|
||||||
.expiresAt(expiresAt)
|
|
||||||
.notBefore(issuedAt);
|
|
||||||
if (!CollectionUtils.isEmpty(authorizedScopes)) {
|
|
||||||
claimsBuilder.claim(OAuth2ParameterNames.SCOPE, authorizedScopes);
|
|
||||||
}
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
return claimsBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
static JwtClaimsSet.Builder idTokenClaims(RegisteredClient registeredClient,
|
|
||||||
String issuer, String subject, String nonce) {
|
|
||||||
|
|
||||||
Instant issuedAt = Instant.now();
|
|
||||||
// TODO Allow configuration for ID Token time-to-live
|
|
||||||
Instant expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
|
|
||||||
if (StringUtils.hasText(issuer)) {
|
|
||||||
claimsBuilder.issuer(issuer);
|
|
||||||
}
|
|
||||||
claimsBuilder
|
|
||||||
.subject(subject)
|
|
||||||
.audience(Collections.singletonList(registeredClient.getClientId()))
|
|
||||||
.issuedAt(issuedAt)
|
|
||||||
.expiresAt(expiresAt)
|
|
||||||
.claim(IdTokenClaimNames.AZP, registeredClient.getClientId());
|
|
||||||
if (StringUtils.hasText(nonce)) {
|
|
||||||
claimsBuilder.claim(IdTokenClaimNames.NONCE, nonce);
|
|
||||||
}
|
|
||||||
// TODO Add 'auth_time' claim
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
return claimsBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -15,29 +15,25 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link Authentication} implementation used when issuing an
|
* An {@link Authentication} implementation used when issuing an OAuth 2.0 Access Token.
|
||||||
* OAuth 2.0 Access Token and (optional) Refresh Token.
|
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Madhu Bhat
|
* @author Madhu Bhat
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see AbstractAuthenticationToken
|
* @see AbstractAuthenticationToken
|
||||||
|
* @see OAuth2AuthorizationCodeAuthenticationProvider
|
||||||
* @see RegisteredClient
|
* @see RegisteredClient
|
||||||
* @see OAuth2AccessToken
|
* @see OAuth2AccessToken
|
||||||
* @see OAuth2RefreshToken
|
|
||||||
* @see OAuth2ClientAuthenticationToken
|
* @see OAuth2ClientAuthenticationToken
|
||||||
*/
|
*/
|
||||||
public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthenticationToken {
|
public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthenticationToken {
|
||||||
@ -45,8 +41,6 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
|
|||||||
private final RegisteredClient registeredClient;
|
private final RegisteredClient registeredClient;
|
||||||
private final Authentication clientPrincipal;
|
private final Authentication clientPrincipal;
|
||||||
private final OAuth2AccessToken accessToken;
|
private final OAuth2AccessToken accessToken;
|
||||||
private final OAuth2RefreshToken refreshToken;
|
|
||||||
private final Map<String, Object> additionalParameters;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
|
* Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
|
||||||
@ -57,43 +51,13 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
|
|||||||
*/
|
*/
|
||||||
public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient,
|
public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient,
|
||||||
Authentication clientPrincipal, OAuth2AccessToken accessToken) {
|
Authentication clientPrincipal, OAuth2AccessToken accessToken) {
|
||||||
this(registeredClient, clientPrincipal, accessToken, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param registeredClient the registered client
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
* @param accessToken the access token
|
|
||||||
* @param refreshToken the refresh token
|
|
||||||
*/
|
|
||||||
public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient, Authentication clientPrincipal,
|
|
||||||
OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken) {
|
|
||||||
this(registeredClient, clientPrincipal, accessToken, refreshToken, Collections.emptyMap());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param registeredClient the registered client
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
* @param accessToken the access token
|
|
||||||
* @param refreshToken the refresh token
|
|
||||||
* @param additionalParameters the additional parameters
|
|
||||||
*/
|
|
||||||
public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient, Authentication clientPrincipal,
|
|
||||||
OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken, Map<String, Object> additionalParameters) {
|
|
||||||
super(Collections.emptyList());
|
super(Collections.emptyList());
|
||||||
Assert.notNull(registeredClient, "registeredClient cannot be null");
|
Assert.notNull(registeredClient, "registeredClient cannot be null");
|
||||||
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
||||||
Assert.notNull(accessToken, "accessToken cannot be null");
|
Assert.notNull(accessToken, "accessToken cannot be null");
|
||||||
Assert.notNull(additionalParameters, "additionalParameters cannot be null");
|
|
||||||
this.registeredClient = registeredClient;
|
this.registeredClient = registeredClient;
|
||||||
this.clientPrincipal = clientPrincipal;
|
this.clientPrincipal = clientPrincipal;
|
||||||
this.accessToken = accessToken;
|
this.accessToken = accessToken;
|
||||||
this.refreshToken = refreshToken;
|
|
||||||
this.additionalParameters = additionalParameters;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -123,23 +87,4 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
|
|||||||
public OAuth2AccessToken getAccessToken() {
|
public OAuth2AccessToken getAccessToken() {
|
||||||
return this.accessToken;
|
return this.accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link OAuth2RefreshToken refresh token}.
|
|
||||||
*
|
|
||||||
* @return the {@link OAuth2RefreshToken} or {@code null} if not available
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
public OAuth2RefreshToken getRefreshToken() {
|
|
||||||
return this.refreshToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the additional parameters.
|
|
||||||
*
|
|
||||||
* @return a {@code Map} of the additional parameters, may be empty
|
|
||||||
*/
|
|
||||||
public Map<String, Object> getAdditionalParameters() {
|
|
||||||
return this.additionalParameters;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,78 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Utility methods for the OAuth 2.0 {@link AuthenticationProvider}'s.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
*/
|
|
||||||
final class OAuth2AuthenticationProviderUtils {
|
|
||||||
|
|
||||||
private OAuth2AuthenticationProviderUtils() {
|
|
||||||
}
|
|
||||||
|
|
||||||
static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = null;
|
|
||||||
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
|
|
||||||
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
|
|
||||||
}
|
|
||||||
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
|
|
||||||
return clientPrincipal;
|
|
||||||
}
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
|
|
||||||
}
|
|
||||||
|
|
||||||
static <T extends AbstractOAuth2Token> OAuth2Authorization invalidate(
|
|
||||||
OAuth2Authorization authorization, T token) {
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
|
|
||||||
.token(token,
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true));
|
|
||||||
|
|
||||||
if (OAuth2RefreshToken.class.isAssignableFrom(token.getClass())) {
|
|
||||||
authorizationBuilder.token(
|
|
||||||
authorization.getAccessToken().getToken(),
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true));
|
|
||||||
|
|
||||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode =
|
|
||||||
authorization.getToken(OAuth2AuthorizationCode.class);
|
|
||||||
if (authorizationCode != null && !authorizationCode.isInvalidated()) {
|
|
||||||
authorizationBuilder.token(
|
|
||||||
authorizationCode.getToken(),
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
return authorizationBuilder.build();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,43 +15,36 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||||
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
|
import org.springframework.security.oauth2.jose.JoseHeader;
|
||||||
import org.springframework.security.oauth2.core.oidc.OidcScopes;
|
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||||
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
|
|
||||||
import org.springframework.security.oauth2.jwt.JoseHeader;
|
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationAttributeNames;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.TokenType;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||||
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
|
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code Grant.
|
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code Grant.
|
||||||
@ -61,72 +54,58 @@ import static org.springframework.security.oauth2.server.authorization.authentic
|
|||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2AuthorizationCodeAuthenticationToken
|
* @see OAuth2AuthorizationCodeAuthenticationToken
|
||||||
* @see OAuth2AccessTokenAuthenticationToken
|
* @see OAuth2AccessTokenAuthenticationToken
|
||||||
|
* @see RegisteredClientRepository
|
||||||
* @see OAuth2AuthorizationService
|
* @see OAuth2AuthorizationService
|
||||||
* @see JwtEncoder
|
* @see JwtEncoder
|
||||||
* @see OAuth2TokenCustomizer
|
|
||||||
* @see JwtEncodingContext
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section 4.1 Authorization Code Grant</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request</a>
|
||||||
*/
|
*/
|
||||||
public class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
|
public class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
|
||||||
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE =
|
private final RegisteredClientRepository registeredClientRepository;
|
||||||
new OAuth2TokenType(OAuth2ParameterNames.CODE);
|
|
||||||
private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE =
|
|
||||||
new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
|
|
||||||
private final OAuth2AuthorizationService authorizationService;
|
private final OAuth2AuthorizationService authorizationService;
|
||||||
private final JwtEncoder jwtEncoder;
|
private final JwtEncoder jwtEncoder;
|
||||||
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
|
|
||||||
private ProviderSettings providerSettings;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters.
|
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters.
|
||||||
*
|
*
|
||||||
|
* @param registeredClientRepository the repository of registered clients
|
||||||
* @param authorizationService the authorization service
|
* @param authorizationService the authorization service
|
||||||
* @param jwtEncoder the jwt encoder
|
* @param jwtEncoder the jwt encoder
|
||||||
*/
|
*/
|
||||||
public OAuth2AuthorizationCodeAuthenticationProvider(OAuth2AuthorizationService authorizationService, JwtEncoder jwtEncoder) {
|
public OAuth2AuthorizationCodeAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
|
||||||
|
OAuth2AuthorizationService authorizationService, JwtEncoder jwtEncoder) {
|
||||||
|
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
|
||||||
Assert.notNull(authorizationService, "authorizationService cannot be null");
|
Assert.notNull(authorizationService, "authorizationService cannot be null");
|
||||||
Assert.notNull(jwtEncoder, "jwtEncoder cannot be null");
|
Assert.notNull(jwtEncoder, "jwtEncoder cannot be null");
|
||||||
|
this.registeredClientRepository = registeredClientRepository;
|
||||||
this.authorizationService = authorizationService;
|
this.authorizationService = authorizationService;
|
||||||
this.jwtEncoder = jwtEncoder;
|
this.jwtEncoder = jwtEncoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void setJwtCustomizer(OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer) {
|
|
||||||
Assert.notNull(jwtCustomizer, "jwtCustomizer cannot be null");
|
|
||||||
this.jwtCustomizer = jwtCustomizer;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Autowired(required = false)
|
|
||||||
protected void setProviderSettings(ProviderSettings providerSettings) {
|
|
||||||
this.providerSettings = providerSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication =
|
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication =
|
||||||
(OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
(OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal =
|
OAuth2ClientAuthenticationToken clientPrincipal = null;
|
||||||
getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
|
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authorizationCodeAuthentication.getPrincipal().getClass())) {
|
||||||
|
clientPrincipal = (OAuth2ClientAuthenticationToken) authorizationCodeAuthentication.getPrincipal();
|
||||||
|
}
|
||||||
|
if (clientPrincipal == null || !clientPrincipal.isAuthenticated()) {
|
||||||
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
|
||||||
|
}
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
||||||
authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
|
authorizationCodeAuthentication.getCode(), TokenType.AUTHORIZATION_CODE);
|
||||||
if (authorization == null) {
|
if (authorization == null) {
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
||||||
}
|
}
|
||||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode =
|
|
||||||
authorization.getToken(OAuth2AuthorizationCode.class);
|
|
||||||
|
|
||||||
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
|
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
|
||||||
OAuth2AuthorizationRequest.class.getName());
|
OAuth2AuthorizationAttributeNames.AUTHORIZATION_REQUEST);
|
||||||
|
|
||||||
if (!registeredClient.getClientId().equals(authorizationRequest.getClientId())) {
|
if (!registeredClient.getClientId().equals(authorizationRequest.getClientId())) {
|
||||||
if (!authorizationCode.isInvalidated()) {
|
|
||||||
// Invalidate the authorization code given that a different client is attempting to use it
|
|
||||||
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
|
|
||||||
this.authorizationService.save(authorization);
|
|
||||||
}
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -135,118 +114,44 @@ public class OAuth2AuthorizationCodeAuthenticationProvider implements Authentica
|
|||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authorizationCode.isInvalidated()) {
|
JoseHeader joseHeader = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
|
||||||
}
|
|
||||||
|
|
||||||
String issuer = this.providerSettings != null ? this.providerSettings.issuer() : null;
|
// TODO Allow configuration for issuer claim
|
||||||
Set<String> authorizedScopes = authorization.getAttribute(
|
URL issuer = null;
|
||||||
OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
|
try {
|
||||||
|
issuer = URI.create("https://oauth2.provider.com").toURL();
|
||||||
|
} catch (MalformedURLException e) { }
|
||||||
|
|
||||||
JoseHeader.Builder headersBuilder = JwtUtils.headers();
|
Instant issuedAt = Instant.now();
|
||||||
JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims(
|
Instant expiresAt = issuedAt.plus(1, ChronoUnit.HOURS); // TODO Allow configuration for access token time-to-live
|
||||||
registeredClient, issuer, authorization.getPrincipalName(),
|
Set<String> authorizedScopes = authorization.getAttribute(OAuth2AuthorizationAttributeNames.AUTHORIZED_SCOPES);
|
||||||
authorizedScopes);
|
|
||||||
|
|
||||||
// @formatter:off
|
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.withClaims()
|
||||||
JwtEncodingContext context = JwtEncodingContext.with(headersBuilder, claimsBuilder)
|
.issuer(issuer)
|
||||||
.registeredClient(registeredClient)
|
.subject(authorization.getPrincipalName())
|
||||||
.principal(authorization.getAttribute(Principal.class.getName()))
|
.audience(Collections.singletonList(registeredClient.getClientId()))
|
||||||
.authorization(authorization)
|
.issuedAt(issuedAt)
|
||||||
.authorizedScopes(authorizedScopes)
|
.expiresAt(expiresAt)
|
||||||
.tokenType(OAuth2TokenType.ACCESS_TOKEN)
|
.notBefore(issuedAt)
|
||||||
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
|
.claim(OAuth2ParameterNames.SCOPE, authorizedScopes)
|
||||||
.authorizationGrant(authorizationCodeAuthentication)
|
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.jwtCustomizer.customize(context);
|
Jwt jwt = this.jwtEncoder.encode(joseHeader, jwtClaimsSet);
|
||||||
|
|
||||||
JoseHeader headers = context.getHeaders().build();
|
|
||||||
JwtClaimsSet claims = context.getClaims().build();
|
|
||||||
Jwt jwtAccessToken = this.jwtEncoder.encode(headers, claims);
|
|
||||||
|
|
||||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
||||||
jwtAccessToken.getTokenValue(), jwtAccessToken.getIssuedAt(),
|
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaim(OAuth2ParameterNames.SCOPE));
|
||||||
jwtAccessToken.getExpiresAt(), authorizedScopes);
|
|
||||||
|
|
||||||
OAuth2RefreshToken refreshToken = null;
|
authorization = OAuth2Authorization.from(authorization)
|
||||||
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN)) {
|
.attribute(OAuth2AuthorizationAttributeNames.ACCESS_TOKEN_ATTRIBUTES, jwt)
|
||||||
refreshToken = OAuth2RefreshTokenAuthenticationProvider.generateRefreshToken(
|
.accessToken(accessToken)
|
||||||
registeredClient.getTokenSettings().refreshTokenTimeToLive());
|
|
||||||
}
|
|
||||||
|
|
||||||
Jwt jwtIdToken = null;
|
|
||||||
if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)) {
|
|
||||||
String nonce = (String) authorizationRequest.getAdditionalParameters().get(OidcParameterNames.NONCE);
|
|
||||||
|
|
||||||
headersBuilder = JwtUtils.headers();
|
|
||||||
claimsBuilder = JwtUtils.idTokenClaims(
|
|
||||||
registeredClient, issuer, authorization.getPrincipalName(), nonce);
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
context = JwtEncodingContext.with(headersBuilder, claimsBuilder)
|
|
||||||
.registeredClient(registeredClient)
|
|
||||||
.principal(authorization.getAttribute(Principal.class.getName()))
|
|
||||||
.authorization(authorization)
|
|
||||||
.authorizedScopes(authorizedScopes)
|
|
||||||
.tokenType(ID_TOKEN_TOKEN_TYPE)
|
|
||||||
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
|
|
||||||
.authorizationGrant(authorizationCodeAuthentication)
|
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.jwtCustomizer.customize(context);
|
|
||||||
|
|
||||||
headers = context.getHeaders().build();
|
|
||||||
claims = context.getClaims().build();
|
|
||||||
jwtIdToken = this.jwtEncoder.encode(headers, claims);
|
|
||||||
}
|
|
||||||
|
|
||||||
OidcIdToken idToken;
|
|
||||||
if (jwtIdToken != null) {
|
|
||||||
idToken = new OidcIdToken(jwtIdToken.getTokenValue(), jwtIdToken.getIssuedAt(),
|
|
||||||
jwtIdToken.getExpiresAt(), jwtIdToken.getClaims());
|
|
||||||
} else {
|
|
||||||
idToken = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
|
|
||||||
.token(accessToken,
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, jwtAccessToken.getClaims())
|
|
||||||
);
|
|
||||||
if (refreshToken != null) {
|
|
||||||
authorizationBuilder.refreshToken(refreshToken);
|
|
||||||
}
|
|
||||||
if (idToken != null) {
|
|
||||||
authorizationBuilder
|
|
||||||
.token(idToken,
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
|
|
||||||
}
|
|
||||||
authorization = authorizationBuilder.build();
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
// Invalidate the authorization code as it can only be used once
|
|
||||||
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
|
|
||||||
|
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
Map<String, Object> additionalParameters = Collections.emptyMap();
|
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
|
||||||
if (idToken != null) {
|
|
||||||
additionalParameters = new HashMap<>();
|
|
||||||
additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
return new OAuth2AccessTokenAuthenticationToken(
|
|
||||||
registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean supports(Class<?> authentication) {
|
public boolean supports(Class<?> authentication) {
|
||||||
return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication);
|
return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,13 +15,15 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link Authentication} implementation used for the OAuth 2.0 Authorization Code Grant.
|
* An {@link Authentication} implementation used for the OAuth 2.0 Authorization Code Grant.
|
||||||
*
|
*
|
||||||
@ -29,12 +31,16 @@ import org.springframework.util.Assert;
|
|||||||
* @author Madhu Bhat
|
* @author Madhu Bhat
|
||||||
* @author Daniel Garnier-Moiroux
|
* @author Daniel Garnier-Moiroux
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2AuthorizationGrantAuthenticationToken
|
* @see AbstractAuthenticationToken
|
||||||
* @see OAuth2AuthorizationCodeAuthenticationProvider
|
* @see OAuth2AuthorizationCodeAuthenticationProvider
|
||||||
|
* @see OAuth2ClientAuthenticationToken
|
||||||
*/
|
*/
|
||||||
public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
|
public class OAuth2AuthorizationCodeAuthenticationToken extends AbstractAuthenticationToken {
|
||||||
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
private final String code;
|
private final String code;
|
||||||
|
private final Authentication clientPrincipal;
|
||||||
private final String redirectUri;
|
private final String redirectUri;
|
||||||
|
private final Map<String, Object> additionalParameters;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided parameters.
|
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided parameters.
|
||||||
@ -46,10 +52,26 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
|
|||||||
*/
|
*/
|
||||||
public OAuth2AuthorizationCodeAuthenticationToken(String code, Authentication clientPrincipal,
|
public OAuth2AuthorizationCodeAuthenticationToken(String code, Authentication clientPrincipal,
|
||||||
@Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) {
|
@Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) {
|
||||||
super(AuthorizationGrantType.AUTHORIZATION_CODE, clientPrincipal, additionalParameters);
|
super(Collections.emptyList());
|
||||||
Assert.hasText(code, "code cannot be empty");
|
Assert.hasText(code, "code cannot be empty");
|
||||||
|
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
||||||
this.code = code;
|
this.code = code;
|
||||||
|
this.clientPrincipal = clientPrincipal;
|
||||||
this.redirectUri = redirectUri;
|
this.redirectUri = redirectUri;
|
||||||
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
|
additionalParameters != null ?
|
||||||
|
additionalParameters :
|
||||||
|
Collections.emptyMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getPrincipal() {
|
||||||
|
return this.clientPrincipal;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getCredentials() {
|
||||||
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -66,8 +88,16 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
|
|||||||
*
|
*
|
||||||
* @return the redirect uri
|
* @return the redirect uri
|
||||||
*/
|
*/
|
||||||
@Nullable
|
public @Nullable String getRedirectUri() {
|
||||||
public String getRedirectUri() {
|
|
||||||
return this.redirectUri;
|
return this.redirectUri;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the additional parameters
|
||||||
|
*
|
||||||
|
* @return the additional parameters
|
||||||
|
*/
|
||||||
|
public Map<String, Object> getAdditionalParameters() {
|
||||||
|
return this.additionalParameters;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,92 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base implementation of an {@link Authentication} representing an OAuth 2.0 Authorization Grant.
|
|
||||||
*
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see AbstractAuthenticationToken
|
|
||||||
* @see AuthorizationGrantType
|
|
||||||
* @see OAuth2ClientAuthenticationToken
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section 1.3 Authorization Grant</a>
|
|
||||||
*/
|
|
||||||
public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthenticationToken {
|
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
|
||||||
private final AuthorizationGrantType authorizationGrantType;
|
|
||||||
private final Authentication clientPrincipal;
|
|
||||||
private final Map<String, Object> additionalParameters;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sub-class constructor.
|
|
||||||
*
|
|
||||||
* @param authorizationGrantType the authorization grant type
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
* @param additionalParameters the additional parameters
|
|
||||||
*/
|
|
||||||
protected OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType authorizationGrantType,
|
|
||||||
Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
|
|
||||||
super(Collections.emptyList());
|
|
||||||
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
|
|
||||||
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
|
||||||
this.authorizationGrantType = authorizationGrantType;
|
|
||||||
this.clientPrincipal = clientPrincipal;
|
|
||||||
this.additionalParameters = Collections.unmodifiableMap(
|
|
||||||
additionalParameters != null ?
|
|
||||||
new HashMap<>(additionalParameters) :
|
|
||||||
Collections.emptyMap());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the authorization grant type.
|
|
||||||
*
|
|
||||||
* @return the authorization grant type
|
|
||||||
*/
|
|
||||||
public AuthorizationGrantType getGrantType() {
|
|
||||||
return this.authorizationGrantType;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getPrincipal() {
|
|
||||||
return this.clientPrincipal;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getCredentials() {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the additional parameters.
|
|
||||||
*
|
|
||||||
* @return the additional parameters
|
|
||||||
*/
|
|
||||||
public Map<String, Object> getAdditionalParameters() {
|
|
||||||
return this.additionalParameters;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,12 +15,6 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
@ -28,18 +22,25 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||||
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
|
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationAttributeNames;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.TokenType;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation used for authenticating an OAuth 2.0 Client.
|
* An {@link AuthenticationProvider} implementation used for authenticating an OAuth 2.0 Client.
|
||||||
*
|
*
|
||||||
@ -53,7 +54,6 @@ import org.springframework.util.StringUtils;
|
|||||||
* @see OAuth2AuthorizationService
|
* @see OAuth2AuthorizationService
|
||||||
*/
|
*/
|
||||||
public class OAuth2ClientAuthenticationProvider implements AuthenticationProvider {
|
public class OAuth2ClientAuthenticationProvider implements AuthenticationProvider {
|
||||||
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE);
|
|
||||||
private final RegisteredClientRepository registeredClientRepository;
|
private final RegisteredClientRepository registeredClientRepository;
|
||||||
private final OAuth2AuthorizationService authorizationService;
|
private final OAuth2AuthorizationService authorizationService;
|
||||||
|
|
||||||
@ -82,27 +82,15 @@ public class OAuth2ClientAuthenticationProvider implements AuthenticationProvide
|
|||||||
throwInvalidClient();
|
throwInvalidClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!registeredClient.getClientAuthenticationMethods().contains(
|
|
||||||
clientAuthentication.getClientAuthenticationMethod())) {
|
|
||||||
throwInvalidClient();
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean authenticatedCredentials = false;
|
|
||||||
|
|
||||||
if (clientAuthentication.getCredentials() != null) {
|
if (clientAuthentication.getCredentials() != null) {
|
||||||
String clientSecret = clientAuthentication.getCredentials().toString();
|
String clientSecret = clientAuthentication.getCredentials().toString();
|
||||||
// TODO Use PasswordEncoder.matches()
|
// TODO Use PasswordEncoder.matches()
|
||||||
if (!registeredClient.getClientSecret().equals(clientSecret)) {
|
if (!registeredClient.getClientSecret().equals(clientSecret)) {
|
||||||
throwInvalidClient();
|
throwInvalidClient();
|
||||||
}
|
}
|
||||||
authenticatedCredentials = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
authenticatedCredentials = authenticatedCredentials ||
|
|
||||||
authenticatePkceIfAvailable(clientAuthentication, registeredClient);
|
authenticatePkceIfAvailable(clientAuthentication, registeredClient);
|
||||||
if (!authenticatedCredentials) {
|
|
||||||
throwInvalidClient();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new OAuth2ClientAuthenticationToken(registeredClient);
|
return new OAuth2ClientAuthenticationToken(registeredClient);
|
||||||
}
|
}
|
||||||
@ -112,39 +100,36 @@ public class OAuth2ClientAuthenticationProvider implements AuthenticationProvide
|
|||||||
return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication);
|
return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean authenticatePkceIfAvailable(OAuth2ClientAuthenticationToken clientAuthentication,
|
private void authenticatePkceIfAvailable(OAuth2ClientAuthenticationToken clientAuthentication,
|
||||||
RegisteredClient registeredClient) {
|
RegisteredClient registeredClient) {
|
||||||
|
|
||||||
Map<String, Object> parameters = clientAuthentication.getAdditionalParameters();
|
Map<String, Object> parameters = clientAuthentication.getAdditionalParameters();
|
||||||
if (CollectionUtils.isEmpty(parameters) || !authorizationCodeGrant(parameters)) {
|
if (CollectionUtils.isEmpty(parameters) || !authorizationCodeGrant(parameters)) {
|
||||||
return false;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
||||||
(String) parameters.get(OAuth2ParameterNames.CODE),
|
(String) parameters.get(OAuth2ParameterNames.CODE),
|
||||||
AUTHORIZATION_CODE_TOKEN_TYPE);
|
TokenType.AUTHORIZATION_CODE);
|
||||||
if (authorization == null) {
|
if (authorization == null) {
|
||||||
throwInvalidClient();
|
throwInvalidClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
|
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
|
||||||
OAuth2AuthorizationRequest.class.getName());
|
OAuth2AuthorizationAttributeNames.AUTHORIZATION_REQUEST);
|
||||||
|
|
||||||
String codeChallenge = (String) authorizationRequest.getAdditionalParameters()
|
String codeChallenge = (String) authorizationRequest.getAdditionalParameters()
|
||||||
.get(PkceParameterNames.CODE_CHALLENGE);
|
.get(PkceParameterNames.CODE_CHALLENGE);
|
||||||
if (!StringUtils.hasText(codeChallenge) &&
|
if (StringUtils.hasText(codeChallenge)) {
|
||||||
registeredClient.getClientSettings().requireProofKey()) {
|
|
||||||
throwInvalidClient();
|
|
||||||
}
|
|
||||||
|
|
||||||
String codeChallengeMethod = (String) authorizationRequest.getAdditionalParameters()
|
String codeChallengeMethod = (String) authorizationRequest.getAdditionalParameters()
|
||||||
.get(PkceParameterNames.CODE_CHALLENGE_METHOD);
|
.get(PkceParameterNames.CODE_CHALLENGE_METHOD);
|
||||||
String codeVerifier = (String) parameters.get(PkceParameterNames.CODE_VERIFIER);
|
String codeVerifier = (String) parameters.get(PkceParameterNames.CODE_VERIFIER);
|
||||||
if (!codeVerifierValid(codeVerifier, codeChallenge, codeChallengeMethod)) {
|
if (!codeVerifierValid(codeVerifier, codeChallenge, codeChallengeMethod)) {
|
||||||
throwInvalidClient();
|
throwInvalidClient();
|
||||||
}
|
}
|
||||||
|
} else if (registeredClient.getClientSettings().requireProofKey()) {
|
||||||
return true;
|
throwInvalidClient();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean authorizationCodeGrant(Map<String, Object> parameters) {
|
private static boolean authorizationCodeGrant(Map<String, Object> parameters) {
|
||||||
|
@ -18,8 +18,7 @@ package org.springframework.security.oauth2.server.authorization.authentication;
|
|||||||
import org.springframework.lang.Nullable;
|
import org.springframework.lang.Nullable;
|
||||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
@ -31,7 +30,6 @@ import java.util.Map;
|
|||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Patryk Kostrzewa
|
* @author Patryk Kostrzewa
|
||||||
* @author Anoop Garlapati
|
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see AbstractAuthenticationToken
|
* @see AbstractAuthenticationToken
|
||||||
* @see RegisteredClient
|
* @see RegisteredClient
|
||||||
@ -41,7 +39,6 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
|
|||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
private String clientId;
|
private String clientId;
|
||||||
private String clientSecret;
|
private String clientSecret;
|
||||||
private ClientAuthenticationMethod clientAuthenticationMethod;
|
|
||||||
private Map<String, Object> additionalParameters;
|
private Map<String, Object> additionalParameters;
|
||||||
private RegisteredClient registeredClient;
|
private RegisteredClient registeredClient;
|
||||||
|
|
||||||
@ -50,17 +47,13 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
|
|||||||
*
|
*
|
||||||
* @param clientId the client identifier
|
* @param clientId the client identifier
|
||||||
* @param clientSecret the client secret
|
* @param clientSecret the client secret
|
||||||
* @param clientAuthenticationMethod the authentication method used by the client
|
|
||||||
* @param additionalParameters the additional parameters
|
* @param additionalParameters the additional parameters
|
||||||
*/
|
*/
|
||||||
public OAuth2ClientAuthenticationToken(String clientId, String clientSecret,
|
public OAuth2ClientAuthenticationToken(String clientId, String clientSecret,
|
||||||
ClientAuthenticationMethod clientAuthenticationMethod,
|
|
||||||
@Nullable Map<String, Object> additionalParameters) {
|
@Nullable Map<String, Object> additionalParameters) {
|
||||||
this(clientId, additionalParameters);
|
this(clientId, additionalParameters);
|
||||||
Assert.hasText(clientSecret, "clientSecret cannot be empty");
|
Assert.hasText(clientSecret, "clientSecret cannot be empty");
|
||||||
Assert.notNull(clientAuthenticationMethod, "clientAuthenticationMethod cannot be null");
|
|
||||||
this.clientSecret = clientSecret;
|
this.clientSecret = clientSecret;
|
||||||
this.clientAuthenticationMethod = clientAuthenticationMethod;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -76,7 +69,6 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
|
|||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
this.additionalParameters = additionalParameters != null ?
|
this.additionalParameters = additionalParameters != null ?
|
||||||
Collections.unmodifiableMap(additionalParameters) : null;
|
Collections.unmodifiableMap(additionalParameters) : null;
|
||||||
this.clientAuthenticationMethod = ClientAuthenticationMethod.NONE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -120,13 +112,4 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
|
|||||||
public @Nullable RegisteredClient getRegisteredClient() {
|
public @Nullable RegisteredClient getRegisteredClient() {
|
||||||
return this.registeredClient;
|
return this.registeredClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the {@link ClientAuthenticationMethod client authentication method}.
|
|
||||||
*
|
|
||||||
* @return the {@link ClientAuthenticationMethod}
|
|
||||||
*/
|
|
||||||
public @Nullable ClientAuthenticationMethod getClientAuthenticationMethod() {
|
|
||||||
return this.clientAuthenticationMethod;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,55 +15,51 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||||
import org.springframework.security.oauth2.jwt.JoseHeader;
|
import org.springframework.security.oauth2.jose.JoseHeader;
|
||||||
|
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
import org.springframework.security.oauth2.jwt.Jwt;
|
||||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||||
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationAttributeNames;
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
|
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials Grant.
|
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials Grant.
|
||||||
*
|
*
|
||||||
* @author Alexey Nesterov
|
* @author Alexey Nesterov
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2ClientCredentialsAuthenticationToken
|
* @see OAuth2ClientCredentialsAuthenticationToken
|
||||||
* @see OAuth2AccessTokenAuthenticationToken
|
* @see OAuth2AccessTokenAuthenticationToken
|
||||||
* @see OAuth2AuthorizationService
|
* @see OAuth2AuthorizationService
|
||||||
* @see JwtEncoder
|
* @see JwtEncoder
|
||||||
* @see OAuth2TokenCustomizer
|
|
||||||
* @see JwtEncodingContext
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4">Section 4.4 Client Credentials Grant</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4">Section 4.4 Client Credentials Grant</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4.2">Section 4.4.2 Access Token Request</a>
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4.2">Section 4.4.2 Access Token Request</a>
|
||||||
*/
|
*/
|
||||||
public class OAuth2ClientCredentialsAuthenticationProvider implements AuthenticationProvider {
|
public class OAuth2ClientCredentialsAuthenticationProvider implements AuthenticationProvider {
|
||||||
private final OAuth2AuthorizationService authorizationService;
|
private final OAuth2AuthorizationService authorizationService;
|
||||||
private final JwtEncoder jwtEncoder;
|
private final JwtEncoder jwtEncoder;
|
||||||
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
|
|
||||||
private ProviderSettings providerSettings;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the provided parameters.
|
* Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the provided parameters.
|
||||||
@ -79,30 +75,21 @@ public class OAuth2ClientCredentialsAuthenticationProvider implements Authentica
|
|||||||
this.jwtEncoder = jwtEncoder;
|
this.jwtEncoder = jwtEncoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void setJwtCustomizer(OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer) {
|
|
||||||
Assert.notNull(jwtCustomizer, "jwtCustomizer cannot be null");
|
|
||||||
this.jwtCustomizer = jwtCustomizer;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Autowired(required = false)
|
|
||||||
protected void setProviderSettings(ProviderSettings providerSettings) {
|
|
||||||
this.providerSettings = providerSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication =
|
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication =
|
||||||
(OAuth2ClientCredentialsAuthenticationToken) authentication;
|
(OAuth2ClientCredentialsAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal =
|
OAuth2ClientAuthenticationToken clientPrincipal = null;
|
||||||
getAuthenticatedClientElseThrowInvalidClient(clientCredentialsAuthentication);
|
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(clientCredentialsAuthentication.getPrincipal().getClass())) {
|
||||||
|
clientPrincipal = (OAuth2ClientAuthenticationToken) clientCredentialsAuthentication.getPrincipal();
|
||||||
|
}
|
||||||
|
if (clientPrincipal == null || !clientPrincipal.isAuthenticated()) {
|
||||||
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
|
||||||
|
}
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.CLIENT_CREDENTIALS)) {
|
Set<String> scopes = registeredClient.getScopes(); // Default to configured scopes
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT));
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> authorizedScopes = registeredClient.getScopes(); // Default to configured scopes
|
|
||||||
if (!CollectionUtils.isEmpty(clientCredentialsAuthentication.getScopes())) {
|
if (!CollectionUtils.isEmpty(clientCredentialsAuthentication.getScopes())) {
|
||||||
Set<String> unauthorizedScopes = clientCredentialsAuthentication.getScopes().stream()
|
Set<String> unauthorizedScopes = clientCredentialsAuthentication.getScopes().stream()
|
||||||
.filter(requestedScope -> !registeredClient.getScopes().contains(requestedScope))
|
.filter(requestedScope -> !registeredClient.getScopes().contains(requestedScope))
|
||||||
@ -110,47 +97,40 @@ public class OAuth2ClientCredentialsAuthenticationProvider implements Authentica
|
|||||||
if (!CollectionUtils.isEmpty(unauthorizedScopes)) {
|
if (!CollectionUtils.isEmpty(unauthorizedScopes)) {
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE));
|
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE));
|
||||||
}
|
}
|
||||||
authorizedScopes = new LinkedHashSet<>(clientCredentialsAuthentication.getScopes());
|
scopes = new LinkedHashSet<>(clientCredentialsAuthentication.getScopes());
|
||||||
}
|
}
|
||||||
|
|
||||||
String issuer = this.providerSettings != null ? this.providerSettings.issuer() : null;
|
JoseHeader joseHeader = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
|
||||||
|
|
||||||
JoseHeader.Builder headersBuilder = JwtUtils.headers();
|
// TODO Allow configuration for issuer claim
|
||||||
JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims(
|
URL issuer = null;
|
||||||
registeredClient, issuer, clientPrincipal.getName(), authorizedScopes);
|
try {
|
||||||
|
issuer = URI.create("https://oauth2.provider.com").toURL();
|
||||||
|
} catch (MalformedURLException e) { }
|
||||||
|
|
||||||
// @formatter:off
|
Instant issuedAt = Instant.now();
|
||||||
JwtEncodingContext context = JwtEncodingContext.with(headersBuilder, claimsBuilder)
|
Instant expiresAt = issuedAt.plus(1, ChronoUnit.HOURS); // TODO Allow configuration for access token time-to-live
|
||||||
.registeredClient(registeredClient)
|
|
||||||
.principal(clientPrincipal)
|
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.withClaims()
|
||||||
.authorizedScopes(authorizedScopes)
|
.issuer(issuer)
|
||||||
.tokenType(OAuth2TokenType.ACCESS_TOKEN)
|
.subject(clientPrincipal.getName())
|
||||||
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
|
.audience(Collections.singletonList(registeredClient.getClientId()))
|
||||||
.authorizationGrant(clientCredentialsAuthentication)
|
.issuedAt(issuedAt)
|
||||||
|
.expiresAt(expiresAt)
|
||||||
|
.notBefore(issuedAt)
|
||||||
|
.claim(OAuth2ParameterNames.SCOPE, scopes)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.jwtCustomizer.customize(context);
|
Jwt jwt = this.jwtEncoder.encode(joseHeader, jwtClaimsSet);
|
||||||
|
|
||||||
JoseHeader headers = context.getHeaders().build();
|
|
||||||
JwtClaimsSet claims = context.getClaims().build();
|
|
||||||
Jwt jwtAccessToken = this.jwtEncoder.encode(headers, claims);
|
|
||||||
|
|
||||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
||||||
jwtAccessToken.getTokenValue(), jwtAccessToken.getIssuedAt(),
|
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), scopes);
|
||||||
jwtAccessToken.getExpiresAt(), authorizedScopes);
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(registeredClient)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(registeredClient)
|
||||||
|
.attribute(OAuth2AuthorizationAttributeNames.ACCESS_TOKEN_ATTRIBUTES, jwt)
|
||||||
.principalName(clientPrincipal.getName())
|
.principalName(clientPrincipal.getName())
|
||||||
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
|
.accessToken(accessToken)
|
||||||
.token(accessToken,
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, jwtAccessToken.getClaims()))
|
|
||||||
.attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes)
|
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
|
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,38 +15,60 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
import java.util.Collections;
|
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link Authentication} implementation used for the OAuth 2.0 Client Credentials Grant.
|
* An {@link Authentication} implementation used for the OAuth 2.0 Client Credentials Grant.
|
||||||
*
|
*
|
||||||
* @author Alexey Nesterov
|
* @author Alexey Nesterov
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
* @see OAuth2AuthorizationGrantAuthenticationToken
|
* @see AbstractAuthenticationToken
|
||||||
* @see OAuth2ClientCredentialsAuthenticationProvider
|
* @see OAuth2ClientCredentialsAuthenticationProvider
|
||||||
|
* @see OAuth2ClientAuthenticationToken
|
||||||
*/
|
*/
|
||||||
public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
|
public class OAuth2ClientCredentialsAuthenticationToken extends AbstractAuthenticationToken {
|
||||||
|
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
||||||
|
private final Authentication clientPrincipal;
|
||||||
private final Set<String> scopes;
|
private final Set<String> scopes;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided parameters.
|
* Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided parameters.
|
||||||
*
|
*
|
||||||
* @param clientPrincipal the authenticated client principal
|
* @param clientPrincipal the authenticated client principal
|
||||||
* @param scopes the requested scope(s)
|
|
||||||
* @param additionalParameters the additional parameters
|
|
||||||
*/
|
*/
|
||||||
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal,
|
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal) {
|
||||||
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
|
this(clientPrincipal, Collections.emptySet());
|
||||||
super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, additionalParameters);
|
}
|
||||||
this.scopes = Collections.unmodifiableSet(
|
|
||||||
scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
|
/**
|
||||||
|
* Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided parameters.
|
||||||
|
*
|
||||||
|
* @param clientPrincipal the authenticated client principal
|
||||||
|
* @param scopes the requested scope(s)
|
||||||
|
*/
|
||||||
|
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, Set<String> scopes) {
|
||||||
|
super(Collections.emptyList());
|
||||||
|
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
||||||
|
Assert.notNull(scopes, "scopes cannot be null");
|
||||||
|
this.clientPrincipal = clientPrincipal;
|
||||||
|
this.scopes = Collections.unmodifiableSet(new LinkedHashSet<>(scopes));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getPrincipal() {
|
||||||
|
return this.clientPrincipal;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getCredentials() {
|
||||||
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,207 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.AuthenticationException;
|
|
||||||
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
|
|
||||||
import org.springframework.security.crypto.keygen.StringKeyGenerator;
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken2;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2TokenType;
|
|
||||||
import org.springframework.security.oauth2.jwt.JoseHeader;
|
|
||||||
import org.springframework.security.oauth2.jwt.Jwt;
|
|
||||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
|
||||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Refresh Token Grant.
|
|
||||||
*
|
|
||||||
* @author Alexey Nesterov
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see OAuth2RefreshTokenAuthenticationToken
|
|
||||||
* @see OAuth2AccessTokenAuthenticationToken
|
|
||||||
* @see OAuth2AuthorizationService
|
|
||||||
* @see JwtEncoder
|
|
||||||
* @see OAuth2TokenCustomizer
|
|
||||||
* @see JwtEncodingContext
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.5">Section 1.5 Refresh Token Grant</a>
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-6">Section 6 Refreshing an Access Token</a>
|
|
||||||
*/
|
|
||||||
public class OAuth2RefreshTokenAuthenticationProvider implements AuthenticationProvider {
|
|
||||||
private static final StringKeyGenerator TOKEN_GENERATOR = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
|
|
||||||
private final OAuth2AuthorizationService authorizationService;
|
|
||||||
private final JwtEncoder jwtEncoder;
|
|
||||||
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
|
|
||||||
private ProviderSettings providerSettings;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2RefreshTokenAuthenticationProvider} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param authorizationService the authorization service
|
|
||||||
* @param jwtEncoder the jwt encoder
|
|
||||||
*/
|
|
||||||
public OAuth2RefreshTokenAuthenticationProvider(OAuth2AuthorizationService authorizationService,
|
|
||||||
JwtEncoder jwtEncoder) {
|
|
||||||
Assert.notNull(authorizationService, "authorizationService cannot be null");
|
|
||||||
Assert.notNull(jwtEncoder, "jwtEncoder cannot be null");
|
|
||||||
this.authorizationService = authorizationService;
|
|
||||||
this.jwtEncoder = jwtEncoder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public final void setJwtCustomizer(OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer) {
|
|
||||||
Assert.notNull(jwtCustomizer, "jwtCustomizer cannot be null");
|
|
||||||
this.jwtCustomizer = jwtCustomizer;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Autowired(required = false)
|
|
||||||
protected void setProviderSettings(ProviderSettings providerSettings) {
|
|
||||||
this.providerSettings = providerSettings;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
|
||||||
OAuth2RefreshTokenAuthenticationToken refreshTokenAuthentication =
|
|
||||||
(OAuth2RefreshTokenAuthenticationToken) authentication;
|
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal =
|
|
||||||
getAuthenticatedClientElseThrowInvalidClient(refreshTokenAuthentication);
|
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
|
||||||
refreshTokenAuthentication.getRefreshToken(), OAuth2TokenType.REFRESH_TOKEN);
|
|
||||||
if (authorization == null) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN)) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT));
|
|
||||||
}
|
|
||||||
|
|
||||||
OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = authorization.getRefreshToken();
|
|
||||||
Instant refreshTokenExpiresAt = refreshToken.getToken().getExpiresAt();
|
|
||||||
if (refreshTokenExpiresAt.isBefore(Instant.now())) {
|
|
||||||
// As per https://tools.ietf.org/html/rfc6749#section-5.2
|
|
||||||
// invalid_grant: The provided authorization grant (e.g., authorization code,
|
|
||||||
// resource owner credentials) or refresh token is invalid, expired, revoked [...].
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
|
||||||
}
|
|
||||||
|
|
||||||
// As per https://tools.ietf.org/html/rfc6749#section-6
|
|
||||||
// The requested scope MUST NOT include any scope not originally granted by the resource owner,
|
|
||||||
// and if omitted is treated as equal to the scope originally granted by the resource owner.
|
|
||||||
Set<String> scopes = refreshTokenAuthentication.getScopes();
|
|
||||||
Set<String> authorizedScopes = authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
|
|
||||||
if (!authorizedScopes.containsAll(scopes)) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE));
|
|
||||||
}
|
|
||||||
if (scopes.isEmpty()) {
|
|
||||||
scopes = authorizedScopes;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (refreshToken.isInvalidated()) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT));
|
|
||||||
}
|
|
||||||
|
|
||||||
String issuer = this.providerSettings != null ? this.providerSettings.issuer() : null;
|
|
||||||
|
|
||||||
JoseHeader.Builder headersBuilder = JwtUtils.headers();
|
|
||||||
JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims(
|
|
||||||
registeredClient, issuer, authorization.getPrincipalName(), scopes);
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
JwtEncodingContext context = JwtEncodingContext.with(headersBuilder, claimsBuilder)
|
|
||||||
.registeredClient(registeredClient)
|
|
||||||
.principal(authorization.getAttribute(Principal.class.getName()))
|
|
||||||
.authorization(authorization)
|
|
||||||
.authorizedScopes(authorizedScopes)
|
|
||||||
.tokenType(OAuth2TokenType.ACCESS_TOKEN)
|
|
||||||
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
|
|
||||||
.authorizationGrant(refreshTokenAuthentication)
|
|
||||||
.build();
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.jwtCustomizer.customize(context);
|
|
||||||
|
|
||||||
JoseHeader headers = context.getHeaders().build();
|
|
||||||
JwtClaimsSet claims = context.getClaims().build();
|
|
||||||
Jwt jwtAccessToken = this.jwtEncoder.encode(headers, claims);
|
|
||||||
|
|
||||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
|
||||||
jwtAccessToken.getTokenValue(), jwtAccessToken.getIssuedAt(),
|
|
||||||
jwtAccessToken.getExpiresAt(), scopes);
|
|
||||||
|
|
||||||
TokenSettings tokenSettings = registeredClient.getTokenSettings();
|
|
||||||
|
|
||||||
OAuth2RefreshToken currentRefreshToken = refreshToken.getToken();
|
|
||||||
if (!tokenSettings.reuseRefreshTokens()) {
|
|
||||||
currentRefreshToken = generateRefreshToken(tokenSettings.refreshTokenTimeToLive());
|
|
||||||
}
|
|
||||||
|
|
||||||
// @formatter:off
|
|
||||||
authorization = OAuth2Authorization.from(authorization)
|
|
||||||
.token(accessToken,
|
|
||||||
(metadata) ->
|
|
||||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, jwtAccessToken.getClaims()))
|
|
||||||
.refreshToken(currentRefreshToken)
|
|
||||||
.build();
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
this.authorizationService.save(authorization);
|
|
||||||
|
|
||||||
return new OAuth2AccessTokenAuthenticationToken(
|
|
||||||
registeredClient, clientPrincipal, accessToken, currentRefreshToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean supports(Class<?> authentication) {
|
|
||||||
return OAuth2RefreshTokenAuthenticationToken.class.isAssignableFrom(authentication);
|
|
||||||
}
|
|
||||||
|
|
||||||
static OAuth2RefreshToken generateRefreshToken(Duration tokenTimeToLive) {
|
|
||||||
Instant issuedAt = Instant.now();
|
|
||||||
Instant expiresAt = issuedAt.plus(tokenTimeToLive);
|
|
||||||
return new OAuth2RefreshToken2(TOKEN_GENERATOR.generateKey(), issuedAt, expiresAt);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,74 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An {@link Authentication} implementation used for the OAuth 2.0 Refresh Token Grant.
|
|
||||||
*
|
|
||||||
* @author Alexey Nesterov
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see OAuth2AuthorizationGrantAuthenticationToken
|
|
||||||
* @see OAuth2RefreshTokenAuthenticationProvider
|
|
||||||
*/
|
|
||||||
public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
|
|
||||||
private final String refreshToken;
|
|
||||||
private final Set<String> scopes;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2RefreshTokenAuthenticationToken} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param refreshToken the refresh token
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
* @param scopes the requested scope(s)
|
|
||||||
* @param additionalParameters the additional parameters
|
|
||||||
*/
|
|
||||||
public OAuth2RefreshTokenAuthenticationToken(String refreshToken, Authentication clientPrincipal,
|
|
||||||
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
|
|
||||||
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
|
|
||||||
Assert.hasText(refreshToken, "refreshToken cannot be empty");
|
|
||||||
this.refreshToken = refreshToken;
|
|
||||||
this.scopes = Collections.unmodifiableSet(
|
|
||||||
scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the refresh token.
|
|
||||||
*
|
|
||||||
* @return the refresh token
|
|
||||||
*/
|
|
||||||
public String getRefreshToken() {
|
|
||||||
return this.refreshToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the requested scope(s).
|
|
||||||
*
|
|
||||||
* @return the requested scope(s), or an empty {@code Set} if not available
|
|
||||||
*/
|
|
||||||
public Set<String> getScopes() {
|
|
||||||
return this.scopes;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,86 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020-2021 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.AuthenticationProvider;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.AuthenticationException;
|
|
||||||
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
|
||||||
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Revocation.
|
|
||||||
*
|
|
||||||
* @author Vivek Babu
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see OAuth2TokenRevocationAuthenticationToken
|
|
||||||
* @see OAuth2AuthorizationService
|
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2.1">Section 2.1 Revocation Request</a>
|
|
||||||
*/
|
|
||||||
public class OAuth2TokenRevocationAuthenticationProvider implements AuthenticationProvider {
|
|
||||||
private final OAuth2AuthorizationService authorizationService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2TokenRevocationAuthenticationProvider} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param authorizationService the authorization service
|
|
||||||
*/
|
|
||||||
public OAuth2TokenRevocationAuthenticationProvider(OAuth2AuthorizationService authorizationService) {
|
|
||||||
Assert.notNull(authorizationService, "authorizationService cannot be null");
|
|
||||||
this.authorizationService = authorizationService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
|
||||||
OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication =
|
|
||||||
(OAuth2TokenRevocationAuthenticationToken) authentication;
|
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal =
|
|
||||||
getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication);
|
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
|
||||||
tokenRevocationAuthentication.getToken(), null);
|
|
||||||
if (authorization == null) {
|
|
||||||
// Return the authentication request when token not found
|
|
||||||
return tokenRevocationAuthentication;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
|
|
||||||
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
|
|
||||||
}
|
|
||||||
|
|
||||||
OAuth2Authorization.Token<AbstractOAuth2Token> token = authorization.getToken(tokenRevocationAuthentication.getToken());
|
|
||||||
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, token.getToken());
|
|
||||||
this.authorizationService.save(authorization);
|
|
||||||
|
|
||||||
return new OAuth2TokenRevocationAuthenticationToken(token.getToken(), clientPrincipal);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean supports(Class<?> authentication) {
|
|
||||||
return OAuth2TokenRevocationAuthenticationToken.class.isAssignableFrom(authentication);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,104 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An {@link Authentication} implementation used for OAuth 2.0 Token Revocation.
|
|
||||||
*
|
|
||||||
* @author Vivek Babu
|
|
||||||
* @author Joe Grandja
|
|
||||||
* @since 0.0.3
|
|
||||||
* @see AbstractAuthenticationToken
|
|
||||||
* @see OAuth2TokenRevocationAuthenticationProvider
|
|
||||||
*/
|
|
||||||
public class OAuth2TokenRevocationAuthenticationToken extends AbstractAuthenticationToken {
|
|
||||||
private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
|
|
||||||
private final String token;
|
|
||||||
private final Authentication clientPrincipal;
|
|
||||||
private final String tokenTypeHint;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2TokenRevocationAuthenticationToken} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param token the token
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
* @param tokenTypeHint the token type hint
|
|
||||||
*/
|
|
||||||
public OAuth2TokenRevocationAuthenticationToken(String token,
|
|
||||||
Authentication clientPrincipal, @Nullable String tokenTypeHint) {
|
|
||||||
super(Collections.emptyList());
|
|
||||||
Assert.hasText(token, "token cannot be empty");
|
|
||||||
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
|
||||||
this.token = token;
|
|
||||||
this.clientPrincipal = clientPrincipal;
|
|
||||||
this.tokenTypeHint = tokenTypeHint;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs an {@code OAuth2TokenRevocationAuthenticationToken} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param revokedToken the revoked token
|
|
||||||
* @param clientPrincipal the authenticated client principal
|
|
||||||
*/
|
|
||||||
public OAuth2TokenRevocationAuthenticationToken(AbstractOAuth2Token revokedToken,
|
|
||||||
Authentication clientPrincipal) {
|
|
||||||
super(Collections.emptyList());
|
|
||||||
Assert.notNull(revokedToken, "revokedToken cannot be null");
|
|
||||||
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
|
|
||||||
this.token = revokedToken.getTokenValue();
|
|
||||||
this.clientPrincipal = clientPrincipal;
|
|
||||||
this.tokenTypeHint = null;
|
|
||||||
setAuthenticated(true); // Indicates that the token was authenticated and revoked
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getPrincipal() {
|
|
||||||
return this.clientPrincipal;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object getCredentials() {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the token.
|
|
||||||
*
|
|
||||||
* @return the token
|
|
||||||
*/
|
|
||||||
public String getToken() {
|
|
||||||
return this.token;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the token type hint.
|
|
||||||
*
|
|
||||||
* @return the token type hint
|
|
||||||
*/
|
|
||||||
@Nullable
|
|
||||||
public String getTokenTypeHint() {
|
|
||||||
return this.tokenTypeHint;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,20 +15,16 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.client;
|
package org.springframework.security.oauth2.server.authorization.client;
|
||||||
|
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A {@link RegisteredClientRepository} that stores {@link RegisteredClient}(s) in-memory.
|
* A {@link RegisteredClientRepository} that stores {@link RegisteredClient}(s) in-memory.
|
||||||
*
|
*
|
||||||
* <p>
|
|
||||||
* <b>NOTE:</b> This implementation is recommended ONLY to be used during development/testing.
|
|
||||||
*
|
|
||||||
* @author Anoop Garlapati
|
* @author Anoop Garlapati
|
||||||
* @see RegisteredClientRepository
|
* @see RegisteredClientRepository
|
||||||
* @see RegisteredClient
|
* @see RegisteredClient
|
||||||
@ -75,14 +71,12 @@ public final class InMemoryRegisteredClientRepository implements RegisteredClien
|
|||||||
this.clientIdRegistrationMap = clientIdRegistrationMapResult;
|
this.clientIdRegistrationMap = clientIdRegistrationMapResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
@Override
|
@Override
|
||||||
public RegisteredClient findById(String id) {
|
public RegisteredClient findById(String id) {
|
||||||
Assert.hasText(id, "id cannot be empty");
|
Assert.hasText(id, "id cannot be empty");
|
||||||
return this.idRegistrationMap.get(id);
|
return this.idRegistrationMap.get(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
@Override
|
@Override
|
||||||
public RegisteredClient findByClientId(String clientId) {
|
public RegisteredClient findByClientId(String clientId) {
|
||||||
Assert.hasText(clientId, "clientId cannot be empty");
|
Assert.hasText(clientId, "clientId cannot be empty");
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,23 +15,22 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.client;
|
package org.springframework.security.oauth2.server.authorization.client;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||||
import org.springframework.security.oauth2.core.Version;
|
|
||||||
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
|
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
|
||||||
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
|
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A representation of a client registration with an OAuth 2.0 Authorization Server.
|
* A representation of a client registration with an OAuth 2.0 Authorization Server.
|
||||||
*
|
*
|
||||||
@ -83,7 +82,8 @@ public class RegisteredClient implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the {@link ClientAuthenticationMethod authentication method(s)} that the client may use.
|
* Returns the {@link ClientAuthenticationMethod authentication method(s)} used
|
||||||
|
* when authenticating the client with the authorization server.
|
||||||
*
|
*
|
||||||
* @return the {@code Set} of {@link ClientAuthenticationMethod authentication method(s)}
|
* @return the {@code Set} of {@link ClientAuthenticationMethod authentication method(s)}
|
||||||
*/
|
*/
|
||||||
@ -110,7 +110,7 @@ public class RegisteredClient implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the scope(s) that the client may use.
|
* Returns the scope(s) used by the client.
|
||||||
*
|
*
|
||||||
* @return the {@code Set} of scope(s)
|
* @return the {@code Set} of scope(s)
|
||||||
*/
|
*/
|
||||||
@ -136,33 +136,6 @@ public class RegisteredClient implements Serializable {
|
|||||||
return this.tokenSettings;
|
return this.tokenSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (obj == null || getClass() != obj.getClass()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
RegisteredClient that = (RegisteredClient) obj;
|
|
||||||
return Objects.equals(this.id, that.id) &&
|
|
||||||
Objects.equals(this.clientId, that.clientId) &&
|
|
||||||
Objects.equals(this.clientSecret, that.clientSecret) &&
|
|
||||||
Objects.equals(this.clientAuthenticationMethods, that.clientAuthenticationMethods) &&
|
|
||||||
Objects.equals(this.authorizationGrantTypes, that.authorizationGrantTypes) &&
|
|
||||||
Objects.equals(this.redirectUris, that.redirectUris) &&
|
|
||||||
Objects.equals(this.scopes, that.scopes) &&
|
|
||||||
Objects.equals(this.clientSettings.settings(), that.getClientSettings().settings()) &&
|
|
||||||
Objects.equals(this.tokenSettings.settings(), that.tokenSettings.settings());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(this.id, this.clientId, this.clientSecret,
|
|
||||||
this.clientAuthenticationMethods, this.authorizationGrantTypes, this.redirectUris,
|
|
||||||
this.scopes, this.clientSettings.settings(), this.tokenSettings.settings());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "RegisteredClient{" +
|
return "RegisteredClient{" +
|
||||||
@ -172,8 +145,6 @@ public class RegisteredClient implements Serializable {
|
|||||||
", authorizationGrantTypes=" + this.authorizationGrantTypes +
|
", authorizationGrantTypes=" + this.authorizationGrantTypes +
|
||||||
", redirectUris=" + this.redirectUris +
|
", redirectUris=" + this.redirectUris +
|
||||||
", scopes=" + this.scopes +
|
", scopes=" + this.scopes +
|
||||||
", clientSettings=" + this.clientSettings.settings() +
|
|
||||||
", tokenSettings=" + this.tokenSettings.settings() +
|
|
||||||
'}';
|
'}';
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -189,12 +160,12 @@ public class RegisteredClient implements Serializable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a new {@link Builder}, initialized with the values from the provided {@link RegisteredClient}.
|
* Returns a new {@link Builder}, initialized with the provided {@link RegisteredClient}.
|
||||||
*
|
*
|
||||||
* @param registeredClient the {@link RegisteredClient} used for initializing the {@link Builder}
|
* @param registeredClient the {@link RegisteredClient} to copy from
|
||||||
* @return the {@link Builder}
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public static Builder from(RegisteredClient registeredClient) {
|
public static Builder withRegisteredClient(RegisteredClient registeredClient) {
|
||||||
Assert.notNull(registeredClient, "registeredClient cannot be null");
|
Assert.notNull(registeredClient, "registeredClient cannot be null");
|
||||||
return new Builder(registeredClient);
|
return new Builder(registeredClient);
|
||||||
}
|
}
|
||||||
@ -207,10 +178,10 @@ public class RegisteredClient implements Serializable {
|
|||||||
private String id;
|
private String id;
|
||||||
private String clientId;
|
private String clientId;
|
||||||
private String clientSecret;
|
private String clientSecret;
|
||||||
private Set<ClientAuthenticationMethod> clientAuthenticationMethods = new HashSet<>();
|
private Set<ClientAuthenticationMethod> clientAuthenticationMethods = new LinkedHashSet<>();
|
||||||
private Set<AuthorizationGrantType> authorizationGrantTypes = new HashSet<>();
|
private Set<AuthorizationGrantType> authorizationGrantTypes = new LinkedHashSet<>();
|
||||||
private Set<String> redirectUris = new HashSet<>();
|
private Set<String> redirectUris = new LinkedHashSet<>();
|
||||||
private Set<String> scopes = new HashSet<>();
|
private Set<String> scopes = new LinkedHashSet<>();
|
||||||
private ClientSettings clientSettings = new ClientSettings();
|
private ClientSettings clientSettings = new ClientSettings();
|
||||||
private TokenSettings tokenSettings = new TokenSettings();
|
private TokenSettings tokenSettings = new TokenSettings();
|
||||||
|
|
||||||
@ -414,16 +385,13 @@ public class RegisteredClient implements Serializable {
|
|||||||
registeredClient.id = this.id;
|
registeredClient.id = this.id;
|
||||||
registeredClient.clientId = this.clientId;
|
registeredClient.clientId = this.clientId;
|
||||||
registeredClient.clientSecret = this.clientSecret;
|
registeredClient.clientSecret = this.clientSecret;
|
||||||
registeredClient.clientAuthenticationMethods = Collections.unmodifiableSet(
|
registeredClient.clientAuthenticationMethods =
|
||||||
new HashSet<>(this.clientAuthenticationMethods));
|
Collections.unmodifiableSet(this.clientAuthenticationMethods);
|
||||||
registeredClient.authorizationGrantTypes = Collections.unmodifiableSet(
|
registeredClient.authorizationGrantTypes = Collections.unmodifiableSet(this.authorizationGrantTypes);
|
||||||
new HashSet<>(this.authorizationGrantTypes));
|
registeredClient.redirectUris = Collections.unmodifiableSet(this.redirectUris);
|
||||||
registeredClient.redirectUris = Collections.unmodifiableSet(
|
registeredClient.scopes = Collections.unmodifiableSet(this.scopes);
|
||||||
new HashSet<>(this.redirectUris));
|
registeredClient.clientSettings = this.clientSettings;
|
||||||
registeredClient.scopes = Collections.unmodifiableSet(
|
registeredClient.tokenSettings = this.tokenSettings;
|
||||||
new HashSet<>(this.scopes));
|
|
||||||
registeredClient.clientSettings = new ClientSettings(this.clientSettings.settings());
|
|
||||||
registeredClient.tokenSettings = new TokenSettings(this.tokenSettings.settings());
|
|
||||||
|
|
||||||
return registeredClient;
|
return registeredClient;
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2020-2021 the original author or authors.
|
* Copyright 2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,8 +15,6 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.client;
|
package org.springframework.security.oauth2.server.authorization.client;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A repository for OAuth 2.0 {@link RegisteredClient}(s).
|
* A repository for OAuth 2.0 {@link RegisteredClient}(s).
|
||||||
*
|
*
|
||||||
@ -28,23 +26,19 @@ import org.springframework.lang.Nullable;
|
|||||||
public interface RegisteredClientRepository {
|
public interface RegisteredClientRepository {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the registered client identified by the provided {@code id},
|
* Returns the registered client identified by the provided {@code id}, or {@code null} if not found.
|
||||||
* or {@code null} if not found.
|
|
||||||
*
|
*
|
||||||
* @param id the registration identifier
|
* @param id the registration identifier
|
||||||
* @return the {@link RegisteredClient} if found, otherwise {@code null}
|
* @return the {@link RegisteredClient} if found, otherwise {@code null}
|
||||||
*/
|
*/
|
||||||
@Nullable
|
|
||||||
RegisteredClient findById(String id);
|
RegisteredClient findById(String id);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the registered client identified by the provided {@code clientId},
|
* Returns the registered client identified by the provided {@code clientId}, or {@code null} if not found.
|
||||||
* or {@code null} if not found.
|
|
||||||
*
|
*
|
||||||
* @param clientId the client identifier
|
* @param clientId the client identifier
|
||||||
* @return the {@link RegisteredClient} if found, otherwise {@code null}
|
* @return the {@link RegisteredClient} if found, otherwise {@code null}
|
||||||
*/
|
*/
|
||||||
@Nullable
|
|
||||||
RegisteredClient findByClientId(String clientId);
|
RegisteredClient findByClientId(String clientId);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -26,7 +26,7 @@ import java.util.Map;
|
|||||||
* @see Settings
|
* @see Settings
|
||||||
*/
|
*/
|
||||||
public class ClientSettings extends Settings {
|
public class ClientSettings extends Settings {
|
||||||
private static final String CLIENT_SETTING_BASE = "setting.client.";
|
private static final String CLIENT_SETTING_BASE = "spring.security.oauth2.authorization-server.client.";
|
||||||
public static final String REQUIRE_PROOF_KEY = CLIENT_SETTING_BASE.concat("require-proof-key");
|
public static final String REQUIRE_PROOF_KEY = CLIENT_SETTING_BASE.concat("require-proof-key");
|
||||||
public static final String REQUIRE_USER_CONSENT = CLIENT_SETTING_BASE.concat("require-user-consent");
|
public static final String REQUIRE_USER_CONSENT = CLIENT_SETTING_BASE.concat("require-user-consent");
|
||||||
|
|
||||||
|
@ -1,155 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2020 the original author or authors.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
package org.springframework.security.oauth2.server.authorization.config;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A facility for provider configuration settings.
|
|
||||||
*
|
|
||||||
* @author Daniel Garnier-Moiroux
|
|
||||||
* @since 0.1.0
|
|
||||||
* @see Settings
|
|
||||||
*/
|
|
||||||
public class ProviderSettings extends Settings {
|
|
||||||
private static final String PROVIDER_SETTING_BASE = "setting.provider.";
|
|
||||||
public static final String ISSUER = PROVIDER_SETTING_BASE.concat("issuer");
|
|
||||||
public static final String AUTHORIZATION_ENDPOINT = PROVIDER_SETTING_BASE.concat("authorization-endpoint");
|
|
||||||
public static final String TOKEN_ENDPOINT = PROVIDER_SETTING_BASE.concat("token-endpoint");
|
|
||||||
public static final String JWK_SET_ENDPOINT = PROVIDER_SETTING_BASE.concat("jwk-set-endpoint");
|
|
||||||
public static final String TOKEN_REVOCATION_ENDPOINT = PROVIDER_SETTING_BASE.concat("token-revocation-endpoint");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a {@code ProviderSettings}.
|
|
||||||
*/
|
|
||||||
public ProviderSettings() {
|
|
||||||
this(defaultSettings());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Constructs a {@code ProviderSettings} using the provided parameters.
|
|
||||||
*
|
|
||||||
* @param settings the initial settings
|
|
||||||
*/
|
|
||||||
public ProviderSettings(Map<String, Object> settings) {
|
|
||||||
super(settings);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the URL of the Provider's Issuer Identifier
|
|
||||||
*
|
|
||||||
* @return the URL of the Provider's Issuer Identifier
|
|
||||||
*/
|
|
||||||
public String issuer() {
|
|
||||||
return setting(ISSUER);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the URL the Provider uses as its Issuer Identifier.
|
|
||||||
*
|
|
||||||
* @param issuer the URL the Provider uses as its Issuer Identifier.
|
|
||||||
* @return the {@link ProviderSettings} for further configuration
|
|
||||||
*/
|
|
||||||
public ProviderSettings issuer(String issuer) {
|
|
||||||
return setting(ISSUER, issuer);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Provider's OAuth 2.0 Authorization endpoint. The default is {@code /oauth2/authorize}.
|
|
||||||
*
|
|
||||||
* @return the Authorization endpoint
|
|
||||||
*/
|
|
||||||
public String authorizationEndpoint() {
|
|
||||||
return setting(AUTHORIZATION_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the Provider's OAuth 2.0 Authorization endpoint.
|
|
||||||
*
|
|
||||||
* @param authorizationEndpoint the Authorization endpoint
|
|
||||||
* @return the {@link ProviderSettings} for further configuration
|
|
||||||
*/
|
|
||||||
public ProviderSettings authorizationEndpoint(String authorizationEndpoint) {
|
|
||||||
return setting(AUTHORIZATION_ENDPOINT, authorizationEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Provider's OAuth 2.0 Token endpoint. The default is {@code /oauth2/token}.
|
|
||||||
*
|
|
||||||
* @return the Token endpoint
|
|
||||||
*/
|
|
||||||
public String tokenEndpoint() {
|
|
||||||
return setting(TOKEN_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the Provider's OAuth 2.0 Token endpoint.
|
|
||||||
*
|
|
||||||
* @param tokenEndpoint the Token endpoint
|
|
||||||
* @return the {@link ProviderSettings} for further configuration
|
|
||||||
*/
|
|
||||||
public ProviderSettings tokenEndpoint(String tokenEndpoint) {
|
|
||||||
return setting(TOKEN_ENDPOINT, tokenEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Provider's JWK Set endpoint. The default is {@code /oauth2/jwks}.
|
|
||||||
*
|
|
||||||
* @return the JWK Set endpoint
|
|
||||||
*/
|
|
||||||
public String jwkSetEndpoint() {
|
|
||||||
return setting(JWK_SET_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the Provider's JWK Set endpoint.
|
|
||||||
*
|
|
||||||
* @param jwkSetEndpoint the JWK Set endpoint
|
|
||||||
* @return the {@link ProviderSettings} for further configuration
|
|
||||||
*/
|
|
||||||
public ProviderSettings jwkSetEndpoint(String jwkSetEndpoint) {
|
|
||||||
return setting(JWK_SET_ENDPOINT, jwkSetEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Provider's OAuth 2.0 Token Revocation endpoint. The default is {@code /oauth2/revoke}.
|
|
||||||
*
|
|
||||||
* @return the Token Revocation endpoint
|
|
||||||
*/
|
|
||||||
public String tokenRevocationEndpoint() {
|
|
||||||
return setting(TOKEN_REVOCATION_ENDPOINT);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the Provider's OAuth 2.0 Token Revocation endpoint.
|
|
||||||
*
|
|
||||||
* @param tokenRevocationEndpoint the Token Revocation endpoint
|
|
||||||
* @return the {@link ProviderSettings} for further configuration
|
|
||||||
*/
|
|
||||||
public ProviderSettings tokenRevocationEndpoint(String tokenRevocationEndpoint) {
|
|
||||||
return setting(TOKEN_REVOCATION_ENDPOINT, tokenRevocationEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected static Map<String, Object> defaultSettings() {
|
|
||||||
Map<String, Object> settings = new HashMap<>();
|
|
||||||
settings.put(AUTHORIZATION_ENDPOINT, "/oauth2/authorize");
|
|
||||||
settings.put(TOKEN_ENDPOINT, "/oauth2/token");
|
|
||||||
settings.put(JWK_SET_ENDPOINT, "/oauth2/jwks");
|
|
||||||
settings.put(TOKEN_REVOCATION_ENDPOINT, "/oauth2/revoke");
|
|
||||||
return settings;
|
|
||||||
}
|
|
||||||
}
|
|
@ -15,7 +15,7 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.config;
|
package org.springframework.security.oauth2.server.authorization.config;
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.Version;
|
import org.springframework.security.oauth2.server.authorization.Version;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
@ -15,8 +15,6 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.config;
|
package org.springframework.security.oauth2.server.authorization.config;
|
||||||
|
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@ -29,10 +27,8 @@ import java.util.Map;
|
|||||||
* @see Settings
|
* @see Settings
|
||||||
*/
|
*/
|
||||||
public class TokenSettings extends Settings {
|
public class TokenSettings extends Settings {
|
||||||
private static final String TOKEN_SETTING_BASE = "setting.token.";
|
private static final String TOKEN_SETTING_BASE = "spring.security.oauth2.authorization-server.token.";
|
||||||
public static final String ACCESS_TOKEN_TIME_TO_LIVE = TOKEN_SETTING_BASE.concat("access-token-time-to-live");
|
public static final String ACCESS_TOKEN_TIME_TO_LIVE = TOKEN_SETTING_BASE.concat("access-token-time-to-live");
|
||||||
public static final String REUSE_REFRESH_TOKENS = TOKEN_SETTING_BASE.concat("reuse-refresh-tokens");
|
|
||||||
public static final String REFRESH_TOKEN_TIME_TO_LIVE = TOKEN_SETTING_BASE.concat("refresh-token-time-to-live");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a {@code TokenSettings}.
|
* Constructs a {@code TokenSettings}.
|
||||||
@ -60,65 +56,19 @@ public class TokenSettings extends Settings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the time-to-live for an access token. Must be greater than {@code Duration.ZERO}.
|
* Set the time-to-live for an access token.
|
||||||
*
|
*
|
||||||
* @param accessTokenTimeToLive the time-to-live for an access token
|
* @param accessTokenTimeToLive the time-to-live for an access token
|
||||||
* @return the {@link TokenSettings}
|
* @return the {@link TokenSettings}
|
||||||
*/
|
*/
|
||||||
public TokenSettings accessTokenTimeToLive(Duration accessTokenTimeToLive) {
|
public TokenSettings accessTokenTimeToLive(Duration accessTokenTimeToLive) {
|
||||||
Assert.notNull(accessTokenTimeToLive, "accessTokenTimeToLive cannot be null");
|
|
||||||
Assert.isTrue(accessTokenTimeToLive.getSeconds() > 0, "accessTokenTimeToLive must be greater than Duration.ZERO");
|
|
||||||
setting(ACCESS_TOKEN_TIME_TO_LIVE, accessTokenTimeToLive);
|
setting(ACCESS_TOKEN_TIME_TO_LIVE, accessTokenTimeToLive);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns {@code true} if refresh tokens are reused when returning the access token response,
|
|
||||||
* or {@code false} if a new refresh token is issued. The default is {@code true}.
|
|
||||||
*/
|
|
||||||
public boolean reuseRefreshTokens() {
|
|
||||||
return setting(REUSE_REFRESH_TOKENS);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set to {@code true} if refresh tokens are reused when returning the access token response,
|
|
||||||
* or {@code false} if a new refresh token is issued.
|
|
||||||
*
|
|
||||||
* @param reuseRefreshTokens {@code true} to reuse refresh tokens, {@code false} to issue new refresh tokens
|
|
||||||
* @return the {@link TokenSettings}
|
|
||||||
*/
|
|
||||||
public TokenSettings reuseRefreshTokens(boolean reuseRefreshTokens) {
|
|
||||||
setting(REUSE_REFRESH_TOKENS, reuseRefreshTokens);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the time-to-live for a refresh token. The default is 60 minutes.
|
|
||||||
*
|
|
||||||
* @return the time-to-live for a refresh token
|
|
||||||
*/
|
|
||||||
public Duration refreshTokenTimeToLive() {
|
|
||||||
return setting(REFRESH_TOKEN_TIME_TO_LIVE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the time-to-live for a refresh token. Must be greater than {@code Duration.ZERO}.
|
|
||||||
*
|
|
||||||
* @param refreshTokenTimeToLive the time-to-live for a refresh token
|
|
||||||
* @return the {@link TokenSettings}
|
|
||||||
*/
|
|
||||||
public TokenSettings refreshTokenTimeToLive(Duration refreshTokenTimeToLive) {
|
|
||||||
Assert.notNull(refreshTokenTimeToLive, "refreshTokenTimeToLive cannot be null");
|
|
||||||
Assert.isTrue(refreshTokenTimeToLive.getSeconds() > 0, "refreshTokenTimeToLive must be greater than Duration.ZERO");
|
|
||||||
setting(REFRESH_TOKEN_TIME_TO_LIVE, refreshTokenTimeToLive);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected static Map<String, Object> defaultSettings() {
|
protected static Map<String, Object> defaultSettings() {
|
||||||
Map<String, Object> settings = new HashMap<>();
|
Map<String, Object> settings = new HashMap<>();
|
||||||
settings.put(ACCESS_TOKEN_TIME_TO_LIVE, Duration.ofMinutes(5));
|
settings.put(ACCESS_TOKEN_TIME_TO_LIVE, Duration.ofMinutes(5));
|
||||||
settings.put(REUSE_REFRESH_TOKENS, true);
|
|
||||||
settings.put(REFRESH_TOKEN_TIME_TO_LIVE, Duration.ofMinutes(60));
|
|
||||||
return settings;
|
return settings;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user