├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── docker ├── Dockerfile ├── docker-compose.yml └── docker-entrypoint-initdb.d │ └── createdb.js ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── dev │ │ └── rexijie │ │ └── auth │ │ ├── Oauth2ServerApplication.java │ │ ├── cache │ │ └── InMemoryCache.java │ │ ├── config │ │ ├── AuthorizationServerConfig.java │ │ ├── CacheConfig.java │ │ ├── OIDCDiscovery.java │ │ ├── PasswordEncoderConfig.java │ │ ├── TokenServicesConfig.java │ │ ├── WebConfig.java │ │ ├── WebSecurityConfig.java │ │ └── interceptors │ │ │ └── SessionInvalidatingHandlerInterceptor.java │ │ ├── constants │ │ ├── Authorities.java │ │ ├── Claims.java │ │ ├── GrantTypes.java │ │ └── Scopes.java │ │ ├── controller │ │ ├── EnhancedAuthorizationEndpoint.java │ │ ├── OAuth2LoginController.java │ │ ├── OIDCEndpoint.java │ │ ├── UserApprovalController.java │ │ ├── UserInfoEndpoint.java │ │ ├── advice │ │ │ └── WebErrorAdvice.java │ │ └── registration │ │ │ ├── client │ │ │ └── ClientRegistrationEndpoint.java │ │ │ ├── dto │ │ │ ├── ClientDto.java │ │ │ ├── UserDto.java │ │ │ └── mapper │ │ │ │ ├── ClientMapper.java │ │ │ │ └── UserMapper.java │ │ │ └── user │ │ │ └── UserRegistrationEndpoint.java │ │ ├── errors │ │ ├── ClientRegistrationException.java │ │ ├── DumbRequestException.java │ │ ├── MalformedRequestException.java │ │ └── UserExistsException.java │ │ ├── filters │ │ └── ApiEndpointAuthenticationFilter.java │ │ ├── generators │ │ └── KeyGen.java │ │ ├── init │ │ └── Bootstrap.java │ │ ├── model │ │ ├── Entity.java │ │ ├── Identified.java │ │ ├── OidcAddress.java │ │ ├── User.java │ │ ├── UserInfo.java │ │ ├── authority │ │ │ ├── Authority.java │ │ │ ├── AuthorityEnum.java │ │ │ ├── Role.java │ │ │ └── RoleEnum.java │ │ ├── client │ │ │ ├── Client.java │ │ │ ├── ClientProfiles.java │ │ │ └── ClientTypes.java │ │ └── token │ │ │ ├── AccessToken.java │ │ │ ├── AuthorizationToken.java │ │ │ ├── IDToken.java │ │ │ ├── KeyPairHolder.java │ │ │ ├── RSAKeyPairHolder.java │ │ │ └── RefreshToken.java │ │ ├── repository │ │ ├── AccessTokenRepository.java │ │ ├── AuthorizationTokenRepository.java │ │ ├── ClientRepository.java │ │ ├── RefreshTokenRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── service │ │ ├── ClientSecretGenerator.java │ │ ├── ClientService.java │ │ ├── SecretGenerator.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── ClientServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ ├── tokenservices │ │ ├── DefaultJwtClaimEnhancer.java │ │ ├── JpaTokenStore.java │ │ ├── JwtClaimsEnhancer.java │ │ ├── JwtTokenConverter.java │ │ ├── JwtTokenEnhancer.java │ │ ├── PersistentAuthorizationCodeServices.java │ │ └── openid │ │ │ ├── AuthorizationServerOidcTokenServices.java │ │ │ ├── IDTokenClaimsEnhancer.java │ │ │ ├── IDTokenEnhancer.java │ │ │ ├── IDTokenGranter.java │ │ │ └── IdTokenGeneratingTokenEnhancer.java │ │ └── util │ │ ├── AuthenticationUtils.java │ │ ├── ObjectUtils.java │ │ ├── TokenRequestUtils.java │ │ └── TokenUtils.java └── resources │ ├── META-INF │ └── additional-spring-configuration-metadata.json │ ├── application-dev.yml │ ├── application-docker.yml │ ├── application-test.yml │ ├── application.yml │ ├── static │ ├── css │ │ ├── confirmaccess.css │ │ ├── global.css │ │ ├── login.css │ │ └── logout.css │ └── img │ │ ├── favicon.ico │ │ ├── read.svg │ │ └── write.svg │ └── templates │ ├── confirmaccess.html │ ├── error │ ├── 400.html │ ├── 404.html │ └── 500.html │ ├── login.html │ └── logout.html └── test └── java └── dev └── rexijie └── auth └── Oauth2ServerApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | *.DS_Store 35 | .DS_Store 36 | src/.DS_Store 37 | src/main/.DS_Store 38 | src/main/java/.DS_Store 39 | src/main/resources/static/.DS_Store 40 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Recks11/spring-oauth2-authorization-server/fad45eec46982b68203e3509879c56ae58c4a833/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring OAuth2 Authorization Server 2 | This is an OAuth2 authorization server written with Spring Boot capable of generating and granting JWTs. All flows are stateless except the `authorization_code` flow 3 | 4 | 5 | ## Endpoints 6 | The baseUrl is `http://127.0.0.1:8080/**`. but you should provide yours using the `${SERVER_URL}` environment variable. 7 | 8 | There are 8 endpoints 9 | - `/oauth2/token` to get tokens with the password, implicit, client_credentials and refresh_token flows. 10 | - `/oauth2/authorize` for the authorization_code flow. 11 | - `/oauth2/check_token` to check the tokens with your resource server. 12 | - `/oauth2/token_key` to get the public key used to verify tokens. 13 | - `/oauth2/introspect` the introspection endpoint 14 | - `/openid/userinfo` user info endpoint 15 | - `/openid/.well-known/jwks.json` openid jwks_uri 16 | - `/openid/.well-known/openid-configuration` openid discovery endpoint 17 | 18 | 19 | ## USAGE 20 | This authorization server supports openid discovery which enables it take advantage of spring-security-oauth2 openid configuration 21 | 22 | ### Configuring a RESOURCE SERVER 23 | Configuring a resource server app to use this authorization server is as easy as setting the issuer-uri property in the application.properties or application.yml file 24 | ```yaml 25 | spring: 26 | security: 27 | oauth2: 28 | resourceserver: 29 | jwt: 30 | issuer-uri: http://127.0.0.1:8080/openid 31 | ``` 32 | You can then configure security in your WebSecurityConfigurerAdapter class. the Jwt decoder Bean gets its configuration from the authorization server. 33 | 34 | 35 | ```java 36 | @Configuration 37 | @EnableWebSecurity 38 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 39 | 40 | @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") 41 | private String issuerUri; 42 | 43 | @Override 44 | protected void configure(HttpSecurity http) throws Exception { 45 | http 46 | .authorizeRequests(authorize -> authorize 47 | .anyRequest().authenticated() 48 | ) 49 | .oauth2ResourceServer(oauth -> oauth 50 | .jwt(jwt -> jwt 51 | .jwtAuthenticationConverter(jwtAuthenticationConverter()) 52 | .decoder(jwtDecoder())) 53 | ); 54 | } 55 | 56 | JwtAuthenticationConverter jwtAuthenticationConverter() { 57 | CustomAuthenticationConverter grantedAuthoritiesConverter = new CustomAuthenticationConverter(); 58 | JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); 59 | converter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); 60 | return converter; 61 | } 62 | 63 | @Bean 64 | public JwtDecoder jwtDecoder() { 65 | return JwtDecoders.fromIssuerLocation(issuerUri); 66 | } 67 | } 68 | ``` 69 | The `jwtAuthenticationConverter()` is optional, but you can add it if you want to customise the granted authorities in the generated jwt. 70 | 71 | ### Configuring a CLIENT 72 | configuring a `Spring-security-oauth2-client` to use the authorization server you need to provide the issuer-uri property. 73 | ```yaml 74 | spring: 75 | security: 76 | oauth2: 77 | client: 78 | provider: 79 | rexijie-dev: 80 | issuerUri: http://127.0.0.1:8080/openid 81 | ``` 82 | and then the security configuration 83 | ```java 84 | @EnableWebFluxSecurity 85 | public class OAuth2Config { 86 | 87 | @Value("${spring.security.oauth2.client.provider.rexijie-dev.issuerUri}") 88 | private String issuerUri; 89 | 90 | @Bean 91 | public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { 92 | http 93 | .authorizeExchange( 94 | authorize -> authorize 95 | .pathMatchers("/").permitAll() 96 | .anyExchange().authenticated() 97 | ) 98 | .oauth2Client(Customizer.withDefaults()) 99 | .oauth2Login(Customizer.withDefaults()); 100 | 101 | return http.build(); 102 | } 103 | } 104 | ``` 105 | ## FLOWS 106 | This section describes how to use the various OAuth2 flows. 107 | 108 | JWTs produced by this application are encrypted using the RSA256 algorithm and hence are signed with a key pair. The public key can be gotten from the `/oauth/token_key` endpoint. 109 | 110 | ```json 111 | { 112 | "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZXhpamllQGdtYWlsLmNvbSIsInJvbGUiOiJVU0VSIiwic2NvcGUiOlsicmVhZCJdLCJpc3MiOiJodHRwczovL3JleGlqaWUuZGV2IiwiZXhwIjoxNTk4MDE0NTcyLCJhdXRob3JpdGllcyI6WyJST0xFX0NBTl9WSUVXIiwiUk9MRV9VU0VSIl0sImp0aSI6IjViMzA1YTE4LWQ0NWMtNDA4YS1iNGU3LWEzYmYwODQ3NWE4ZCIsImNsaWVudF9pZCI6Im1hbmFnZW1lbnQtYXBwIn0.li0f2gEA2VsbginzWa0ELcKrWGXeXSybsZVFdQiWHRZ2YbqvuYbpr0ReN_D6_0zWgCBdWjblibSLUiLrM2vlQBr0UarU1RnaDP5WDTxnTBch80rjWIfc-_QBwFOuitD7iXHwRhJLDObv491YcxLcmXhJmPTr-CavgG-cruD6kuqIzqpwQ22-TXZ_iHT2OCddsSX-DUtXMIb7oBIkbUgdc3UCmFn2fdVsFxZbUM2CYsKc56VgGO27MlfKfRQhCfIhBIzpvXmBRUETWMipOJOCtJ60JPW1NM78-lgV-Y8lw280SZAgK5jukJNshNXJgkqw42scQMSdXJTKg-WBWoV6Bg", 113 | "token_type": "bearer", 114 | "refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZXhpamllQGdtYWlsLmNvbSIsInJvbGUiOiJVU0VSIiwic2NvcGUiOlsicmVhZCJdLCJhdGkiOiI1YjMwNWExOC1kNDVjLTQwOGEtYjRlNy1hM2JmMDg0NzVhOGQiLCJpc3MiOiJodHRwczovL3JleGlqaWUuZGV2IiwiZXhwIjoxNjAwNTYzMzcyLCJhdXRob3JpdGllcyI6WyJST0xFX0NBTl9WSUVXIiwiUk9MRV9VU0VSIl0sImp0aSI6IjE1YmNjYjQwLTQ3NWEtNDk4My05YWI2LTczNmZhNmI2MDU5OSIsImNsaWVudF9pZCI6Im1hbmFnZW1lbnQtYXBwIn0.P8tW6DsEd1qefdWMGZiBq7hlaYSl6hFZ2aRACHf5u-F-NUTY7F9wiB1vXRoDFS577AwRAajPFB5Mq-IFsGl4LfOoth9AjJJpA9EF3hPXj6XH6f49Ozzn2mF8AvEZBO-SJ04eK1eS-cJN03YK4FBTO9LT59-6SLqzhGE8x-NwGQWSab91Gv7_DmmuPHEM_vAnQfBV9ycuN0wdcJmaj1wsRnbBAtCe-bETu9LZgQ5vw5ANCd8Dfz0DTM2vu6vCFTpFeFwMy91Ol73POh34z_pGd2tgSaWzJm_qCVq-hKOjXj-4d2tmDvLcwUzPtwCvbUrbPoQYyF9RZEO8NOdr0--3IA", 115 | "expires_in": 43199, 116 | "scope": "read", 117 | "jti": "5b305a18-d45c-408a-b4e7-a3bf08475a8d" 118 | } 119 | ``` 120 | ### PASSWORD FLOW 121 | ... 122 | ### IMPLICIT FLOW 123 | ... 124 | ### CLIENT CREDENTIALS FLOW 125 | ... 126 | ### REFRESH TOKEN FLOW 127 | ... 128 | ### AUTHORIZATION CODE FLOW 129 | ... 130 | 131 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM adoptopenjdk:14-jre-hotspot as builder 2 | WORKDIR application 3 | ARG JAR_FILE=target/*.jar 4 | COPY ${JAR_FILE} app.jar 5 | RUN java -Djarmode=layertools -jar app.jar extract 6 | 7 | FROM adoptopenjdk:14-jre-hotspot 8 | WORKDIR auth-server 9 | COPY --from=builder application/dependencies/ ./ 10 | COPY --from=builder application/spring-boot-loader/ ./ 11 | COPY --from=builder application/snapshot-dependencies/ ./ 12 | COPY --from=builder application/application/ ./ 13 | 14 | EXPOSE 8000 15 | 16 | ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"] -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.1" 2 | 3 | services: 4 | 5 | mongodb: 6 | image: mongo:4.4 7 | restart: always 8 | volumes: 9 | - type: volume 10 | source: mongo-data 11 | target: /data 12 | volume: 13 | nocopy: true 14 | - type: bind 15 | source: ./docker-entrypoint-initdb.d 16 | target: /docker-entrypoint-initdb.d 17 | environment: 18 | - MONGO_INITDB_ROOT_USERNAME=root 19 | - MONGO_INITDB_ROOT_PASSWORD=root@pass 20 | - MONGO_INITDB_DATABASE=authserver 21 | networks: 22 | - authserver 23 | 24 | auth-server: 25 | build: 26 | context: ../ 27 | dockerfile: docker/Dockerfile 28 | restart: always 29 | ports: 30 | - target: 8080 31 | published: 8000 32 | mode: host 33 | protocol: tcp 34 | depends_on: 35 | - mongodb 36 | environment: 37 | - SERVER_URL=http://127.0.0.1:8000 38 | - spring.profiles.active=docker 39 | - ENABLE_IMPLICIT_ID_TOKEN=true 40 | - MONGO_HOST=mongodb 41 | - MONGO_USERNAME=idea 42 | - MONGO_PASSWORD=ideapass 43 | - MONGO_DATABASE=authserver 44 | networks: 45 | - authserver 46 | 47 | volumes: 48 | mongo-data: 49 | 50 | networks: 51 | authserver: -------------------------------------------------------------------------------- /docker/docker-entrypoint-initdb.d/createdb.js: -------------------------------------------------------------------------------- 1 | db.auth('root', 'root@pass') 2 | 3 | db = db.getSiblingDB('authserver') 4 | 5 | db.createUser( 6 | { 7 | user: "idea", 8 | pwd: "ideapass", 9 | roles: [ 10 | { 11 | role: "readWrite", 12 | db: "authserver" 13 | } 14 | ] 15 | } 16 | ) -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.3.RELEASE 9 | 10 | 11 | dev.rexijie.oauth2 12 | authorization-server 13 | 0.2.0-SNAPSHOT 14 | oauth2-server 15 | OAuth2 authorization server with support for OIDC discovery and ID tokens 16 | 17 | 18 | 11 19 | 0.9.1 20 | Hoxton.SR7 21 | ${spring-boot.version} 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-actuator 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-mongodb 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-thymeleaf 36 | 37 | 38 | org.springframework.security.oauth.boot 39 | spring-security-oauth2-autoconfigure 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-web 44 | 45 | 46 | org.projectlombok 47 | lombok 48 | true 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-configuration-processor 53 | true 54 | 55 | 56 | 57 | io.jsonwebtoken 58 | jjwt 59 | ${jjwt.version} 60 | 61 | 62 | 63 | org.springframework.security 64 | spring-security-oauth2-jose 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-starter-test 70 | test 71 | 72 | 73 | org.junit.vintage 74 | junit-vintage-engine 75 | 76 | 77 | 78 | 79 | org.springframework.security 80 | spring-security-test 81 | test 82 | 83 | 84 | 85 | 86 | 87 | 88 | org.springframework.cloud 89 | spring-cloud-dependencies 90 | ${spring-cloud.version} 91 | pom 92 | import 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | org.springframework.boot 101 | spring-boot-maven-plugin 102 | 103 | 104 | true 105 | 106 | rexijie/oauth-server:${project.version} 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/Oauth2ServerApplication.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth; 2 | 3 | import dev.rexijie.auth.config.OIDCDiscovery; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.context.properties.ConfigurationPropertiesScan; 7 | 8 | /** 9 | * @author Rex Ijiekhuamen 10 | */ 11 | @SpringBootApplication 12 | @ConfigurationPropertiesScan(basePackageClasses = {OIDCDiscovery.class}) 13 | public class Oauth2ServerApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(Oauth2ServerApplication.class, args); 17 | } 18 | } 19 | 20 | /* 21 | things left to do for the base implementation as per 22 | https://openid.net/specs/openid-connect-core-1_0.html#ImplementationConsiderations 23 | TODO 24 | - Implement prompt parameter 25 | - implement display parameter 26 | - implement preferred locales 27 | - implement max_age 28 | - implement context-class-reference (acr_values) 29 | for Dynamic Client 30 | TODO 31 | - implement dynamic registration 32 | - implement Request URI (request_uri) 33 | 34 | */ -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/cache/InMemoryCache.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.cache; 2 | 3 | public class InMemoryCache { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/AuthorizationServerConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import dev.rexijie.auth.config.interceptors.SessionInvalidatingHandlerInterceptor; 4 | import dev.rexijie.auth.service.ClientService; 5 | import dev.rexijie.auth.service.UserService; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 13 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 14 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 15 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 16 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 17 | import org.springframework.security.oauth2.provider.CompositeTokenGranter; 18 | import org.springframework.security.oauth2.provider.OAuth2RequestFactory; 19 | import org.springframework.security.oauth2.provider.TokenGranter; 20 | import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; 21 | import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; 22 | import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter; 23 | import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter; 24 | import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter; 25 | import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; 26 | import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; 27 | import org.springframework.security.oauth2.provider.token.AccessTokenConverter; 28 | import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; 29 | import org.springframework.web.cors.CorsConfiguration; 30 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 31 | import org.springframework.web.filter.CorsFilter; 32 | 33 | import java.time.Duration; 34 | import java.util.List; 35 | 36 | @Configuration 37 | @EnableAuthorizationServer 38 | public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 39 | private final UserService userService; 40 | private final ClientService clientService; 41 | private final PasswordEncoder passwordEncoder; 42 | private final AuthenticationManager authenticationManager; 43 | private final AuthorizationServerTokenServices tokenServices; 44 | private final AuthorizationCodeServices authorizationCodeServices; 45 | private final AccessTokenConverter accessTokenConverter; 46 | 47 | public AuthorizationServerConfig(UserService userService, 48 | ClientService clientService, 49 | PasswordEncoder passwordEncoder, 50 | AuthenticationConfiguration authenticationConfiguration, 51 | AuthorizationServerTokenServices tokenServices, 52 | AuthorizationCodeServices authorizationCodeServices, 53 | AccessTokenConverter accessTokenConverter) throws Exception { 54 | this.userService = userService; 55 | this.tokenServices = tokenServices; 56 | this.clientService = clientService; 57 | this.passwordEncoder = passwordEncoder; 58 | this.authenticationManager = authenticationConfiguration.getAuthenticationManager(); 59 | this.authorizationCodeServices = authorizationCodeServices; 60 | this.accessTokenConverter = accessTokenConverter; 61 | } 62 | 63 | @Override 64 | public void configure(AuthorizationServerSecurityConfigurer security) { 65 | security.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_CLIENT')") 66 | .checkTokenAccess("hasAuthority('ROLE_CLIENT')") 67 | .passwordEncoder(passwordEncoder); 68 | 69 | 70 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 71 | CorsConfiguration corsConfig = new CorsConfiguration(); 72 | corsConfig.applyPermitDefaultValues(); 73 | corsConfig.setMaxAge(Duration.ofMinutes(10L)); 74 | 75 | source.registerCorsConfiguration("/oauth2/token", corsConfig); 76 | CorsFilter filter = new CorsFilter(source); 77 | 78 | security.addTokenEndpointAuthenticationFilter(filter); 79 | 80 | } 81 | 82 | @Override 83 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 84 | clients.withClientDetails(clientService); 85 | } 86 | 87 | @Override 88 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) { 89 | endpoints. 90 | authenticationManager(authenticationManager) 91 | .userDetailsService(userService) 92 | .accessTokenConverter(accessTokenConverter) 93 | .authorizationCodeServices(authorizationCodeServices) 94 | .tokenServices(tokenServices) 95 | .requestFactory(oAuth2RequestFactory()) 96 | .tokenGranter(tokenGranter()) 97 | .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS); 98 | 99 | endpoints.addInterceptor(new SessionInvalidatingHandlerInterceptor()); 100 | 101 | // workaround to replace the authorize endpoint. 102 | // rename all oauth mappins and deny access to /oauth/** 103 | endpoints 104 | .pathMapping("/oauth/check_token", "/oauth2/check_token") 105 | .pathMapping("/oauth/token_key", "/oauth2/token_key") 106 | .pathMapping("/oauth/token", "/oauth2/token") 107 | .pathMapping("/oauth/revoke", "/oauth2/revoke"); 108 | } 109 | 110 | // configure endpoints 111 | @Bean 112 | public TokenGranter tokenGranter() { 113 | return new CompositeTokenGranter(getDefaultTokenGranters(oAuth2RequestFactory())); 114 | } 115 | 116 | private OAuth2RequestFactory oAuth2RequestFactory() { 117 | return new DefaultOAuth2RequestFactory(clientService); 118 | } 119 | 120 | private List getDefaultTokenGranters(OAuth2RequestFactory oAuth2RequestFactory) { 121 | return List.of( 122 | new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientService, oAuth2RequestFactory), 123 | new RefreshTokenGranter(tokenServices, clientService, oAuth2RequestFactory), 124 | new ImplicitTokenGranter(tokenServices, clientService, oAuth2RequestFactory), 125 | new ClientCredentialsTokenGranter(tokenServices, clientService, oAuth2RequestFactory), 126 | new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientService, oAuth2RequestFactory)); 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/CacheConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; 4 | import org.springframework.cache.CacheManager; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | import org.springframework.cache.concurrent.ConcurrentMapCacheManager; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.List; 12 | 13 | @Configuration 14 | @EnableCaching 15 | public class CacheConfig { 16 | 17 | @Bean 18 | public CacheManager concurrentMapCacheManager() { 19 | return new ConcurrentMapCacheManager(); 20 | } 21 | 22 | @Component 23 | static 24 | class CacheCustomizer implements CacheManagerCustomizer { 25 | 26 | @Override 27 | public void customize(ConcurrentMapCacheManager cacheManager) { 28 | cacheManager.setCacheNames(List.of("registered-clients")); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/OIDCDiscovery.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import com.fasterxml.jackson.databind.PropertyNamingStrategy; 6 | import com.fasterxml.jackson.databind.annotation.JsonNaming; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | 9 | import java.util.Set; 10 | 11 | @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) 12 | @ConfigurationProperties(prefix = "oauth2.openid.discovery") 13 | public class OIDCDiscovery { 14 | @JsonIgnore 15 | private String baseUri; 16 | private String issuer; 17 | private String tokenEndpoint; 18 | private String tokenKeyEndpoint; 19 | private String authorizationEndpoint; 20 | private String checkTokenEndpoint; 21 | private String userinfoEndpoint; 22 | private String introspectionEndpoint; 23 | private String jwksUri; 24 | private String revocationEndpoint; 25 | 26 | private Set userinfoSigningAlgSupported; 27 | private Set idTokenSigningAlgValuesSupported; 28 | @JsonProperty("token_endpoint_auth_signing_alg_values_supported") 29 | private Set tokenEndpointAuthSigningAlgorithmsSupported; 30 | 31 | 32 | private Set scopesSupported; 33 | private Set subjectTypesSupported; 34 | private Set responseTypesSupported; 35 | private Set claimsSupported; 36 | private Set grantTypesSupported; 37 | private Set tokenEndpointAuthMethodsSupported; 38 | 39 | public String getBaseUri() { 40 | return baseUri; 41 | } 42 | 43 | public void setBaseUri(String baseUri) { 44 | this.baseUri = baseUri; 45 | } 46 | 47 | public String getIssuer() { 48 | return issuer; 49 | } 50 | 51 | public void setIssuer(String issuer) { 52 | this.issuer = issuer; 53 | } 54 | 55 | public String getTokenEndpoint() { 56 | return tokenEndpoint; 57 | } 58 | 59 | public void setTokenEndpoint(String tokenEndpoint) { 60 | this.tokenEndpoint = tokenEndpoint; 61 | } 62 | 63 | public String getTokenKeyEndpoint() { 64 | return tokenKeyEndpoint; 65 | } 66 | 67 | public void setTokenKeyEndpoint(String tokenKeyEndpoint) { 68 | this.tokenKeyEndpoint = tokenKeyEndpoint; 69 | } 70 | 71 | public String getAuthorizationEndpoint() { 72 | return authorizationEndpoint; 73 | } 74 | 75 | public void setAuthorizationEndpoint(String authorizationEndpoint) { 76 | this.authorizationEndpoint = authorizationEndpoint; 77 | } 78 | 79 | public String getCheckTokenEndpoint() { 80 | return checkTokenEndpoint; 81 | } 82 | 83 | public void setCheckTokenEndpoint(String checkTokenEndpoint) { 84 | this.checkTokenEndpoint = checkTokenEndpoint; 85 | } 86 | 87 | public String getUserinfoEndpoint() { 88 | return userinfoEndpoint; 89 | } 90 | 91 | public void setUserinfoEndpoint(String userinfoEndpoint) { 92 | this.userinfoEndpoint = userinfoEndpoint; 93 | } 94 | 95 | public String getIntrospectionEndpoint() { 96 | return introspectionEndpoint; 97 | } 98 | 99 | public void setIntrospectionEndpoint(String introspectionEndpoint) { 100 | this.introspectionEndpoint = introspectionEndpoint; 101 | } 102 | 103 | public String getJwksUri() { 104 | return jwksUri; 105 | } 106 | 107 | public void setJwksUri(String jwksUri) { 108 | this.jwksUri = jwksUri; 109 | } 110 | 111 | public String getRevocationEndpoint() { 112 | return revocationEndpoint; 113 | } 114 | 115 | public void setRevocationEndpoint(String revocationEndpoint) { 116 | this.revocationEndpoint = revocationEndpoint; 117 | } 118 | 119 | public Set getUserinfoSigningAlgSupported() { 120 | return userinfoSigningAlgSupported; 121 | } 122 | 123 | public void setUserinfoSigningAlgSupported(Set userinfoSigningAlgSupported) { 124 | this.userinfoSigningAlgSupported = userinfoSigningAlgSupported; 125 | } 126 | 127 | public Set getIdTokenSigningAlgValuesSupported() { 128 | return idTokenSigningAlgValuesSupported; 129 | } 130 | 131 | public void setIdTokenSigningAlgValuesSupported(Set idTokenSigningAlgValuesSupported) { 132 | this.idTokenSigningAlgValuesSupported = idTokenSigningAlgValuesSupported; 133 | } 134 | 135 | public Set getTokenEndpointAuthSigningAlgorithmsSupported() { 136 | return tokenEndpointAuthSigningAlgorithmsSupported; 137 | } 138 | 139 | public void setTokenEndpointAuthSigningAlgorithmsSupported(Set tokenEndpointAuthSigningAlgorithmsSupported) { 140 | this.tokenEndpointAuthSigningAlgorithmsSupported = tokenEndpointAuthSigningAlgorithmsSupported; 141 | } 142 | 143 | public Set getScopesSupported() { 144 | return scopesSupported; 145 | } 146 | 147 | public void setScopesSupported(Set scopesSupported) { 148 | this.scopesSupported = scopesSupported; 149 | } 150 | 151 | public Set getSubjectTypesSupported() { 152 | return subjectTypesSupported; 153 | } 154 | 155 | public void setSubjectTypesSupported(Set subjectTypesSupported) { 156 | this.subjectTypesSupported = subjectTypesSupported; 157 | } 158 | 159 | public Set getResponseTypesSupported() { 160 | return responseTypesSupported; 161 | } 162 | 163 | public void setResponseTypesSupported(Set responseTypesSupported) { 164 | this.responseTypesSupported = responseTypesSupported; 165 | } 166 | 167 | public Set getClaimsSupported() { 168 | return claimsSupported; 169 | } 170 | 171 | public void setClaimsSupported(Set claimsSupported) { 172 | this.claimsSupported = claimsSupported; 173 | } 174 | 175 | public Set getGrantTypesSupported() { 176 | return grantTypesSupported; 177 | } 178 | 179 | public void setGrantTypesSupported(Set grantTypesSupported) { 180 | this.grantTypesSupported = grantTypesSupported; 181 | } 182 | 183 | public Set getTokenEndpointAuthMethodsSupported() { 184 | return tokenEndpointAuthMethodsSupported; 185 | } 186 | 187 | public void setTokenEndpointAuthMethodsSupported(Set tokenEndpointAuthMethodsSupported) { 188 | this.tokenEndpointAuthMethodsSupported = tokenEndpointAuthMethodsSupported; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/PasswordEncoderConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | import org.springframework.security.crypto.password.PasswordEncoder; 7 | 8 | /** 9 | * @author Rex Ijiekhuamen 10 | * 09 Sep 2020 11 | */ 12 | @Configuration 13 | public class PasswordEncoderConfig { 14 | 15 | @Bean 16 | public PasswordEncoder passwordEncoder() { 17 | return new BCryptPasswordEncoder(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/TokenServicesConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import dev.rexijie.auth.model.token.KeyPairHolder; 4 | import dev.rexijie.auth.service.ClientService; 5 | import dev.rexijie.auth.service.SecretGenerator; 6 | import dev.rexijie.auth.service.UserService; 7 | import dev.rexijie.auth.tokenservices.DefaultJwtClaimEnhancer; 8 | import dev.rexijie.auth.tokenservices.JwtClaimsEnhancer; 9 | import dev.rexijie.auth.tokenservices.JwtTokenConverter; 10 | import dev.rexijie.auth.tokenservices.JwtTokenEnhancer; 11 | import dev.rexijie.auth.tokenservices.openid.IDTokenClaimsEnhancer; 12 | import dev.rexijie.auth.tokenservices.openid.IDTokenEnhancer; 13 | import dev.rexijie.auth.tokenservices.openid.IdTokenGeneratingTokenEnhancer; 14 | import lombok.extern.slf4j.Slf4j; 15 | import org.springframework.context.annotation.Bean; 16 | import org.springframework.context.annotation.Configuration; 17 | import org.springframework.context.annotation.Primary; 18 | import org.springframework.security.authentication.ProviderManager; 19 | import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper; 20 | import org.springframework.security.oauth2.provider.token.*; 21 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 22 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 23 | import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; 24 | 25 | import java.util.List; 26 | 27 | @Configuration 28 | @Slf4j 29 | public class TokenServicesConfig { 30 | private final UserService userService; 31 | private final KeyPairHolder keyPairHolder; 32 | private final ClientService clientService; 33 | private final String kid; 34 | 35 | public TokenServicesConfig(UserService userService, 36 | KeyPairHolder keyPairHolder, 37 | ClientService clientService, 38 | SecretGenerator secretGenerator) { 39 | this.userService = userService; 40 | this.keyPairHolder = keyPairHolder; 41 | this.clientService = clientService; 42 | this.kid = secretGenerator.generate(8); 43 | } 44 | 45 | @Bean 46 | @Primary 47 | public DefaultTokenServices tokenServices() { 48 | var tokenServices = new DefaultTokenServices(); 49 | tokenServices.setSupportRefreshToken(true); 50 | tokenServices.setTokenStore(tokenStore()); 51 | tokenServices.setTokenEnhancer(tokenEnhancerChain()); 52 | tokenServices.setAuthenticationManager(preAuthProvider()); 53 | tokenServices.setClientDetailsService(clientService); 54 | return tokenServices; 55 | } 56 | 57 | @Bean 58 | public TokenStore tokenStore() { 59 | return new JwtTokenStore(tokenEnhancer()); 60 | } 61 | 62 | @Bean 63 | public TokenEnhancer tokenEnhancerChain() { 64 | var tokenEnhancerChain = new TokenEnhancerChain(); 65 | List tokenEnhancers = 66 | List.of(tokenEnhancer(), idTokenEnhancer()); 67 | tokenEnhancerChain.setTokenEnhancers(tokenEnhancers); 68 | return tokenEnhancerChain; 69 | } 70 | 71 | /** 72 | * Token enhancer responsible for converting normal tokens to Jwt. 73 | * This is also the AccessTokenConverter 74 | */ 75 | @Bean 76 | public JwtAccessTokenConverter tokenEnhancer() { 77 | var jwtTokenEnhancer = new JwtTokenEnhancer(keyPairHolder); 78 | jwtTokenEnhancer.setAccessTokenConverter(accessTokenConverter()); 79 | return jwtTokenEnhancer; 80 | } 81 | 82 | /** 83 | * Token enhancer responsible for generating ID tokens using normal tokens. 84 | * This enhancer creates the ID token in the additional information field only. 85 | * without actually modifying the token 86 | */ 87 | @Bean 88 | TokenEnhancer idTokenEnhancer() { 89 | var idTokenEnhancer = new IdTokenGeneratingTokenEnhancer( 90 | userService, idTokenClaimsEnhancer(), keyPairHolder); 91 | idTokenEnhancer.setAccessTokenConverter(accessTokenConverter()); 92 | return idTokenEnhancer; 93 | } 94 | 95 | @Bean 96 | @Primary 97 | public AccessTokenConverter accessTokenConverter() { 98 | return new JwtTokenConverter(jwtClaimsEnhancer()); 99 | } 100 | 101 | @Bean 102 | public JwtClaimsEnhancer jwtClaimsEnhancer() { 103 | return new DefaultJwtClaimEnhancer(userService); 104 | } 105 | 106 | @Bean 107 | public IDTokenClaimsEnhancer idTokenClaimsEnhancer() { 108 | return new IDTokenEnhancer(); 109 | } 110 | 111 | private ProviderManager preAuthProvider() { 112 | PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider(); 113 | provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userService)); 114 | return new ProviderManager(provider); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | import org.springframework.beans.factory.annotation.Qualifier; 4 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.web.cors.CorsConfigurationSource; 7 | import org.springframework.web.filter.CorsFilter; 8 | 9 | public class WebConfig { 10 | 11 | private final CorsConfigurationSource corsConfigurationSource; 12 | 13 | public WebConfig(@Qualifier("urlBasedCorsConfig") CorsConfigurationSource corsConfigurationSource) { 14 | this.corsConfigurationSource = corsConfigurationSource; 15 | } 16 | 17 | /** 18 | * Cors Configuration 19 | * This is currently set to allow all methods from all origins 20 | */ 21 | @Bean 22 | public FilterRegistrationBean corsFilter() { 23 | var bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource)); 24 | bean.setOrder(0); 25 | return bean; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config; 2 | 3 | 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import dev.rexijie.auth.filters.ApiEndpointAuthenticationFilter; 6 | import dev.rexijie.auth.service.UserService; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.crypto.password.PasswordEncoder; 16 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 17 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 18 | import org.springframework.web.cors.CorsConfiguration; 19 | import org.springframework.web.cors.CorsConfigurationSource; 20 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 21 | 22 | import java.util.List; 23 | 24 | @Configuration 25 | @EnableWebSecurity 26 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 27 | private final UserService userService; 28 | private final PasswordEncoder passwordEncoder; 29 | private final ObjectMapper objectMapper; 30 | private final ResourceServerTokenServices resourceServerTokenServices; 31 | 32 | public WebSecurityConfig(UserService userService, 33 | PasswordEncoder passwordEncoder, 34 | ObjectMapper objectMapper, 35 | ResourceServerTokenServices tokenServices) { 36 | this.userService = userService; 37 | this.passwordEncoder = passwordEncoder; 38 | this.objectMapper = objectMapper; 39 | this.resourceServerTokenServices = tokenServices; 40 | } 41 | 42 | /** 43 | * Cors Configuration 44 | * This is currently set to allow all methods from all origins 45 | */ 46 | @Override 47 | public void configure(HttpSecurity http) throws Exception { 48 | http 49 | .authorizeRequests() 50 | .antMatchers("/css/**", "/img/**", "/openid/**") 51 | .permitAll() 52 | .antMatchers("/api/**") 53 | .authenticated() 54 | .antMatchers("/oauth/authorize").denyAll() 55 | .and() 56 | .cors().configurationSource(corsConfigurationSource()) 57 | .and().authorizeRequests().anyRequest().authenticated(); 58 | 59 | 60 | http 61 | .formLogin(form -> form 62 | .loginPage("/oauth2/login") 63 | .permitAll() 64 | ) 65 | .logout(logout -> logout 66 | .logoutUrl("/oauth2/logout") 67 | .permitAll() 68 | ); 69 | 70 | http.addFilterBefore(new ApiEndpointAuthenticationFilter(objectMapper, resourceServerTokenServices), 71 | UsernamePasswordAuthenticationFilter.class); 72 | } 73 | 74 | @Bean 75 | @Qualifier("urlBasedCorsConfig") 76 | CorsConfigurationSource corsConfigurationSource() { 77 | var source = new UrlBasedCorsConfigurationSource(); 78 | var corsConfig = new CorsConfiguration(); 79 | corsConfig.setAllowedMethods(List.of("GET", "POST", "DELETE", "PUT", "OPTIONS")); 80 | corsConfig.addAllowedHeader("*"); 81 | corsConfig.addAllowedOrigin("*"); 82 | corsConfig.setAllowCredentials(true); 83 | source.registerCorsConfiguration("/**", corsConfig); 84 | source.registerCorsConfiguration("/oauth2/token", corsConfig); 85 | 86 | return source; 87 | } 88 | 89 | // 90 | @Override 91 | public void configure(AuthenticationManagerBuilder auth) throws Exception { 92 | auth 93 | .userDetailsService(userService) 94 | .passwordEncoder(passwordEncoder); 95 | } 96 | 97 | @Bean("authenticationManagerBean") 98 | @Override 99 | public AuthenticationManager authenticationManagerBean() throws Exception { 100 | return super.authenticationManagerBean(); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/config/interceptors/SessionInvalidatingHandlerInterceptor.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.config.interceptors; 2 | 3 | 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.web.servlet.ModelAndView; 6 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 7 | import org.springframework.web.servlet.view.RedirectView; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | import javax.servlet.http.HttpSession; 12 | 13 | /** 14 | * This is interceptor invalidates sessions after the Authorization code flow is complete 15 | * To ensure the Authorization server is stateless 16 | */ 17 | @Slf4j 18 | public class SessionInvalidatingHandlerInterceptor extends HandlerInterceptorAdapter { 19 | 20 | @Override 21 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { 22 | if (modelAndView != null && modelAndView.getView() instanceof RedirectView) { 23 | RedirectView redirectView = (RedirectView) modelAndView.getView(); 24 | String redirectUrl = redirectView.getUrl(); 25 | if (redirectUrl == null) return; 26 | if (redirectUrl.contains("code=") || redirectUrl.contains("error=")) { 27 | HttpSession session = request.getSession(false); 28 | if (session != null) { 29 | log.debug("invalidating session {}", session.getId()); 30 | session.invalidate(); 31 | } 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/constants/Authorities.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.constants; 2 | 3 | public class Authorities { 4 | public static final String ROLE_PREFIX = "ROLE_"; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/constants/Claims.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.constants; 2 | 3 | public class Claims { 4 | public static class JwtClaims { 5 | public static final String USERNAME_CLAIM = "user_name"; 6 | public static final String ROLE_CLAIM = "role"; 7 | } 8 | public static class OpenIdClaims { 9 | public static final String NAME_CLAIM = "name"; 10 | public static final String FAMILY_NAME_CLAIM = "family_name"; 11 | public static final String GIVEN_NAME_CLAIM = "given_name"; 12 | public static final String PREFERRED_USERNAME_CLAIM = "preferred_username"; 13 | public static final String BIRTH_DATE_CLAIM = "birthdate"; 14 | public static final String EMAIL_CLAIM = "email"; 15 | public static final String EMAIL_VERIFIED = "email_verified"; 16 | public static final String PHONE_CLAIM = "phone"; 17 | public static final String PHONE_VERIFIED = "phone_verified"; 18 | public static final String PICTURE_CLAIM = "picture"; 19 | public static final String PROFILE_CLAIM = "profile"; 20 | public static final String AUTHORIZED_PARTY = "azp"; 21 | public static final String AUTH_TIME = "auth_time"; 22 | public static final String NONCE = "nonce"; 23 | public static final String ACCESS_TOKEN_HASH = "at_hash"; 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/constants/GrantTypes.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.constants; 2 | 3 | public class GrantTypes { 4 | public static final String AUTHORIZATION_CODE = "authorization_code"; 5 | public static final String IMPLICIT = "implicit"; 6 | public static final String PASSWORD = "password"; 7 | public static final String CLIENT_CREDENTIALS = "client_credentials"; 8 | public static final String REFRESH_TOKEN = "refresh_token"; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/constants/Scopes.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.constants; 2 | 3 | public class Scopes { 4 | public static final String READ_SCOPE = "read"; 5 | public static final String WRITE_SCOPE = "write"; 6 | public static final String ID_SCOPE = "openid"; 7 | 8 | public static class IDTokenScopes { 9 | public static final String PROFILE = "profile"; 10 | public static final String EMAIL = "email"; 11 | public static final String ADDRESS = "address"; 12 | public static final String PHONE = "phone"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/OAuth2LoginController.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 8 | import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.RequestParam; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | import org.springframework.web.bind.annotation.SessionAttributes; 14 | 15 | /** 16 | * @author Rex Ijiekhuamen 17 | */ 18 | @FrameworkEndpoint 19 | @SessionAttributes("authorizationRequest") 20 | public class OAuth2LoginController { 21 | 22 | private final ObjectMapper objectMapper; 23 | 24 | public OAuth2LoginController(ObjectMapper objectMapper) { 25 | this.objectMapper = objectMapper; 26 | } 27 | 28 | @GetMapping("/oauth2/introspect") 29 | @ResponseBody 30 | public ResponseEntity introspect(@AuthenticationPrincipal Authentication authentication) throws Exception { 31 | var as = objectMapper.writeValueAsString(authentication); 32 | return new ResponseEntity<>(as, HttpStatus.OK); 33 | } 34 | 35 | @GetMapping("/oauth2/login") 36 | public String loginPage(Model model, @RequestParam(required = false) String error) { 37 | if (error != null) { 38 | model.addAttribute("error", "BAD CREDENTIALS"); 39 | } 40 | return "login"; 41 | } 42 | 43 | @GetMapping("/oauth2/logout") 44 | public String logout() { 45 | return "logout"; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/OIDCEndpoint.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller; 2 | 3 | import com.nimbusds.jose.jwk.JWKSet; 4 | import dev.rexijie.auth.config.OIDCDiscovery; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; 8 | import org.springframework.web.bind.annotation.CrossOrigin; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.ResponseBody; 12 | 13 | import java.util.Map; 14 | 15 | @CrossOrigin(origins = "*", allowCredentials = "", allowedHeaders = "*") 16 | @FrameworkEndpoint 17 | public class OIDCEndpoint { 18 | private final JWKSet jwkSet; 19 | private final OIDCDiscovery oidcDiscovery; 20 | 21 | public OIDCEndpoint(JWKSet jwkSet, 22 | OIDCDiscovery oidcDiscovery) { 23 | this.jwkSet = jwkSet; 24 | this.oidcDiscovery = oidcDiscovery; 25 | } 26 | 27 | @RequestMapping("/openid/.well-known/openid-configuration") 28 | public ResponseEntity openIdDiscovery() { 29 | return new ResponseEntity<>(oidcDiscovery, HttpStatus.OK); 30 | } 31 | 32 | @GetMapping("/openid/.well-known/jwks.json") 33 | @ResponseBody 34 | public Map jwkKeys() { 35 | return jwkSet.toJSONObject(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/UserApprovalController.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller; 2 | 3 | import dev.rexijie.auth.errors.DumbRequestException; 4 | import dev.rexijie.auth.model.client.Client; 5 | import dev.rexijie.auth.service.ClientService; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.oauth2.provider.AuthorizationRequest; 8 | import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.SessionAttributes; 12 | 13 | import java.util.Set; 14 | 15 | /** 16 | * @author Rex Ijiekhuamen 17 | * 09 Sep 2020 18 | */ 19 | @FrameworkEndpoint 20 | @SessionAttributes("authorizationRequest") 21 | @Slf4j 22 | public class UserApprovalController { 23 | private final ClientService clientService; 24 | 25 | public UserApprovalController(ClientService clientService) { 26 | this.clientService = clientService; 27 | } 28 | 29 | @GetMapping("/oauth/confirm_access") 30 | public String confirmAccessPage(Model model) { 31 | AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.getAttribute("authorizationRequest"); 32 | if (authorizationRequest == null) 33 | return "redirect:/oauth/login"; 34 | 35 | String clientId = authorizationRequest.getClientId(); 36 | if (clientId == null) throw new DumbRequestException("No client"); 37 | Set scope = authorizationRequest.getScope(); 38 | var client = (Client) clientService.loadClientByClientId(clientId); 39 | 40 | model.addAttribute("client_name", client.getClientName()); 41 | model.addAttribute("scopes", scope); 42 | 43 | return "confirmaccess"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/UserInfoEndpoint.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller; 2 | 3 | import dev.rexijie.auth.model.User; 4 | import dev.rexijie.auth.model.UserInfo; 5 | import dev.rexijie.auth.service.UserService; 6 | import dev.rexijie.auth.util.ObjectUtils; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 10 | import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; 11 | import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; 12 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 13 | import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; 14 | import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator; 15 | import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; 16 | import org.springframework.security.oauth2.provider.token.AccessTokenConverter; 17 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 18 | import org.springframework.web.bind.annotation.ExceptionHandler; 19 | import org.springframework.web.bind.annotation.RequestHeader; 20 | import org.springframework.web.bind.annotation.RequestMapping; 21 | 22 | import java.util.Map; 23 | 24 | import static io.jsonwebtoken.Claims.SUBJECT; 25 | 26 | /** 27 | * @author Rex Ijiekhuamen 28 | */ 29 | @FrameworkEndpoint 30 | public class UserInfoEndpoint { 31 | 32 | private final ResourceServerTokenServices resourceServerTokenServices; 33 | private final AccessTokenConverter accessTokenConverter; 34 | private final UserService userService; 35 | 36 | 37 | private WebResponseExceptionTranslator exceptionTranslator = new DefaultWebResponseExceptionTranslator(); 38 | 39 | public UserInfoEndpoint(ResourceServerTokenServices resourceServerTokenServices, 40 | AccessTokenConverter accessTokenConverter, 41 | UserService userService) { 42 | this.resourceServerTokenServices = resourceServerTokenServices; 43 | this.accessTokenConverter = accessTokenConverter; 44 | this.userService = userService; 45 | } 46 | 47 | /** 48 | * @param exceptionTranslator the exception translator to set 49 | */ 50 | public void setExceptionTranslator(WebResponseExceptionTranslator exceptionTranslator) { 51 | this.exceptionTranslator = exceptionTranslator; 52 | } 53 | /* 54 | * Maybe add aggregated claims 55 | * that will link to other resources 56 | * https://openid.net/specs/openid-connect-core-1_0.html#UserInfo 57 | */ 58 | @RequestMapping("/openid/userinfo") 59 | private ResponseEntity> userInfo(@RequestHeader("Authorization") String authorization) { 60 | String tokenValue = authorization.startsWith("Bearer ") ? authorization.substring(7) : null; 61 | 62 | OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(tokenValue); 63 | if (tokenValue == null || token == null) throw new InvalidTokenException("Token was not recognised"); 64 | if (token.isExpired()) throw new InvalidTokenException("Token has expired"); 65 | 66 | OAuth2Authentication auth2Authentication = resourceServerTokenServices.loadAuthentication(token.getValue()); 67 | Map claims = accessTokenConverter.convertAccessToken(token, auth2Authentication); 68 | 69 | String subject = claims.get(SUBJECT).toString(); 70 | User user = userService.findUserByUsername(subject); 71 | 72 | UserInfo userInfo = user.getUserInfo(); 73 | Map userInfoMap = ObjectUtils.toMap(userInfo); 74 | userInfoMap.put(SUBJECT, subject); 75 | 76 | return new ResponseEntity<>(ObjectUtils.cleanMap(userInfoMap), HttpStatus.OK); 77 | } 78 | 79 | @ExceptionHandler(InvalidTokenException.class) 80 | public ResponseEntity handleException(Exception e) throws Exception { 81 | InvalidTokenException e400 = new InvalidTokenException(e.getMessage()) { 82 | @Override 83 | public int getHttpErrorCode() { 84 | return 400; 85 | } 86 | }; 87 | return exceptionTranslator.translate(e400); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/advice/WebErrorAdvice.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.advice; 2 | 3 | import dev.rexijie.auth.errors.MalformedRequestException; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.web.bind.annotation.ControllerAdvice; 7 | import org.springframework.web.bind.annotation.ExceptionHandler; 8 | import org.springframework.web.servlet.ModelAndView; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | 12 | /** 13 | * @author Rex Ijiekhuamen 14 | * 09 Sep 2020 15 | */ 16 | @ControllerAdvice 17 | @Slf4j 18 | public class WebErrorAdvice { 19 | 20 | @ExceptionHandler(IllegalArgumentException.class) 21 | public ModelAndView handleIllegalArgumentException(IllegalStateException ex, 22 | HttpServletRequest request) { 23 | if (request != null) { 24 | log.error("request {} lead to an error", request.getRequestURI()); 25 | } 26 | log.error(ex.getMessage(), ex); 27 | ModelAndView mv = new ModelAndView(); 28 | mv.addObject("httpstatus", 400); 29 | mv.setViewName("error/400"); 30 | return mv; 31 | } 32 | 33 | @ExceptionHandler(MalformedRequestException.class) 34 | public ModelAndView handleMalformedRequest(MalformedRequestException ex, HttpServletRequest request) { 35 | 36 | ModelAndView modelAndView = new ModelAndView("error/400", HttpStatus.BAD_REQUEST); 37 | modelAndView.addObject("httpstatus", 400); 38 | 39 | return modelAndView; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/client/ClientRegistrationEndpoint.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.client; 2 | 3 | import dev.rexijie.auth.controller.registration.dto.ClientDto; 4 | import dev.rexijie.auth.controller.registration.dto.mapper.ClientMapper; 5 | import dev.rexijie.auth.model.client.Client; 6 | import dev.rexijie.auth.service.ClientService; 7 | import org.springframework.http.CacheControl; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import java.util.List; 14 | import java.util.stream.Collectors; 15 | // TODO - Update Client Registration 16 | @RestController 17 | @RequestMapping("/api/clients") 18 | public class ClientRegistrationEndpoint { 19 | 20 | private final ClientService clientService; 21 | 22 | public ClientRegistrationEndpoint(ClientService clientService) { 23 | this.clientService = clientService; 24 | } 25 | 26 | @PostMapping 27 | public ResponseEntity addClient(@RequestBody Client client) { 28 | var savedClient = clientService.addClient(client); 29 | var clientDto = ClientMapper.toDto(savedClient); 30 | var headers = new HttpHeaders(); 31 | headers.setCacheControl(CacheControl.noCache()); 32 | return new ResponseEntity<>(clientDto, headers, HttpStatus.CREATED); 33 | } 34 | 35 | @GetMapping 36 | public ResponseEntity> getAllClients() { 37 | var clients = clientService 38 | .listClientDetails() 39 | .parallelStream() 40 | .map(ClientMapper::toDto) 41 | .collect(Collectors.toList()); 42 | return new ResponseEntity<>(clients, HttpStatus.OK); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/dto/ClientDto.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.dto; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import dev.rexijie.auth.model.Entity; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.EqualsAndHashCode; 8 | import lombok.NoArgsConstructor; 9 | import org.codehaus.jackson.annotate.JsonProperty; 10 | 11 | @EqualsAndHashCode(callSuper = true) 12 | @Data 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | @JsonInclude(JsonInclude.Include.NON_NULL) 16 | public class ClientDto extends Entity { 17 | private String name; 18 | 19 | @JsonProperty("client_id") 20 | private String clientId; 21 | 22 | @JsonProperty("client_secret") 23 | private String clientSecret; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | import java.time.LocalDate; 7 | 8 | /** 9 | * @author Rex Ijiekhuamen 10 | * 09 Sep 2020 11 | */ 12 | 13 | @Data 14 | @Builder 15 | public class UserDto { 16 | private String username; 17 | private String password; 18 | private String firstName; 19 | private String lastName; 20 | private String email; 21 | private String phone; 22 | private LocalDate dateOfBirth; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/dto/mapper/ClientMapper.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.dto.mapper; 2 | 3 | import dev.rexijie.auth.controller.registration.dto.ClientDto; 4 | import dev.rexijie.auth.model.client.Client; 5 | 6 | public class ClientMapper { 7 | private ClientMapper() {} 8 | 9 | public static ClientDto toDto(Client client) { 10 | var clientDto = new ClientDto(); 11 | clientDto.setId(client.getId()); 12 | clientDto.setName(client.getClientName()); 13 | clientDto.setClientId(client.getClientId()); 14 | clientDto.setClientSecret(clientDto.getClientSecret()); 15 | 16 | return clientDto; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/dto/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.dto.mapper; 2 | 3 | import dev.rexijie.auth.controller.registration.dto.UserDto; 4 | import dev.rexijie.auth.model.User; 5 | 6 | /** 7 | * @author Rex Ijiekhuamen 8 | * 09 Sep 2020 9 | */ 10 | public class UserMapper { 11 | private UserMapper() {} 12 | public static UserDto toDto (User user) { 13 | return UserDto.builder() 14 | .username(user.getUsername()) 15 | .password("[REDACTED]") 16 | .build(); 17 | } 18 | 19 | public static User toUser (UserDto userDto) { 20 | User user = new User(); 21 | user.setUsername(userDto.getUsername() != null ? userDto.getUsername() : userDto.getEmail()); 22 | user.setPassword(userDto.getPassword()); 23 | user.getUserInfo().setFirstName(userDto.getFirstName()); 24 | user.getUserInfo().setLastName(userDto.getLastName()); 25 | user.getUserInfo().setEmail(userDto.getEmail()); 26 | user.getUserInfo().setPhoneNumber(userDto.getPhone()); 27 | user.getUserInfo().setDateOfBirth(userDto.getDateOfBirth()); 28 | return user; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/controller/registration/user/UserRegistrationEndpoint.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.controller.registration.user; 2 | 3 | import dev.rexijie.auth.controller.registration.dto.UserDto; 4 | import dev.rexijie.auth.controller.registration.dto.mapper.UserMapper; 5 | import dev.rexijie.auth.model.OidcAddress; 6 | import dev.rexijie.auth.model.User; 7 | import dev.rexijie.auth.model.UserInfo; 8 | import dev.rexijie.auth.service.UserService; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | /** 16 | * @author Rex Ijiekhuamen 17 | * 09 Sep 2020 18 | */ 19 | @RestController 20 | @RequestMapping("/api/users") 21 | public class UserRegistrationEndpoint { 22 | private final UserService userService; 23 | 24 | public UserRegistrationEndpoint(UserService userService) { 25 | this.userService = userService; 26 | } 27 | 28 | // do i add userinfo request types? 29 | // so UserUpdateRequest 30 | // UserDeleteRequest 31 | // UserCreationRequest 32 | // UserDeleteRequest 33 | 34 | @GetMapping("/principal") 35 | public ResponseEntity getPrincipal(@AuthenticationPrincipal Authentication authentication) { 36 | return new ResponseEntity<>(authentication, HttpStatus.OK); 37 | } 38 | 39 | @PostMapping 40 | public ResponseEntity addUser(@RequestBody UserDto userDto) { 41 | validateUser(userDto); 42 | User user = UserMapper.toUser(userDto); 43 | 44 | User savedUser = userService.addUser(user); 45 | return new ResponseEntity<>(savedUser, HttpStatus.OK); 46 | } 47 | 48 | @GetMapping("/{id}") 49 | public ResponseEntity getUser(@PathVariable("id") String id) { 50 | User user = userService.getUserById(id); 51 | 52 | return new ResponseEntity<>(user, HttpStatus.OK); 53 | } 54 | 55 | @PostMapping("/{id}") 56 | public ResponseEntity updateUser(@RequestBody UserInfo userInfo, 57 | @PathVariable("id") String id) { 58 | validateUserInfo(userInfo); 59 | User user = userService.getUserById(id); 60 | user.setUserInfo(userInfo); 61 | userService.updateUserInfo(user); 62 | return new ResponseEntity<>(user, HttpStatus.OK); 63 | } 64 | 65 | @PostMapping("/{id}/address") 66 | public ResponseEntity updateUserAddress(@RequestBody OidcAddress address, 67 | @PathVariable("id") String id) { 68 | validateAddress(address); 69 | User user = userService.getUserById(id); 70 | user.getUserInfo().setAddress(address); 71 | 72 | User updatedUser = userService.updateUserInfo(user); 73 | 74 | return new ResponseEntity<>(user, HttpStatus.OK); 75 | } 76 | 77 | private void validateUser(UserDto userDto) { 78 | 79 | } 80 | private void validateUserInfo(UserInfo userInfo) { 81 | 82 | } 83 | 84 | private void validateAddress(OidcAddress address) { 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/errors/ClientRegistrationException.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.errors; 2 | 3 | public class ClientRegistrationException extends RuntimeException { 4 | 5 | public ClientRegistrationException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/errors/DumbRequestException.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.errors; 2 | 3 | import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException; 4 | 5 | /** 6 | * Exception thrown when a request makes no sense 7 | * @author Rex Ijiekhuamen 8 | * 08 Sep 2020 9 | */ 10 | public class DumbRequestException extends ClientAuthenticationException { 11 | public DumbRequestException(String message) { 12 | super(message); 13 | } 14 | 15 | @Override 16 | public String getOAuth2ErrorCode() { 17 | return "invalid_token"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/errors/MalformedRequestException.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.errors; 2 | 3 | import org.springframework.boot.web.server.WebServerException; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.annotation.ResponseStatus; 6 | 7 | /** 8 | * @author Rex Ijiekhuamen 9 | * 09 Sep 2020 10 | */ 11 | @ResponseStatus(HttpStatus.BAD_REQUEST) 12 | public class MalformedRequestException extends WebServerException { 13 | 14 | public MalformedRequestException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/errors/UserExistsException.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.errors; 2 | 3 | /** 4 | * Exception thrown when an attempt is made to assign a duplicate 5 | * username, user identifier or subject claim 6 | * 7 | * @author Rex Ijiekhuamen 8 | */ 9 | public class UserExistsException extends RuntimeException { 10 | public UserExistsException(String message) { 11 | super(message); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/filters/ApiEndpointAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.filters; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.context.SecurityContext; 8 | import org.springframework.security.core.context.SecurityContextHolder; 9 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 10 | import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; 11 | import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; 12 | import org.springframework.stereotype.Component; 13 | import org.springframework.web.filter.OncePerRequestFilter; 14 | 15 | import javax.servlet.FilterChain; 16 | import javax.servlet.ServletException; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | import java.io.IOException; 20 | import java.util.HashMap; 21 | import java.util.HashSet; 22 | import java.util.Map; 23 | import java.util.Set; 24 | 25 | import static dev.rexijie.auth.util.TokenUtils.getTokenFromAuthorizationHeader; 26 | 27 | @Slf4j 28 | @Component 29 | public class ApiEndpointAuthenticationFilter extends OncePerRequestFilter { 30 | 31 | private final ResourceServerTokenServices tokenServices; 32 | private final ObjectMapper objectMapper; 33 | private final Set ignoredPaths = new HashSet<>(); 34 | 35 | public ApiEndpointAuthenticationFilter( 36 | ObjectMapper objectMapper, 37 | ResourceServerTokenServices resourceServerTokenServices) { 38 | this.objectMapper = objectMapper; 39 | this.tokenServices = resourceServerTokenServices; 40 | ignoredPaths.add("/oauth"); 41 | ignoredPaths.add("/oauth2"); 42 | ignoredPaths.add("/openid"); 43 | ignoredPaths.add("/css"); 44 | ignoredPaths.add("/js"); 45 | ignoredPaths.add("/img"); 46 | } 47 | 48 | @Override 49 | protected void doFilterInternal(HttpServletRequest request, 50 | HttpServletResponse response, 51 | FilterChain chain) throws ServletException, IOException { 52 | String authorization = request.getHeader("Authorization"); 53 | String token; 54 | String path = request.getRequestURI(); 55 | 56 | if ((authorization != null && authorization.contains("Bearer")) && !pathShouldBeIgnored(path)) { 57 | try { 58 | token = getTokenFromAuthorizationHeader(authorization); 59 | 60 | OAuth2AccessToken oAuth2AccessToken = tokenServices.readAccessToken(token); 61 | if (oAuth2AccessToken.isExpired()) throw new InvalidTokenException("Token has expired"); 62 | Authentication authentication = tokenServices.loadAuthentication(token); 63 | 64 | SecurityContext context = SecurityContextHolder.getContext(); 65 | context.setAuthentication(authentication); 66 | } catch (InvalidTokenException ex) { 67 | writeErrorResponse(request, response, ex); 68 | return; 69 | } 70 | 71 | } 72 | chain.doFilter(request, response); 73 | } 74 | 75 | protected void writeErrorResponse(HttpServletRequest request, 76 | HttpServletResponse response, 77 | Exception exception) throws IOException{ 78 | response.setContentType("application/json"); 79 | response.setCharacterEncoding("UTF-8"); 80 | response.setHeader("Access-Control-Allow-Origin","*"); 81 | response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE"); 82 | response.setHeader("Access-Control-Max-Age","*"); 83 | response.setHeader("Access-Control-Allow-Headers","x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"); 84 | response.setStatus(HttpStatus.FORBIDDEN.value()); 85 | 86 | log.warn("Token Expired: {}", exception.getMessage()); 87 | Map errorResponse = new HashMap<>(); 88 | errorResponse.put("error", "invalid_token"); 89 | errorResponse.put("error_description", exception.getMessage()); 90 | 91 | response.getWriter() 92 | .write(objectMapper.writeValueAsString(errorResponse)); 93 | } 94 | 95 | private boolean pathShouldBeIgnored(String path) { 96 | return ignoredPaths 97 | .stream() 98 | .anyMatch(path::startsWith); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/generators/KeyGen.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.generators; 2 | 3 | import com.nimbusds.jose.JWSAlgorithm; 4 | import com.nimbusds.jose.jwk.JWKSet; 5 | import com.nimbusds.jose.jwk.KeyUse; 6 | import com.nimbusds.jose.jwk.RSAKey; 7 | import dev.rexijie.auth.model.token.KeyPairHolder; 8 | import dev.rexijie.auth.model.token.RSAKeyPairHolder; 9 | import dev.rexijie.auth.service.SecretGenerator; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.stereotype.Component; 12 | 13 | import java.security.*; 14 | 15 | @Component 16 | public class KeyGen { 17 | private final SecretGenerator secretGenerator; 18 | 19 | public KeyGen(SecretGenerator secretGenerator) { 20 | this.secretGenerator = secretGenerator; 21 | } 22 | 23 | @Bean 24 | public KeyPairHolder rsaKeys() throws Exception { 25 | return new RSAKeyPairHolder(secretGenerator.generate(8), generateKeys()); 26 | } 27 | 28 | @Bean 29 | public JWKSet jwkSet(KeyPairHolder keyPairHolder) { 30 | RSAKey.Builder builder = new RSAKey.Builder(((RSAKeyPairHolder) keyPairHolder).getPublicKey()) 31 | .keyUse(KeyUse.SIGNATURE) 32 | .algorithm(JWSAlgorithm.RS256) 33 | .keyID(keyPairHolder.getId()); 34 | 35 | return new JWKSet(builder.build()); 36 | } 37 | 38 | public static KeyPair generateKeys() throws NoSuchAlgorithmException { 39 | Provider provider = KeyFactory.getInstance("RSA").getProvider(); 40 | return KeyPairGenerator.getInstance("RSA", provider).generateKeyPair(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/init/Bootstrap.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.init; 2 | 3 | import dev.rexijie.auth.constants.GrantTypes; 4 | import dev.rexijie.auth.model.User; 5 | import dev.rexijie.auth.model.UserInfo; 6 | import dev.rexijie.auth.model.authority.Authority; 7 | import dev.rexijie.auth.model.authority.Role; 8 | import dev.rexijie.auth.model.authority.RoleEnum; 9 | import dev.rexijie.auth.model.client.Client; 10 | import dev.rexijie.auth.model.client.ClientProfiles; 11 | import dev.rexijie.auth.model.client.ClientTypes; 12 | import dev.rexijie.auth.repository.ClientRepository; 13 | import dev.rexijie.auth.repository.RoleRepository; 14 | import dev.rexijie.auth.repository.UserRepository; 15 | import dev.rexijie.auth.service.ClientService; 16 | import lombok.extern.slf4j.Slf4j; 17 | import org.springframework.boot.context.event.ApplicationStartedEvent; 18 | import org.springframework.context.ApplicationListener; 19 | import org.springframework.security.crypto.password.PasswordEncoder; 20 | import org.springframework.stereotype.Component; 21 | 22 | import java.time.LocalDate; 23 | import java.time.LocalDateTime; 24 | import java.util.List; 25 | import java.util.Set; 26 | import java.util.UUID; 27 | 28 | /** 29 | * @author Rex Ijiekhuamen 30 | * 08 Sep 2020 31 | */ 32 | @Slf4j 33 | @Component 34 | public class Bootstrap implements ApplicationListener { 35 | private final UserRepository userRepository; 36 | private final ClientRepository clientRepository; 37 | private final RoleRepository roleRepository; 38 | private final PasswordEncoder encoder; 39 | private final ClientService clientService; 40 | 41 | public Bootstrap(UserRepository userRepository, 42 | ClientRepository clientRepository, 43 | RoleRepository roleRepository, 44 | PasswordEncoder encoder, 45 | ClientService clientService) { 46 | this.userRepository = userRepository; 47 | this.clientRepository = clientRepository; 48 | this.roleRepository = roleRepository; 49 | this.encoder = encoder; 50 | this.clientService = clientService; 51 | } 52 | 53 | @Override 54 | public void onApplicationEvent(ApplicationStartedEvent event) { 55 | log.info("*********************************************"); 56 | log.info("* INITIALISING TEST DATA *"); 57 | log.info("*********************************************"); 58 | userRepository.deleteAll(); 59 | clientRepository.deleteAll(); 60 | roleRepository.deleteAll(); 61 | List roles = createRoles(); 62 | var userRole = getRoleFromEnum(roles, RoleEnum.USER); 63 | createClient(); 64 | createUser(userRole); 65 | log.info("*********************************************"); 66 | log.info("* <(0_0<) DONE (>0_0)> *"); 67 | log.info("*********************************************"); 68 | } 69 | 70 | private List createRoles() { 71 | var authority = new Authority(); 72 | authority.setId(generateId()); 73 | authority.setName("CAN_VIEW"); 74 | authority.setDescription("user can view stuff"); 75 | 76 | var userRole = new Role(RoleEnum.USER); 77 | userRole.setId(generateId()); 78 | userRole.getAuthorities().add(authority); 79 | 80 | var adminRole = new Role(RoleEnum.ADMIN); 81 | adminRole.setId(generateId()); 82 | roleRepository.saveAll(List.of(userRole, adminRole)); 83 | 84 | return List.of(userRole, adminRole); 85 | } 86 | 87 | private void createClient() { 88 | var registeredClient = new Client("Benoly management app", ClientTypes.CONFIDENTIAL, ClientProfiles.WEB); 89 | registeredClient.setClientId("management-app"); 90 | registeredClient.setClientSecret(encoder.encode("secret")); 91 | registeredClient.setAccessTokenValiditySeconds(10 * 60); 92 | registeredClient.setRefreshTokenValiditySeconds(15 * 60); 93 | registeredClient.setResourceIds(List.of("stock-api")); 94 | registeredClient.setScope(List.of("read", "read:appointments", "write", "remove", "profile", "openid", "email")); 95 | registeredClient.setRegisteredRedirectUri(Set.of("http://localhost:8008/login/oauth2/code/", 96 | "http://localhost:3000/")); 97 | registeredClient.setAuthorizedGrantTypes( 98 | List.of(GrantTypes.REFRESH_TOKEN, GrantTypes.PASSWORD, GrantTypes.AUTHORIZATION_CODE, GrantTypes.IMPLICIT)); 99 | 100 | Client save = clientService.addClient(registeredClient); 101 | log.info("added client {}", save.toString()); 102 | } 103 | 104 | private void createUser(Role role) { 105 | var user = new User("rexijie@gmail.com", encoder.encode("pass@rex"), role); 106 | var profile = UserInfo.builder() 107 | .firstName("Rex") 108 | .lastName("Ijiekhuamen") 109 | .username(user.getUsername()) 110 | .email(user.getUsername()) 111 | .dateOfBirth(LocalDate.of(2000, 1, 30)) // random day 112 | .build(); 113 | user.setId(generateId()); 114 | user.setEnabled(true); 115 | user.setUserInfo(profile); 116 | user.setAccountNonExpired(true); 117 | user.setAccountNonLocked(true); 118 | user.setCredentialsNonExpired(true); 119 | user.setCreatedAt(LocalDateTime.now()); 120 | User save = userRepository.save(user); 121 | log.info("added user {}", save); 122 | } 123 | 124 | private void logAllData() { 125 | userRepository.findAll() 126 | .forEach(user -> log.info("Added User {}", user)); 127 | clientRepository.findAll() 128 | .forEach(client -> log.info("Added client {}", client)); 129 | roleRepository.findAll() 130 | .forEach(role -> log.info("Added role {}", role)); 131 | } 132 | 133 | private Role getRoleFromEnum(List roles, RoleEnum roleEnum) { 134 | return roles.stream().filter( 135 | role -> role.getName().equals(roleEnum.getName()) 136 | ).findFirst().orElse(new Role(RoleEnum.USER)); 137 | } 138 | 139 | private String generateId() { 140 | return UUID.randomUUID().toString(); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/Entity.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model; 2 | 3 | import lombok.Data; 4 | import lombok.EqualsAndHashCode; 5 | 6 | import java.time.LocalDateTime; 7 | 8 | @Data 9 | @EqualsAndHashCode(callSuper = true) 10 | public class Entity extends Identified { 11 | private LocalDateTime createdAt; 12 | private LocalDateTime updatedAt; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/Identified.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.data.annotation.Id; 5 | 6 | @Data 7 | public abstract class Identified { 8 | @Id 9 | private String id; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/OidcAddress.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonRootName; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * @author Rex Ijiekhuamen 11 | * 09 Sep 2020 12 | */ 13 | @JsonRootName("address") 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | @Builder 18 | public class OidcAddress { 19 | private String streetAddress; 20 | private String locality; // city 21 | private String region; // state 22 | private String postalCode;// zip/postcode 23 | private String country; 24 | 25 | @Override 26 | public String toString() { 27 | return "{" + 28 | "\"streetAddress\": \"" + streetAddress + '\"' + 29 | ", \"locality\": \"" + locality + '\"' + 30 | ", \"region\": \"" + region + '\"' + 31 | ", \"postalCode\": \"" + postalCode + '\"' + 32 | ", \"country\": \"" + country + '\"' + 33 | '}'; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/User.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model; 2 | 3 | import dev.rexijie.auth.model.authority.Role; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | import org.springframework.data.mongodb.core.mapping.Document; 8 | import org.springframework.security.core.GrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Collection; 13 | import java.util.Objects; 14 | 15 | @Getter 16 | @Setter 17 | @Document 18 | @NoArgsConstructor 19 | public class User extends Entity implements UserDetails { 20 | private static final long serialVersionUID = 8668310170868956407L; 21 | private String username; 22 | private String password; 23 | private Role role; 24 | private transient UserInfo userInfo; 25 | private boolean isEnabled; 26 | private boolean accountNonExpired; 27 | private boolean accountNonLocked; 28 | private boolean credentialsNonExpired; 29 | 30 | public User(String username, String password, Role role) { 31 | this.username = username; 32 | this.password = password; 33 | this.role = role; 34 | } 35 | 36 | @Override 37 | public Collection getAuthorities() { 38 | return new ArrayList<>(role.getAuthorities()); 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | StringBuilder sb = new StringBuilder(); 44 | sb.append("User").append(" {"); 45 | sb.append("Username: ").append(this.username).append("; "); 46 | sb.append("Password: [PROTECTED]; "); 47 | sb.append("Profile: [PROTECTED]; "); 48 | sb.append("Role: ").append(this.role).append("; "); 49 | sb.append("Enabled: ").append(this.isEnabled).append("; "); 50 | sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; "); 51 | sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired) 52 | .append("; "); 53 | sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; "); 54 | 55 | sb.append(" }"); 56 | 57 | return sb.toString(); 58 | } 59 | 60 | @Override 61 | public boolean equals(Object o) { 62 | if (this == o) return true; 63 | if (o == null || getClass() != o.getClass()) return false; 64 | if (!super.equals(o)) return false; 65 | User user = (User) o; 66 | return username.equals(user.username) && 67 | role.equals(user.role) && 68 | Objects.equals(userInfo, user.userInfo); 69 | } 70 | 71 | @Override 72 | public int hashCode() { 73 | return Objects.hash(super.hashCode(), username, role, userInfo); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/UserInfo.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.annotation.JsonPropertyOrder; 5 | import lombok.*; 6 | import org.codehaus.jackson.annotate.JsonProperty; 7 | 8 | import java.time.LocalDate; 9 | 10 | @Data 11 | @EqualsAndHashCode(callSuper = true) 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | @JsonPropertyOrder({"name","firstname", "lastname", "fullname", "email", "dob"}) 16 | @JsonInclude(JsonInclude.Include.NON_NULL) 17 | public class UserInfo extends Entity { 18 | @JsonProperty("given_name") 19 | private String firstName; 20 | @JsonProperty("family_name") 21 | private String lastName; 22 | @JsonProperty("preferred_username") 23 | private String username; 24 | private String email; 25 | private boolean emailVerified; 26 | private OidcAddress address; 27 | @JsonProperty("phone_number") 28 | private String phoneNumber; 29 | @JsonProperty("phone_number_verified") 30 | private boolean phoneNumberVerified; 31 | @JsonProperty("birthdate") 32 | private LocalDate dateOfBirth; 33 | 34 | @JsonProperty("name") 35 | public String getFullName() { 36 | StringBuilder sb = new StringBuilder(); 37 | return sb.append(firstName) 38 | .append(" ") 39 | .append(lastName) 40 | .toString(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/authority/Authority.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.authority; 2 | 3 | import dev.rexijie.auth.constants.Authorities; 4 | import dev.rexijie.auth.model.Identified; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.EqualsAndHashCode; 8 | import lombok.NoArgsConstructor; 9 | import org.springframework.security.core.GrantedAuthority; 10 | 11 | @Data 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | @EqualsAndHashCode(callSuper = true) 15 | public class Authority extends Identified implements GrantedAuthority { 16 | private String name; 17 | private String description; 18 | 19 | public Authority(AuthorityEnum authorityEnum) { 20 | this.name = authorityEnum.getName(); 21 | this.description = authorityEnum.getDescription(); 22 | } 23 | 24 | @Override 25 | public String getAuthority() { 26 | return Authorities.ROLE_PREFIX + name; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/authority/AuthorityEnum.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.authority; 2 | 3 | public enum AuthorityEnum { 4 | CAN_CREATE("CAN_CREATE", "has authority to create"), 5 | CAN_MODIFY("CAN_CREATE", "has authority to modify"), 6 | CAN_VIEW("CAN_VIEW", "has authority to view"), 7 | CAN_DELETE("CAN_DELETE", "has authority to delete"), 8 | CLIENT("CLIENT", "application only authority. can request for tokens on behalf of users"); 9 | 10 | private final String name; 11 | private final String description; 12 | 13 | AuthorityEnum(String name, String description) { 14 | this.name = name; 15 | this.description = description; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public String getDescription() { 23 | return description; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/authority/Role.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.authority; 2 | 3 | import dev.rexijie.auth.model.Identified; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | import lombok.NoArgsConstructor; 8 | 9 | import java.io.Serializable; 10 | import java.util.Collection; 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | @EqualsAndHashCode(callSuper = true) 18 | public class Role extends Identified implements Serializable { 19 | private static final long serialVersionUID = 1373828140005067324L; 20 | private String name; 21 | private String description; 22 | private Set authorities = new HashSet<>(); 23 | 24 | public Role(RoleEnum roleEnum) { 25 | this.name = roleEnum.getName(); 26 | this.description = roleEnum.getDescription(); 27 | } 28 | 29 | public Role(RoleEnum roleEnum, Collection authorities) { 30 | this(roleEnum); 31 | this.authorities = Set.copyOf(authorities); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/authority/RoleEnum.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.authority; 2 | 3 | public enum RoleEnum { 4 | USER("USER", "Standard application user"), 5 | ADMIN("ADMIN", "System administrator"); 6 | 7 | private final String name; 8 | private final String description; 9 | 10 | RoleEnum(String name, String description) { 11 | this.name = name; 12 | this.description = description; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getDescription() { 20 | return description; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/client/Client.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.client; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import dev.rexijie.auth.model.authority.Authority; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | import org.springframework.data.annotation.Id; 10 | import org.springframework.data.mongodb.core.mapping.Document; 11 | import org.springframework.security.oauth2.provider.ClientRegistrationException; 12 | import org.springframework.security.oauth2.provider.client.BaseClientDetails; 13 | 14 | import java.time.LocalDateTime; 15 | import java.util.HashSet; 16 | import java.util.Objects; 17 | import java.util.Set; 18 | import java.util.UUID; 19 | 20 | // TODO - Use some client object fields in token generation 21 | @Getter 22 | @Setter 23 | @AllArgsConstructor 24 | @NoArgsConstructor 25 | @Document 26 | @JsonInclude(JsonInclude.Include.NON_NULL) 27 | public class Client extends BaseClientDetails { 28 | @Id 29 | private String id; 30 | private String clientName; 31 | private String clientType = ClientTypes.CONFIDENTIAL.getName(); 32 | private String clientProfile = ClientProfiles.WEB.getName(); 33 | private String logoUri; 34 | private String clientUri; // uri to the homepage of the client; 35 | private String policyUri; 36 | // private String jwksUri; 37 | // private String jwks; 38 | private String selectorIdentifierUri; // json file showing alternate redirect uris 39 | private String subjectType; // subject types supported to use for requests to this client 40 | private String tokenEndpointAuthMethod; 41 | private int defaultMaxAge; // default value for max_age claim 42 | private boolean requireAuthTime; // is auth time claim required? 43 | 44 | private LocalDateTime createdAt; 45 | private LocalDateTime updatedAt; 46 | 47 | public Client(String clientName, ClientTypes clientType, 48 | ClientProfiles clientProfile) { 49 | this.id = UUID.randomUUID().toString(); 50 | this.clientName = clientName; 51 | this.clientType = clientType == null ? ClientTypes.CONFIDENTIAL.getName() : clientType.getName(); 52 | this.clientProfile = clientProfile == null ? ClientProfiles.WEB.getName() : clientProfile.getName(); 53 | this.createdAt = LocalDateTime.now(); 54 | } 55 | 56 | public String getId() { 57 | return id; 58 | } 59 | 60 | public void setId(String id) { 61 | this.id = id; 62 | } 63 | 64 | public void addAuthority(Authority authority) { 65 | if (this.getAuthorities().contains(authority)) return; 66 | this.getAuthorities().add(authority); 67 | } 68 | 69 | // this method will be moved to a client builder or a validator class 70 | public void addRedirectUri(String uri) { 71 | if (getClientType() == null) 72 | throw new IllegalStateException("can not add redirect uri before specifying client type"); 73 | if (isPublicClient()) { 74 | // public clients must be served via https 75 | if (!uri.matches("^(https)://(\\w)*(.\\w*)+(/(\\w)*)*$")) 76 | throw new ClientRegistrationException("Invalid redirect Uri for public client. public clients must use the https scheme"); 77 | } 78 | this.getRegisteredRedirectUri().add(uri); 79 | } 80 | 81 | @Override 82 | public void setRegisteredRedirectUri(Set registeredRedirectUris) { 83 | super.setRegisteredRedirectUri(new HashSet<>()); 84 | for (String uri : registeredRedirectUris) { 85 | addRedirectUri(uri); 86 | } 87 | } 88 | 89 | public boolean isPublicClient() { 90 | return getClientType().equals(ClientTypes.PUBLIC.getName()); 91 | } 92 | 93 | @Override 94 | public boolean equals(Object o) { 95 | if (this == o) return true; 96 | if (o == null || getClass() != o.getClass()) return false; 97 | if (!super.equals(o)) return false; 98 | Client client = (Client) o; 99 | return Objects.equals(getId(), client.getId()) && 100 | Objects.equals(getClientName(), client.getClientName()) && 101 | Objects.equals(getClientType(), client.getClientType()) && 102 | Objects.equals(getClientProfile(), client.getClientProfile()) && 103 | Objects.equals(super.getClientId(), client.getClientId()) && 104 | Objects.equals(super.getClientSecret(), client.getClientSecret()); 105 | } 106 | 107 | @Override 108 | public int hashCode() { 109 | return Objects.hash(super.hashCode()); 110 | } 111 | 112 | @Override 113 | public String toString() { 114 | return "Client {" + 115 | "id: '" + getId() + '\'' + 116 | ", name: '" + getClientName() + '\'' + 117 | ", type: '" + getClientType() + '\'' + 118 | ", clientId: '" + this.getClientId() + '\'' + 119 | ", clientSecret: '" + "[SECRET]" + '\'' + 120 | ", scope: '" + this.getScope() + '\'' + 121 | ", resourceIds: '" + this.getResourceIds() + '\'' + 122 | ", authorizedGrantTypes: '" + this.getAuthorizedGrantTypes() + '\'' + 123 | ", registeredRedirectUris: '" + this.getRegisteredRedirectUri() + '\'' + 124 | ", authorities: '" + this.getAuthorities() + '\'' + 125 | ", accessTokenValiditySeconds: '" + this.getAccessTokenValiditySeconds() + '\'' + 126 | ", refreshTokenValiditySeconds: '" + this.getRefreshTokenValiditySeconds() + '\'' + 127 | ", additionalInformation: '" + this.getAdditionalInformation() + '\'' + 128 | ", createdAt: '" + getCreatedAt() + '\'' + 129 | ", updatedAt: '" + getUpdatedAt() + '\'' + 130 | "}"; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/client/ClientProfiles.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.client; 2 | 3 | public enum ClientProfiles { 4 | WEB("web", "A confidential client running on a server"), 5 | USER_AGENT_APPLICATION("user-agent-web-application", "A public client running on a browser or a user-agent"), 6 | NATIVE("native", "A public client installed and executed on a device"); 7 | 8 | private final String name; 9 | private final String description; 10 | ClientProfiles(String name, String description) { 11 | this.name = name; 12 | this.description = description; 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public String getDescription() { 20 | return description; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/client/ClientTypes.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.client; 2 | 3 | public enum ClientTypes { 4 | CONFIDENTIAL("confidential", "Client that can maintain the confidentiality of their client secret"), 5 | PUBLIC("public", "Client that can not maintain the confidentiality of their client secret"); 6 | 7 | private final String name; 8 | private final String description; 9 | ClientTypes(String name, String description) { 10 | this.name = name; 11 | this.description = description; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public String getDescription() { 19 | return description; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/AccessToken.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import dev.rexijie.auth.util.TokenUtils; 4 | import lombok.Data; 5 | import lombok.NonNull; 6 | import org.springframework.data.annotation.Id; 7 | import org.springframework.data.mongodb.core.mapping.Document; 8 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | 11 | @Data 12 | @Document(collection = "accesstokens") 13 | public class AccessToken { 14 | @Id 15 | private String tokenId; 16 | private OAuth2AccessToken token; 17 | private String username; 18 | private String clientId; 19 | private String authenticationId; 20 | private String refreshToken; 21 | private String authentication; 22 | 23 | public OAuth2Authentication getAuthentication() { 24 | return TokenUtils.deserializeAuthentication(this.authentication); 25 | } 26 | 27 | public void setAuthentication(@NonNull OAuth2Authentication authentication) { 28 | this.authentication = TokenUtils.serializeAuthentication(authentication); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/AuthorizationToken.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import dev.rexijie.auth.model.Entity; 4 | import lombok.*; 5 | 6 | import java.time.LocalDateTime; 7 | 8 | @Data 9 | @Builder 10 | @EqualsAndHashCode(callSuper = true) 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class AuthorizationToken extends Entity { 14 | private byte[] authentication; 15 | private String username; 16 | private String code; 17 | private boolean used; 18 | private LocalDateTime expiresAt; 19 | 20 | public boolean isExpired() { 21 | return expiresAt.isBefore(LocalDateTime.now()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/IDToken.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import dev.rexijie.auth.util.ObjectUtils; 5 | import dev.rexijie.auth.util.TokenUtils; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 10 | import org.springframework.security.oauth2.common.OAuth2RefreshToken; 11 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 12 | 13 | import java.util.*; 14 | 15 | import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames.ID_TOKEN; 16 | 17 | @Data 18 | @NoArgsConstructor 19 | @Builder 20 | @JsonInclude(JsonInclude.Include.NON_NULL) 21 | public class IDToken implements OAuth2AccessToken { 22 | public static final String TYPE = ID_TOKEN; 23 | private OidcIdToken token; 24 | 25 | public IDToken(OidcIdToken idToken) { 26 | this.token = idToken; 27 | } 28 | 29 | @Override 30 | public Map getAdditionalInformation() { 31 | return Collections.emptyMap(); 32 | } 33 | 34 | @Override 35 | public Set getScope() { 36 | return Collections.emptySet(); 37 | } 38 | 39 | @Override 40 | public OAuth2RefreshToken getRefreshToken() { 41 | return null; 42 | } 43 | 44 | @Override 45 | public String getTokenType() { 46 | return TYPE; 47 | } 48 | 49 | @Override 50 | public boolean isExpired() { 51 | return System.currentTimeMillis() > getExpiration().getTime(); 52 | } 53 | 54 | @Override 55 | public Date getExpiration() { 56 | return new Date(Objects.requireNonNull(getToken().getExpiresAt()).toEpochMilli()); 57 | } 58 | 59 | @Override 60 | public int getExpiresIn() { 61 | return (int) (getExpiration().getTime() - System.currentTimeMillis()); 62 | } 63 | 64 | @Override 65 | public String getValue() { 66 | return null; 67 | } 68 | 69 | public synchronized Map getClaims() { 70 | Map cleanedMapCopy = ObjectUtils.cleanMap(getToken().getClaims()); 71 | return TokenUtils.toOpenIdCompliantMap(cleanedMapCopy); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/KeyPairHolder.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import java.security.KeyPair; 4 | import java.security.PrivateKey; 5 | import java.security.PublicKey; 6 | 7 | public interface KeyPairHolder { 8 | String getId(); 9 | 10 | KeyPair getKeyPair(); 11 | 12 | K1 getPublicKey(); 13 | 14 | K2 getPrivateKey(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/RSAKeyPairHolder.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import java.security.KeyPair; 4 | import java.security.interfaces.RSAPrivateKey; 5 | import java.security.interfaces.RSAPublicKey; 6 | 7 | public class RSAKeyPairHolder implements KeyPairHolder { 8 | 9 | private final String id; 10 | private final KeyPair keyPair; 11 | 12 | 13 | public RSAKeyPairHolder(String id, KeyPair keyPair) { 14 | this.id = id; 15 | this.keyPair = keyPair; 16 | } 17 | 18 | @Override 19 | public String getId() { 20 | return this.id; 21 | } 22 | 23 | @Override 24 | public KeyPair getKeyPair() { 25 | return this.keyPair; 26 | } 27 | 28 | @Override 29 | public RSAPublicKey getPublicKey() { 30 | return (RSAPublicKey) keyPair.getPublic(); 31 | } 32 | 33 | @Override 34 | public RSAPrivateKey getPrivateKey() { 35 | return (RSAPrivateKey) keyPair.getPrivate(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/model/token/RefreshToken.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.model.token; 2 | 3 | import dev.rexijie.auth.util.TokenUtils; 4 | import lombok.Data; 5 | import lombok.NonNull; 6 | import org.springframework.data.annotation.Id; 7 | import org.springframework.data.mongodb.core.mapping.Document; 8 | import org.springframework.security.oauth2.common.OAuth2RefreshToken; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | 11 | @Data 12 | @Document(collection = "refreshtokens") 13 | public class RefreshToken { 14 | @Id 15 | private String tokenId; 16 | private OAuth2RefreshToken token; 17 | private String authentication; 18 | 19 | public OAuth2Authentication getAuthentication() { 20 | return TokenUtils.deserializeAuthentication(this.authentication); 21 | } 22 | 23 | public void setAuthentication(@NonNull OAuth2Authentication authentication) { 24 | this.authentication = TokenUtils.serializeAuthentication(authentication); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/AccessTokenRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.token.AccessToken; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | public interface AccessTokenRepository extends MongoRepository { 10 | List findAllByClientId(String clientId); 11 | 12 | List findAllByClientIdAndUsername(String clientId, String username); 13 | 14 | Optional findByTokenId(String tokenId); 15 | 16 | Optional findByRefreshToken(String refreshToken); 17 | 18 | Optional findByAuthenticationId(String authenticationId); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/AuthorizationTokenRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.token.AuthorizationToken; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface AuthorizationTokenRepository extends MongoRepository { 9 | public Optional findByCode(String id); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/ClientRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.client.Client; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | public interface ClientRepository extends MongoRepository { 7 | Client findByClientId(String clientId); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/RefreshTokenRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.token.RefreshToken; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface RefreshTokenRepository extends MongoRepository { 9 | Optional findByTokenId(String tokenId); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.authority.Role; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | public interface RoleRepository extends MongoRepository { 7 | Role findByName(String name); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.repository; 2 | 3 | import dev.rexijie.auth.model.User; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | public interface UserRepository extends MongoRepository { 7 | User findByUsername(String username); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/ClientSecretGenerator.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service; 2 | 3 | 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.security.crypto.codec.Hex; 6 | import org.springframework.stereotype.Component; 7 | 8 | import java.security.NoSuchAlgorithmException; 9 | import java.security.SecureRandom; 10 | 11 | /** 12 | * Factory for generating random String keys. 13 | * It makes use of {@link SecureRandom} to generate random bytes 14 | * of a given length 15 | * 16 | * @author Rex Ijiekhuamen 17 | */ 18 | 19 | @Slf4j 20 | @Component 21 | public class ClientSecretGenerator implements SecretGenerator { 22 | final int DEFAULT_KEY_LENGTH = 32; 23 | private final int bytesKeyLength; 24 | 25 | public ClientSecretGenerator() { 26 | this.bytesKeyLength = this.DEFAULT_KEY_LENGTH; 27 | } 28 | 29 | public ClientSecretGenerator(int bytesKeyLength) { 30 | this.bytesKeyLength = bytesKeyLength; 31 | } 32 | 33 | @Override 34 | public String generate() { 35 | return generate(bytesKeyLength); 36 | } 37 | 38 | @Override 39 | public String generate(int length) { 40 | char[] charEncodedBytes = Hex.encode(generateBytes(length)); 41 | return new String(charEncodedBytes); 42 | } 43 | 44 | private byte[] generateBytes(int byteLength) { 45 | SecureRandom secureRandom; 46 | try { 47 | secureRandom = SecureRandom.getInstanceStrong(); 48 | } catch (NoSuchAlgorithmException ex) { 49 | log.warn("No Strong secure algorithm available in JDK, switching to default instance"); 50 | secureRandom = new SecureRandom(); 51 | } 52 | 53 | byte[] bytes = new byte[byteLength]; 54 | secureRandom.nextBytes(bytes); 55 | 56 | return bytes; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/ClientService.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service; 2 | 3 | import dev.rexijie.auth.model.client.Client; 4 | import org.springframework.security.oauth2.provider.ClientDetailsService; 5 | import org.springframework.security.oauth2.provider.NoSuchClientException; 6 | 7 | import java.util.List; 8 | 9 | public interface ClientService extends ClientDetailsService { 10 | Client addClient(Client client); 11 | Client updateClient(String clientId, Client client); 12 | Client updateClientSecret(String clientId, String secret); 13 | void removeClientDetails(String clientId) throws NoSuchClientException; 14 | List listClientDetails(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/SecretGenerator.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service; 2 | 3 | /** 4 | * Class which represent entities able to generate secrets 5 | * @author Rex Ijiekhuamen 6 | */ 7 | public interface SecretGenerator { 8 | String generate(); 9 | String generate(int length); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/UserService.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service; 2 | 3 | import dev.rexijie.auth.model.User; 4 | import dev.rexijie.auth.model.UserInfo; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | 7 | public interface UserService extends UserDetailsService { 8 | User findUserByUsername(String username); 9 | UserInfo findProfileByUserId(String id); 10 | UserInfo findProfileByUsername(String username); 11 | User addUser(User user); 12 | User getUserById(String id); 13 | User updateUserInfo(User user); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/impl/ClientServiceImpl.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service.impl; 2 | 3 | import dev.rexijie.auth.constants.GrantTypes; 4 | import dev.rexijie.auth.model.authority.Authority; 5 | import dev.rexijie.auth.model.authority.AuthorityEnum; 6 | import dev.rexijie.auth.model.client.Client; 7 | import dev.rexijie.auth.model.client.ClientProfiles; 8 | import dev.rexijie.auth.model.client.ClientTypes; 9 | import dev.rexijie.auth.repository.ClientRepository; 10 | import dev.rexijie.auth.service.ClientService; 11 | import dev.rexijie.auth.service.SecretGenerator; 12 | import dev.rexijie.auth.util.ObjectUtils; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.cache.annotation.CacheEvict; 15 | import org.springframework.cache.annotation.Cacheable; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.security.oauth2.provider.ClientDetails; 18 | import org.springframework.security.oauth2.provider.ClientRegistrationException; 19 | import org.springframework.security.oauth2.provider.NoSuchClientException; 20 | import org.springframework.stereotype.Service; 21 | 22 | import java.time.LocalDateTime; 23 | import java.util.List; 24 | 25 | import static dev.rexijie.auth.util.TokenUtils.generateUUID; 26 | 27 | @Service 28 | @Slf4j 29 | public class ClientServiceImpl implements ClientService { 30 | private final ClientRepository clientRepository; 31 | private final PasswordEncoder encoder; 32 | private final SecretGenerator secretGenerator; 33 | 34 | public ClientServiceImpl(ClientRepository clientRepository, 35 | PasswordEncoder encoder, 36 | SecretGenerator secretGenerator) { 37 | this.clientRepository = clientRepository; 38 | this.encoder = encoder; 39 | this.secretGenerator = secretGenerator; 40 | } 41 | 42 | @Override 43 | public Client addClient(Client client) { 44 | var defaultClient = createDefaultClient(); 45 | assignNonEmptyFields(client, defaultClient); 46 | 47 | String secret = secretGenerator.generate(); 48 | if (defaultClient.getClientSecret() == null) 49 | defaultClient.setClientSecret(encoder.encode(secret)); 50 | 51 | var returnedClient = clientRepository.save(defaultClient); 52 | returnedClient.setClientSecret(secret); 53 | 54 | return returnedClient; 55 | } 56 | 57 | public Client findByClientId(String clientId) { 58 | Client foundClient = clientRepository.findByClientId(clientId); 59 | if (foundClient == null) throw new NoSuchClientException("client with id " + clientId + "not found"); 60 | return foundClient; 61 | } 62 | 63 | @Override 64 | @Cacheable(value = "registered-clients", key = "#root.args[0]") 65 | public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException { 66 | Client found; 67 | try { 68 | found = this.findByClientId(clientId); 69 | } catch (NoSuchClientException e) { 70 | throw new ClientRegistrationException("Client has not been registered"); 71 | } 72 | return found; 73 | } 74 | 75 | @Override 76 | @CacheEvict(value = "registered-clients", key = "#root.args[0]") 77 | public Client updateClientSecret(String clientId, String secret) { 78 | var client = findByClientId(clientId); 79 | client.setClientSecret(encoder.encode(secret)); 80 | return clientRepository.save(client); 81 | } 82 | 83 | @Override 84 | @CacheEvict(value = "registered-clients", key = "#root.args[0]") 85 | public Client updateClient(String clientId, Client newClient) { 86 | var client = findByClientId(clientId); 87 | 88 | assignNonEmptyFields(newClient, client); 89 | 90 | return clientRepository.save(newClient); 91 | } 92 | 93 | @Override 94 | public void removeClientDetails(String clientId) throws NoSuchClientException { 95 | var client = findByClientId(clientId); 96 | 97 | clientRepository.deleteById(client.getId()); 98 | } 99 | 100 | @Override 101 | public List listClientDetails() { 102 | return clientRepository.findAll(); 103 | } 104 | 105 | private Client createDefaultClient() { 106 | var defaultClient = new Client(null, ClientTypes.CONFIDENTIAL, ClientProfiles.WEB); 107 | defaultClient.setId(generateUUID()); 108 | defaultClient.setClientId(secretGenerator.generate(8)); 109 | defaultClient.setAccessTokenValiditySeconds(10 * 60); 110 | defaultClient.setRefreshTokenValiditySeconds(15 * 60); 111 | defaultClient.setScope(List.of("read", "write", "profile", "openid", "email")); 112 | defaultClient.setAuthorizedGrantTypes(List.of(GrantTypes.PASSWORD, GrantTypes.AUTHORIZATION_CODE, GrantTypes.REFRESH_TOKEN)); 113 | defaultClient.setAuthorities(List.of(createClientAuthority())); 114 | defaultClient.setCreatedAt(LocalDateTime.now()); 115 | 116 | return defaultClient; 117 | } 118 | 119 | private Authority createClientAuthority() { 120 | return new Authority(AuthorityEnum.CLIENT); 121 | } 122 | 123 | private void assignNonEmptyFields(Client from, Client to) { 124 | ObjectUtils.applyIfNonNull(from.getId(), to::setId); 125 | ObjectUtils.applyIfNonNull(from.getClientName(), to::setClientName); 126 | ObjectUtils.applyIfNonNull(from.getClientType(), to::setClientType); 127 | ObjectUtils.applyIfNonNull(from.getClientProfile(), to::setClientProfile); 128 | ObjectUtils.applyIfNonNull(from.getClientId(), to::setClientId); 129 | ObjectUtils.applyIfNonNull(from.getClientSecret(), to::setClientSecret); 130 | ObjectUtils.applyIfNonNull(from.getScope(), to::setScope); 131 | ObjectUtils.applyIfNonNull(from.getResourceIds(), to::setResourceIds); 132 | ObjectUtils.applyIfNonNull(from.getAuthorizedGrantTypes(), to::setAuthorizedGrantTypes); 133 | ObjectUtils.applyIfNonNull(from.getRegisteredRedirectUri(), to::setRegisteredRedirectUri); 134 | ObjectUtils.applyIfNonNull(from.getAutoApproveScopes(), to::setAutoApproveScopes); 135 | ObjectUtils.applyIfNonNull(from.getAuthorities(), to::setAuthorities); 136 | ObjectUtils.applyIfNonNull(from.getAccessTokenValiditySeconds(), to::setAccessTokenValiditySeconds); 137 | ObjectUtils.applyIfNonNull(from.getRefreshTokenValiditySeconds(), to::setRefreshTokenValiditySeconds); 138 | ObjectUtils.applyIfNonNull(from.getAdditionalInformation(), to::setAdditionalInformation); 139 | // ObjectUtils.applyIfNonNull(from.getJwksuri(), to::setJwksuri); 140 | // ObjectUtils.applyIfNonNull(from.getJwks(), to::setJwks); 141 | ObjectUtils.applyIfNonNull(from.getLogoUri(), to::setLogoUri); 142 | ObjectUtils.applyIfNonNull(from.getClientUri(), to::setClientUri); 143 | ObjectUtils.applyIfNonNull(from.getPolicyUri(), to::setPolicyUri); 144 | ObjectUtils.applyIfNonNull(from.getSelectorIdentifierUri(), to::setSelectorIdentifierUri); 145 | ObjectUtils.applyIfNonNull(from.getSubjectType(), to::setSubjectType); 146 | ObjectUtils.applyIfNonNull(from.getTokenEndpointAuthMethod(), to::setTokenEndpointAuthMethod); 147 | ObjectUtils.applyIfNonNull(from.getDefaultMaxAge(), to::setDefaultMaxAge); 148 | ObjectUtils.applyIfNonNull(from.isRequireAuthTime(), to::setRequireAuthTime); 149 | 150 | 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.service.impl; 2 | 3 | import dev.rexijie.auth.errors.UserExistsException; 4 | import dev.rexijie.auth.model.User; 5 | import dev.rexijie.auth.model.UserInfo; 6 | import dev.rexijie.auth.model.authority.Authority; 7 | import dev.rexijie.auth.repository.UserRepository; 8 | import dev.rexijie.auth.service.UserService; 9 | import dev.rexijie.auth.util.ObjectUtils; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.stereotype.Service; 15 | 16 | import java.time.LocalDateTime; 17 | import java.util.Optional; 18 | import java.util.UUID; 19 | 20 | @Service 21 | @Slf4j 22 | public class UserServiceImpl implements UserService { 23 | private final UserRepository userRepository; 24 | private final PasswordEncoder encoder; 25 | 26 | public UserServiceImpl(UserRepository userRepository, 27 | PasswordEncoder encoder) { 28 | this.userRepository = userRepository; 29 | this.encoder = encoder; 30 | } 31 | 32 | @Override 33 | public User findUserByUsername(String username) { 34 | return (User) loadUserByUsername(username); 35 | } 36 | 37 | @Override 38 | public UserDetails loadUserByUsername(String username) { 39 | var user = userRepository.findByUsername(username); 40 | if (user == null) throw new UsernameNotFoundException("User does not exist"); 41 | user.getRole().getAuthorities().add(new Authority(user.getRole().getName(), user.getRole().getDescription())); 42 | return user; 43 | } 44 | 45 | @Override 46 | public UserInfo findProfileByUserId(String id) { 47 | return null; 48 | } 49 | 50 | @Override 51 | public UserInfo findProfileByUsername(String username) { 52 | return findUserByUsername(username).getUserInfo(); 53 | } 54 | 55 | @Override 56 | public User addUser(User user) { 57 | User storedUser = findUserByUsername(user.getUsername()); 58 | if (storedUser != null) throw new UserExistsException("A user with the username exists"); 59 | 60 | String id = UUID.fromString(user.getUsername()).toString(); 61 | user.setId(id); 62 | user.setCreatedAt(LocalDateTime.now()); 63 | user.setPassword(encoder.encode(user.getPassword())); 64 | return save(user); 65 | } 66 | 67 | @Override 68 | public User getUserById(String id) { 69 | 70 | Optional userOp = userRepository.findById(id); 71 | if (userOp.isEmpty()) throw new UsernameNotFoundException("user does not exist"); 72 | User user = userOp.get(); 73 | user.getRole() 74 | .getAuthorities() 75 | .add(new Authority(user.getRole().getName(), user.getRole().getDescription())); 76 | 77 | return user; 78 | } 79 | 80 | @Override 81 | public User updateUserInfo(User user) { 82 | User storedUser = findUserByUsername(user.getUsername()); 83 | if (storedUser == null) return null; 84 | 85 | UserInfo sentUserInfo = user.getUserInfo(); 86 | UserInfo storedInfo = storedUser.getUserInfo(); 87 | 88 | ObjectUtils.applyIfNonNull(sentUserInfo.getUsername(), storedInfo::setUsername); 89 | ObjectUtils.applyIfNonNull(sentUserInfo.getFirstName(), storedInfo::setFirstName); 90 | ObjectUtils.applyIfNonNull(sentUserInfo.getLastName(), storedInfo::setLastName); 91 | ObjectUtils.applyIfNonNull(sentUserInfo.getEmail(), storedInfo::setEmail); 92 | ObjectUtils.applyIfNonNull(sentUserInfo.getDateOfBirth(), storedInfo::setDateOfBirth); 93 | ObjectUtils.applyIfNonNull(sentUserInfo.getAddress(), storedInfo::setAddress); 94 | return update(storedUser); 95 | } 96 | 97 | protected User updatePassword(String username, String rawPassword) { 98 | User userToUpdate = findUserByUsername(username); 99 | // String encryptedPassword = encoder.encode(rawPassword); 100 | // if (encryptedPassword.equals(userToUpdate.getPassword())) 101 | userToUpdate.setPassword(rawPassword); 102 | return update(userToUpdate); 103 | } 104 | 105 | protected User disableUser(String username) { 106 | User user = findUserByUsername(username); 107 | user.setAccountNonLocked(false); 108 | return update(user); 109 | } 110 | 111 | protected User update(User user) { 112 | user.setUpdatedAt(LocalDateTime.now()); 113 | return userRepository.save(user); 114 | } 115 | 116 | protected User save(User user) { 117 | return userRepository.save(user); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/DefaultJwtClaimEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import dev.rexijie.auth.service.UserService; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.impl.DefaultClaims; 6 | import org.springframework.beans.factory.annotation.Value; 7 | 8 | import java.util.Date; 9 | import java.util.Map; 10 | 11 | import static io.jsonwebtoken.Claims.ISSUED_AT; 12 | 13 | public class DefaultJwtClaimEnhancer implements JwtClaimsEnhancer { 14 | @Value("${oauth2.openid.discovery.issuer:https://rexijie.dev}") 15 | private String issuer; 16 | 17 | private final UserService userService; 18 | 19 | public DefaultJwtClaimEnhancer(UserService userService) { 20 | this.userService = userService; 21 | } 22 | 23 | public Claims enhance(Map originalClaims) { 24 | Claims claims = new DefaultClaims(originalClaims); 25 | String userName = claims.get(dev.rexijie.auth.constants.Claims.JwtClaims.USERNAME_CLAIM, String.class); 26 | claims.remove(dev.rexijie.auth.constants.Claims.JwtClaims.USERNAME_CLAIM); 27 | 28 | var user = userService.findUserByUsername(userName); 29 | var role = user.getRole().getName(); 30 | 31 | if (!claims.containsKey(ISSUED_AT)) 32 | claims.setIssuedAt(new Date()); 33 | claims.setSubject(userName); 34 | claims.setIssuer(issuer); 35 | claims.put(dev.rexijie.auth.constants.Claims.JwtClaims.ROLE_CLAIM, role); 36 | 37 | return claims; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/JpaTokenStore.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import dev.rexijie.auth.repository.AccessTokenRepository; 4 | import dev.rexijie.auth.repository.RefreshTokenRepository; 5 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 6 | import org.springframework.security.oauth2.common.OAuth2RefreshToken; 7 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 8 | import org.springframework.security.oauth2.provider.token.TokenStore; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.Collection; 12 | 13 | @Component 14 | public class JpaTokenStore implements TokenStore { 15 | private final AccessTokenRepository accessTokenRepository; 16 | private final RefreshTokenRepository refreshTokenRepository; 17 | 18 | public JpaTokenStore(AccessTokenRepository accessTokenRepository, 19 | RefreshTokenRepository refreshTokenRepository) { 20 | this.accessTokenRepository = accessTokenRepository; 21 | this.refreshTokenRepository = refreshTokenRepository; 22 | } 23 | 24 | @Override 25 | public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { 26 | return null; 27 | } 28 | 29 | @Override 30 | public OAuth2Authentication readAuthentication(String token) { 31 | return null; 32 | } 33 | 34 | @Override 35 | public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { 36 | 37 | } 38 | 39 | @Override 40 | public OAuth2AccessToken readAccessToken(String tokenValue) { 41 | return null; 42 | } 43 | 44 | @Override 45 | public void removeAccessToken(OAuth2AccessToken token) { 46 | 47 | } 48 | 49 | @Override 50 | public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { 51 | 52 | } 53 | 54 | @Override 55 | public OAuth2RefreshToken readRefreshToken(String tokenValue) { 56 | return null; 57 | } 58 | 59 | @Override 60 | public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { 61 | return null; 62 | } 63 | 64 | @Override 65 | public void removeRefreshToken(OAuth2RefreshToken token) { 66 | 67 | } 68 | 69 | @Override 70 | public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { 71 | 72 | } 73 | 74 | @Override 75 | public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { 76 | return null; 77 | } 78 | 79 | @Override 80 | public Collection findTokensByClientIdAndUserName(String clientId, String userName) { 81 | return null; 82 | } 83 | 84 | @Override 85 | public Collection findTokensByClientId(String clientId) { 86 | return null; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/JwtClaimsEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * This class takes a map of claims in a jwt and returns a new map 7 | * with updated claims. 8 | */ 9 | 10 | public interface JwtClaimsEnhancer { 11 | Map enhance(Map originalClaims); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/JwtTokenConverter.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import dev.rexijie.auth.model.token.IDToken; 4 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 5 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 6 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 7 | import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | import static io.jsonwebtoken.Claims.ISSUER; 13 | import static io.jsonwebtoken.Claims.SUBJECT; 14 | import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AZP; 15 | import static org.springframework.security.oauth2.provider.token.UserAuthenticationConverter.USERNAME; 16 | 17 | /** 18 | * Custom access token converter to add custom claims. 19 | * This token converter, it converts an OAuth2Access token to and from a Map 20 | */ 21 | public class JwtTokenConverter extends DefaultAccessTokenConverter { 22 | 23 | private final JwtClaimsEnhancer jwtClaimsEnhancer; 24 | 25 | public JwtTokenConverter(JwtClaimsEnhancer jwtClaimsEnhancer) { 26 | this.jwtClaimsEnhancer = jwtClaimsEnhancer; 27 | } 28 | 29 | /** 30 | * Convert access token using the default converter and add custom claims 31 | * access token type was set in the token enhancer 32 | * @param token OAuth2 access token to convert 33 | * @param authentication authentication to convert 34 | */ 35 | @Override 36 | public Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { 37 | if (token.getTokenType().equals(IDToken.TYPE)) 38 | return ((IDToken) token).getClaims(); 39 | 40 | var superToken = super.convertAccessToken(token, authentication); 41 | return jwtClaimsEnhancer.enhance(new HashMap<>(superToken)); 42 | } 43 | 44 | /** 45 | * Extract access token from a previously converted Token 46 | * 47 | * @param value the value of the token 48 | * @param map A map of the previously converted token 49 | * @return Original Token 50 | */ 51 | @Override 52 | public OAuth2AccessToken extractAccessToken(String value, Map map) { 53 | var superToken = super.extractAccessToken(value, map); 54 | var info = superToken.getAdditionalInformation(); 55 | 56 | DefaultOAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(superToken); 57 | oAuth2AccessToken.setAdditionalInformation(info); 58 | info.remove(ISSUER); 59 | 60 | return oAuth2AccessToken; 61 | } 62 | 63 | @Override 64 | public OAuth2Authentication extractAuthentication(Map map) { 65 | var response = new HashMap(map); 66 | Object username = response.remove(SUBJECT); 67 | response.put(USERNAME, username); 68 | if (response.containsKey(AZP) && !response.containsKey(CLIENT_ID)) 69 | response.put(CLIENT_ID, response.get(AZP)); 70 | return super.extractAuthentication(response); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/JwtTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import dev.rexijie.auth.model.token.KeyPairHolder; 4 | import lombok.SneakyThrows; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.security.jwt.JwtHelper; 7 | import org.springframework.security.jwt.crypto.sign.RsaSigner; 8 | import org.springframework.security.jwt.crypto.sign.Signer; 9 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 10 | import org.springframework.security.oauth2.common.util.JsonParser; 11 | import org.springframework.security.oauth2.common.util.JsonParserFactory; 12 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 13 | import org.springframework.security.oauth2.provider.token.store.IssuerClaimVerifier; 14 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 15 | import org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier; 16 | 17 | import java.net.URL; 18 | import java.security.KeyPair; 19 | import java.security.interfaces.RSAPrivateKey; 20 | import java.security.interfaces.RSAPublicKey; 21 | import java.util.Base64; 22 | import java.util.Map; 23 | 24 | public class JwtTokenEnhancer extends JwtAccessTokenConverter { 25 | @Value("${oauth2.openid.discovery.issuer:https://rexijie.dev}") 26 | private String issuer; 27 | private final JsonParser objectMapper = JsonParserFactory.create(); 28 | private final Signer signer; 29 | private final KeyPairHolder keyPairHolder; 30 | 31 | public JwtTokenEnhancer(KeyPairHolder keyPairHolder) { 32 | super(); 33 | this.keyPairHolder = keyPairHolder; 34 | setKeyPair(keyPairHolder.getKeyPair()); 35 | this.signer = new RsaSigner((RSAPrivateKey) keyPairHolder.getPrivateKey()); 36 | } 37 | 38 | @SneakyThrows 39 | @Override 40 | public void setJwtClaimsSetVerifier(JwtClaimsSetVerifier jwtClaimsSetVerifier) { 41 | var issuerUrl = new URL(issuer); 42 | super.setJwtClaimsSetVerifier(new IssuerClaimVerifier(issuerUrl)); 43 | } 44 | 45 | @Override 46 | public void setKeyPair(KeyPair keyPair) { 47 | super.setKeyPair(keyPair); 48 | this.setVerifierKey(generateRSAString(keyPair)); 49 | } 50 | 51 | protected String generateRSAString(KeyPair keyPair) { 52 | RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 53 | return "-----BEGIN PUBLIC KEY-----" 54 | + Base64.getEncoder().encodeToString(publicKey.getEncoded()) 55 | + "-----END PUBLIC KEY-----"; 56 | } 57 | 58 | @Override 59 | protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 60 | String content; 61 | final Map customHeaders; 62 | try { 63 | content = objectMapper.formatMap( 64 | getAccessTokenConverter() 65 | .convertAccessToken(accessToken, authentication)); 66 | } catch (Exception e) { 67 | throw new IllegalStateException("Cannot convert access token to JSON", e); 68 | } 69 | return JwtHelper.encode( 70 | content, 71 | signer, 72 | getCustomHeaders()) 73 | .getEncoded(); 74 | } 75 | 76 | protected Map getCustomHeaders() { 77 | return Map.of("kid", keyPairHolder.getId()); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/PersistentAuthorizationCodeServices.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices; 2 | 3 | import dev.rexijie.auth.model.User; 4 | import dev.rexijie.auth.model.token.AuthorizationToken; 5 | import dev.rexijie.auth.repository.AuthorizationTokenRepository; 6 | import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; 7 | import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; 8 | import org.springframework.security.oauth2.common.util.SerializationUtils; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.time.LocalDateTime; 14 | 15 | import static dev.rexijie.auth.util.TokenUtils.generateUUID; 16 | 17 | // TODO - create cron to delete all expired codes 18 | /** 19 | * Custom authorization code services to persist authorization codes. 20 | */ 21 | @Service 22 | public class PersistentAuthorizationCodeServices implements AuthorizationCodeServices { 23 | 24 | private final RandomValueStringGenerator generator; 25 | private final AuthorizationTokenRepository authorizationTokenRepository; 26 | 27 | public PersistentAuthorizationCodeServices(AuthorizationTokenRepository authorizationTokenRepository) { 28 | this.authorizationTokenRepository = authorizationTokenRepository; 29 | this.generator = new RandomValueStringGenerator(16); 30 | } 31 | 32 | @Override 33 | public String createAuthorizationCode(OAuth2Authentication authentication) { 34 | sanitizeAuthentication(authentication); 35 | byte[] serializedAuthentication = SerializationUtils.serialize(authentication); 36 | var token = createAuthorizationToken(); 37 | token.setAuthentication(serializedAuthentication); 38 | token.setUsername(authentication.getName()); 39 | token = authorizationTokenRepository.save(token); 40 | return token.getCode(); 41 | } 42 | 43 | @Override 44 | public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException { 45 | var tokenOptional = authorizationTokenRepository.findByCode(code); 46 | if (tokenOptional.isEmpty()) throwAuthorizationCode(code); 47 | 48 | var token = tokenOptional.get(); 49 | if (token.isUsed()) throwAuthorizationCode(code); 50 | if (token.isExpired()) { 51 | authorizationTokenRepository.delete(token); 52 | throwAuthorizationCodeExpired(); 53 | } 54 | 55 | var authentication = SerializationUtils.deserialize(token.getAuthentication()); 56 | token.setUsed(true); 57 | token.setAuthentication(null); 58 | token.setUpdatedAt(LocalDateTime.now()); 59 | authorizationTokenRepository.save(token); 60 | 61 | return authentication; 62 | } 63 | 64 | protected String generateCode() { 65 | return generator.generate(); 66 | } 67 | 68 | protected AuthorizationToken createAuthorizationToken() { 69 | var id = generateUUID(); 70 | var date = LocalDateTime.now(); 71 | var expiryDate = date.plusMinutes(3); 72 | var token = new AuthorizationToken(null, "", "", false, expiryDate); 73 | token.setId(id); 74 | token.setCode(generateCode()); 75 | token.setCreatedAt(date); 76 | return token; 77 | } 78 | 79 | /** 80 | * remove sensitive data from authentication token 81 | */ 82 | private void sanitizeAuthentication(OAuth2Authentication authentication) { 83 | ((User) authentication.getPrincipal()).setPassword(null); 84 | } 85 | 86 | private void throwAuthorizationCode(String code) { 87 | throw new InvalidGrantException("Invalid authorization code: " + code); 88 | } 89 | 90 | private void throwAuthorizationCodeExpired() { 91 | throw new InvalidGrantException("Authorization code expired"); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/openid/AuthorizationServerOidcTokenServices.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices.openid; 2 | 3 | import dev.rexijie.auth.service.ClientService; 4 | import dev.rexijie.auth.service.SecretGenerator; 5 | import org.springframework.security.core.AuthenticationException; 6 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 7 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 8 | import org.springframework.security.oauth2.provider.ClientDetails; 9 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 10 | import org.springframework.security.oauth2.provider.OAuth2Request; 11 | import org.springframework.security.oauth2.provider.TokenRequest; 12 | import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; 13 | import org.springframework.security.oauth2.provider.token.TokenEnhancer; 14 | import org.springframework.security.oauth2.provider.token.TokenStore; 15 | 16 | import java.util.Date; 17 | 18 | /** 19 | * An implementation of {@link AuthorizationServerTokenServices} that generates IDTokens only 20 | * #UNUSED 21 | * @author Rex Ijiekhuamen 22 | */ 23 | public class AuthorizationServerOidcTokenServices implements AuthorizationServerTokenServices { 24 | private final TokenStore tokenStore; 25 | private final TokenEnhancer tokenEnhancer; 26 | private final ClientService clientDetailsService; 27 | private final SecretGenerator secretGenerator; 28 | 29 | public AuthorizationServerOidcTokenServices(TokenStore tokenStore, 30 | ClientService clientDetailsService, 31 | SecretGenerator secretGenerator, 32 | TokenEnhancer tokenEnhancer) { 33 | this.tokenStore = tokenStore; 34 | this.tokenEnhancer = tokenEnhancer; 35 | this.secretGenerator = secretGenerator; 36 | this.clientDetailsService = clientDetailsService; 37 | } 38 | 39 | @Override 40 | public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { 41 | String tokenId = getSecretGenerator().generate(16); 42 | DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(tokenId); 43 | int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); 44 | if (validitySeconds > 0) 45 | token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); 46 | 47 | token.setScope(authentication.getOAuth2Request().getScope()); 48 | token.setTokenType("id_token"); 49 | // add the id_token type so the token enhancer generates the ID token 50 | 51 | return getTokenEnhancer().enhance(token, authentication); 52 | } 53 | 54 | @Override 55 | public OAuth2AccessToken refreshAccessToken(String refreshToken, TokenRequest tokenRequest) throws AuthenticationException { 56 | // id tokens do not have refresh tokens 57 | return null; 58 | } 59 | 60 | @Override 61 | public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { 62 | // will return null since the tokens are not stored 63 | return getTokenStore().getAccessToken(authentication); 64 | } 65 | 66 | private int getAccessTokenValiditySeconds(OAuth2Request request) { 67 | ClientDetails client = getClientDetailsService().loadClientByClientId(request.getClientId()); 68 | if (client != null) { 69 | return client.getAccessTokenValiditySeconds(); 70 | } 71 | return 5 * 60; 72 | } 73 | 74 | private SecretGenerator getSecretGenerator() { 75 | return this.secretGenerator; 76 | } 77 | 78 | public TokenStore getTokenStore() { 79 | return tokenStore; 80 | } 81 | 82 | public TokenEnhancer getTokenEnhancer() { 83 | return tokenEnhancer; 84 | } 85 | 86 | public ClientService getClientDetailsService() { 87 | return clientDetailsService; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/openid/IDTokenClaimsEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices.openid; 2 | 3 | import dev.rexijie.auth.model.token.IDToken; 4 | import dev.rexijie.auth.tokenservices.JwtClaimsEnhancer; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import java.util.Map; 8 | 9 | public interface IDTokenClaimsEnhancer extends JwtClaimsEnhancer { 10 | 11 | IDToken enhanceClaims(); 12 | void addProfileClaims(Map originalClaims, UserDetails user); 13 | void addEmailClaims(Map originalClaims, UserDetails user); 14 | void addAddressClaims(Map originalClaims, UserDetails user); 15 | void addPhoneClaims(Map originalClaims, UserDetails user); 16 | 17 | 18 | default T getUserFromUserDetails(UserDetails userDetails, Class userClazz) { 19 | return userClazz.cast(userDetails); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/openid/IDTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices.openid; 2 | 3 | import dev.rexijie.auth.constants.Claims; 4 | import dev.rexijie.auth.model.User; 5 | import dev.rexijie.auth.model.token.IDToken; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.Map; 9 | 10 | /** 11 | * @author Rex Ijiekhuamen 12 | */ 13 | public class IDTokenEnhancer implements IDTokenClaimsEnhancer { 14 | 15 | @Override 16 | public Map enhance(Map originalClaims) { 17 | return originalClaims; 18 | } 19 | 20 | @Override 21 | public IDToken enhanceClaims() { 22 | return null; 23 | } 24 | 25 | //TODO update to use oidc userinfo 26 | @Override 27 | public void addProfileClaims(Map originalClaims, UserDetails user) { 28 | var profile = getUserFromUserDetails(user, User.class).getUserInfo(); 29 | originalClaims.put(Claims.OpenIdClaims.NAME_CLAIM, profile.getFullName()); 30 | originalClaims.put(Claims.OpenIdClaims.FAMILY_NAME_CLAIM, profile.getLastName()); 31 | originalClaims.put(Claims.OpenIdClaims.GIVEN_NAME_CLAIM, profile.getFirstName()); 32 | originalClaims.put(Claims.OpenIdClaims.PREFERRED_USERNAME_CLAIM, profile.getUsername()); 33 | originalClaims.put(Claims.OpenIdClaims.BIRTH_DATE_CLAIM, profile.getDateOfBirth()); 34 | 35 | // OidcUserInfo.builder() 36 | // .name(profile.getFullName()) 37 | // .familyName(profile.getLastName()) 38 | // .givenName(profile.getFirstName()) 39 | // .preferredUsername(profile.getUsername()) 40 | // .birthdate(profile.getDataOfBirth().toString()); 41 | } 42 | 43 | @Override 44 | public void addEmailClaims(Map originalClaims, UserDetails user) { 45 | var profile = getUserFromUserDetails(user, User.class).getUserInfo(); 46 | originalClaims.put(Claims.OpenIdClaims.EMAIL_CLAIM, profile.getEmail()); 47 | originalClaims.put(Claims.OpenIdClaims.EMAIL_VERIFIED, profile.isEmailVerified()); 48 | 49 | // OidcUserInfo.builder() 50 | // .email(profile.getEmail()) 51 | // .emailVerified(profile.isEmailVerified()); 52 | } 53 | 54 | @Override 55 | public void addAddressClaims(Map originalClaims, UserDetails user) { 56 | var profile = getUserFromUserDetails(user, User.class).getUserInfo(); 57 | // add email and emaill_verified 58 | // OidcUserInfo.builder() 59 | // .address(profile.getAddress().toString()); 60 | } 61 | 62 | @Override 63 | public void addPhoneClaims(Map originalClaims, UserDetails user) { 64 | var profile = getUserFromUserDetails(user, User.class).getUserInfo(); 65 | originalClaims.put(Claims.OpenIdClaims.PHONE_CLAIM, profile.getPhoneNumber()); 66 | originalClaims.put(Claims.OpenIdClaims.PHONE_VERIFIED, profile.isEmailVerified()); 67 | // add phone numbers 68 | // OidcUserInfo.builder() 69 | // .phoneNumber(profile.getPhoneNumber()) 70 | // .phoneNumberVerified(profile.isPhoneNumberVerified() ? "true" : "false"); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/openid/IDTokenGranter.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices.openid; 2 | 3 | import org.springframework.security.authentication.InsufficientAuthenticationException; 4 | import org.springframework.security.core.Authentication; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.security.oauth2.provider.*; 7 | import org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest; 8 | import org.springframework.security.oauth2.provider.token.AbstractTokenGranter; 9 | import org.springframework.util.Assert; 10 | 11 | import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames.ID_TOKEN; 12 | 13 | /* 14 | TODO - implement c-hash claim 15 | */ 16 | /** 17 | * An implementation of {@link TokenGranter} that grants id_tokens 18 | * using the implicit token grant 19 | * #UNUSED 20 | * 21 | * @author Rex Ijiekhuamen 22 | */ 23 | public class IDTokenGranter extends AbstractTokenGranter { 24 | private static final String GRANT_TYPE = ID_TOKEN; 25 | 26 | private IDTokenGranter(AuthorizationServerOidcTokenServices tokenServices, 27 | ClientDetailsService clientDetailsService, 28 | OAuth2RequestFactory requestFactory, 29 | String grantType) { 30 | super(tokenServices, clientDetailsService, requestFactory, grantType); 31 | } 32 | 33 | public IDTokenGranter(AuthorizationServerOidcTokenServices tokenServices, 34 | ClientDetailsService clientDetailsService, 35 | OAuth2RequestFactory requestFactory) { 36 | this(tokenServices, clientDetailsService, requestFactory, "id_token"); 37 | } 38 | 39 | @Override 40 | protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) { 41 | 42 | Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); 43 | if (userAuth==null || !userAuth.isAuthenticated()) { 44 | throw new InsufficientAuthenticationException("There is no currently logged in user"); 45 | } 46 | Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest."); 47 | 48 | OAuth2Request requestForStorage = ((ImplicitTokenRequest)clientToken).getOAuth2Request(); 49 | 50 | return new OAuth2Authentication(requestForStorage, userAuth); 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/tokenservices/openid/IdTokenGeneratingTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.tokenservices.openid; 2 | 3 | import dev.rexijie.auth.constants.Scopes; 4 | import dev.rexijie.auth.model.User; 5 | import dev.rexijie.auth.model.token.IDToken; 6 | import dev.rexijie.auth.model.token.KeyPairHolder; 7 | import dev.rexijie.auth.service.UserService; 8 | import dev.rexijie.auth.tokenservices.JwtTokenEnhancer; 9 | import io.jsonwebtoken.Claims; 10 | import io.jsonwebtoken.impl.DefaultClaims; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.jwt.JwtHelper; 14 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 15 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 16 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 17 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 18 | import org.springframework.security.oauth2.provider.OAuth2Request; 19 | 20 | import java.nio.charset.StandardCharsets; 21 | import java.security.MessageDigest; 22 | import java.time.Instant; 23 | import java.util.*; 24 | 25 | import static dev.rexijie.auth.util.TokenRequestUtils.isAuthorizationCodeRequest; 26 | import static dev.rexijie.auth.util.TokenRequestUtils.isImplicitRequest; 27 | import static dev.rexijie.auth.util.TokenUtils.getMessageDigestInstance; 28 | import static dev.rexijie.auth.util.TokenUtils.hashString; 29 | import static io.jsonwebtoken.Claims.AUDIENCE; 30 | import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.NONCE; 31 | 32 | /** 33 | * @author Rex Ijiekhuamen 34 | */ 35 | public class IdTokenGeneratingTokenEnhancer extends JwtTokenEnhancer { 36 | 37 | private final IDTokenClaimsEnhancer enhancer; 38 | private final UserService userService; 39 | @Value("${oauth2.openid.implicit.enabled}") 40 | private final boolean implicitEnabled = false; 41 | 42 | public IdTokenGeneratingTokenEnhancer(UserService userService, 43 | IDTokenClaimsEnhancer enhancer, 44 | KeyPairHolder keyPairHolder) { 45 | super(keyPairHolder); 46 | this.userService = userService; 47 | this.enhancer = enhancer; 48 | } 49 | 50 | @Override 51 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 52 | OAuth2Request request = authentication.getOAuth2Request(); 53 | if (!request.getScope().contains(Scopes.ID_SCOPE)) 54 | return accessToken; 55 | 56 | if (isAuthorizationCodeRequest(request) || (implicitEnabled && isImplicitRequest(request))) 57 | return appendIdToken(accessToken, authentication); 58 | 59 | return accessToken; // return normal token for other grant types 60 | } 61 | 62 | /** 63 | * This method uses an access token to generate an ID token. 64 | * some claims are taken directly from the access toke and mapped to the ID token 65 | *

66 | * The ID token is generated with base claims, then depending on the scopes requested 67 | * a delegate {@link IDTokenClaimsEnhancer} populates the required claims 68 | * 69 | * @param accessToken access token 70 | * @param authentication authentication context containing the authentication request 71 | * @return IDToken 72 | */ 73 | private OAuth2AccessToken appendIdToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 74 | OAuth2Request request = authentication.getOAuth2Request(); 75 | 76 | String nonce = request.getRequestParameters().get(NONCE); 77 | Claims accessTokenClaims = new DefaultClaims(super.decode(accessToken.getValue())); 78 | accessTokenClaims.put(AUDIENCE, request.getClientId()); 79 | 80 | OidcIdToken.Builder builder = OidcIdToken.withTokenValue(accessToken.getValue()) 81 | .issuer(accessTokenClaims.getIssuer()) 82 | .subject(accessTokenClaims.getSubject()) 83 | .audience(Set.of(accessTokenClaims.getAudience())) 84 | .authorizedParty(request.getClientId()) 85 | .nonce(nonce) 86 | .expiresAt(accessTokenClaims.getExpiration().toInstant()) 87 | .accessTokenHash(generateAccessTokenHash(accessToken)) 88 | .authorizationCodeHash(generateCodeHash(accessToken, authentication)) 89 | .authTime(accessTokenClaims.getIssuedAt().toInstant()) 90 | .issuedAt(Instant.now()) 91 | .authenticationMethods(getAuthenticationMethods(authentication)); 92 | 93 | String username = accessTokenClaims.getSubject(); 94 | User user = userService.findUserByUsername(username); 95 | 96 | if (request.getScope().contains(Scopes.IDTokenScopes.PROFILE)) 97 | builder.claims(claimsMap -> enhancer.addProfileClaims(claimsMap, user)); 98 | 99 | 100 | if (request.getScope().contains(Scopes.IDTokenScopes.EMAIL)) 101 | builder.claims(claimsMap -> enhancer.addEmailClaims(claimsMap, user)); 102 | 103 | OidcIdToken oidcIdToken = builder.build(); 104 | IDToken idToken = new IDToken(oidcIdToken); 105 | 106 | String idTokenString = super.encode(idToken, authentication); 107 | 108 | DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken; 109 | token.setAdditionalInformation(Map.of(IDToken.TYPE, idTokenString)); 110 | 111 | return token; 112 | } 113 | 114 | // generates the at_hash 115 | protected String generateAccessTokenHash(OAuth2AccessToken accessToken) { 116 | 117 | String algorithm = getHashAlgorithmForToken(accessToken.getValue()); 118 | MessageDigest MD5 = getMessageDigestInstance(algorithm); 119 | // - get ascii representation of the token 120 | byte[] asciiValues = accessToken.getValue().getBytes(StandardCharsets.US_ASCII); 121 | 122 | // - hash the ascii value using the jwt hashing algorithm 123 | byte[] hashedToken = MD5.digest(asciiValues); 124 | 125 | // get the first 128 bits (hash alg length / 2 === 256 / 2) 126 | byte[] bytes = Arrays.copyOf(hashedToken, 16); 127 | 128 | return Base64.getEncoder().encodeToString(bytes); 129 | } 130 | 131 | // generate the c_hash claim value 132 | protected String generateCodeHash(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 133 | OAuth2Request request = authentication.getOAuth2Request(); 134 | Map requestParameters = request.getRequestParameters(); 135 | String authorizationCode = requestParameters.get("code"); 136 | if (authorizationCode == null) return null; 137 | 138 | String algorithm = getHashAlgorithmForToken(accessToken.getValue()); 139 | byte[] hashedCode = hashString(algorithm, authorizationCode); 140 | byte[] bytes = Arrays.copyOf(hashedCode, 16); 141 | 142 | return Base64.getEncoder().encodeToString(bytes); 143 | } 144 | 145 | // you should override this 146 | // RS256 is used to sign tokens so the algorithm returns SHA-256 147 | protected String getHashAlgorithmForToken(String token) { 148 | Map headers = JwtHelper.headers(token); 149 | String tokenAlg = headers.get("alg"); 150 | return "SHA-".concat(tokenAlg.substring(2)); 151 | } 152 | 153 | protected List getAuthenticationMethods(Authentication authentication) { 154 | return List.of("user"); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/util/AuthenticationUtils.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.util; 2 | 3 | import dev.rexijie.auth.model.User; 4 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 5 | 6 | public class AuthenticationUtils { 7 | 8 | public static User extractUserFromAuthentication(OAuth2Authentication auth2Authentication) { 9 | return (User) auth2Authentication.getPrincipal(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/util/ObjectUtils.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.util; 2 | 3 | import com.fasterxml.jackson.core.type.TypeReference; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.util.Collection; 7 | import java.util.Map; 8 | import java.util.concurrent.ConcurrentHashMap; 9 | import java.util.function.Consumer; 10 | 11 | public class ObjectUtils { 12 | private static final ObjectMapper objectMapper = new ObjectMapper(); 13 | 14 | /** 15 | * Helper method to apply a function on an object if it is not null or empty. 16 | * The object if not null is then passed as a parameter in the function. 17 | * 18 | * @param object the object to check 19 | * @param function the function to apply 20 | * @param The type of the object 21 | */ 22 | public static void applyIfNonNull(T object, Consumer function) { 23 | if (object == null) return; 24 | if (object instanceof Collection) { 25 | var collection = ((Collection) object); 26 | if (collection.isEmpty()) return; 27 | } 28 | function.accept(object); 29 | } 30 | 31 | public static void applyIfNonEmpty(Collection object, Consumer> function) { 32 | if (object == null) return; 33 | if (object.isEmpty()) return; 34 | function.accept(object); 35 | } 36 | 37 | /** 38 | * Utility method to remove null elements from map 39 | */ 40 | public static Map cleanMap(Map map) { 41 | Map returnedMap = new ConcurrentHashMap<>(); 42 | for (String key : map.keySet()) 43 | if (map.get(key) != null) 44 | returnedMap.put(key, map.get(key)); 45 | 46 | return returnedMap; 47 | } 48 | 49 | public static Map toMap(T object) { 50 | return objectMapper.convertValue(object, new TypeReference<>() {}); 51 | } 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/util/TokenRequestUtils.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.util; 2 | 3 | import org.springframework.security.oauth2.provider.AuthorizationRequest; 4 | import org.springframework.security.oauth2.provider.OAuth2Request; 5 | 6 | import static dev.rexijie.auth.constants.GrantTypes.AUTHORIZATION_CODE; 7 | import static dev.rexijie.auth.constants.GrantTypes.IMPLICIT; 8 | 9 | public class TokenRequestUtils { 10 | 11 | public static boolean isImplicitRequest(OAuth2Request request) { 12 | return request.getGrantType().equals(IMPLICIT); 13 | } 14 | public static boolean isImplicitRequest(AuthorizationRequest request) { 15 | return request.getResponseTypes().contains("token"); 16 | } 17 | 18 | public static boolean isAuthorizationCodeRequest(OAuth2Request request) { 19 | return request.getGrantType().equals(AUTHORIZATION_CODE); 20 | } 21 | public static boolean isAuthorizationCodeRequest(AuthorizationRequest request) { 22 | return request.getResponseTypes().contains("code"); 23 | } 24 | 25 | public static boolean isIdTokenRequest(AuthorizationRequest authorizationRequest) { 26 | return authorizationRequest.getResponseTypes().contains("id_token"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/dev/rexijie/auth/util/TokenUtils.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth.util; 2 | 3 | import lombok.NonNull; 4 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 5 | import org.springframework.util.SerializationUtils; 6 | 7 | import java.math.BigInteger; 8 | import java.nio.charset.StandardCharsets; 9 | import java.security.MessageDigest; 10 | import java.security.NoSuchAlgorithmException; 11 | import java.time.Instant; 12 | import java.time.LocalDate; 13 | import java.util.Base64; 14 | import java.util.Map; 15 | import java.util.Objects; 16 | import java.util.UUID; 17 | 18 | public class TokenUtils { 19 | public static String serializeAuthentication(@NonNull OAuth2Authentication auth2Authentication) { 20 | var authenticationByteArray = SerializationUtils.serialize(auth2Authentication); 21 | return Base64.getEncoder().encodeToString(authenticationByteArray); 22 | } 23 | 24 | public static OAuth2Authentication deserializeAuthentication(String authentication) { 25 | var authenticationBytes = Base64.getDecoder().decode(authentication); 26 | var deserializedAuthentication = SerializationUtils.deserialize(authenticationBytes); 27 | if (!(deserializedAuthentication instanceof OAuth2Authentication)) 28 | throw new RuntimeException("invalid authentication object"); 29 | 30 | return (OAuth2Authentication) deserializedAuthentication; 31 | } 32 | 33 | public static String generateHash(String value) { 34 | if (value == null) return null; 35 | try { 36 | var md5Digest = MessageDigest.getInstance("MD5"); 37 | var tokenBytes = value.getBytes(StandardCharsets.UTF_8); 38 | tokenBytes = md5Digest.digest(tokenBytes); 39 | return String.format("%032x", new BigInteger(1, tokenBytes)); 40 | 41 | } catch (NoSuchAlgorithmException exception) { 42 | throw new IllegalStateException("MD5 algorithm not available"); 43 | } 44 | } 45 | 46 | public static MessageDigest getMessageDigestInstance(String algorithm) { 47 | try { 48 | return MessageDigest.getInstance(algorithm); 49 | } catch (NoSuchAlgorithmException ignored) { 50 | throw new RuntimeException("unable to get hash algorithm"); 51 | } 52 | } 53 | 54 | public static byte[] hashString(String algorithm, String value) { 55 | return getMessageDigestInstance(algorithm) 56 | .digest(value.getBytes(StandardCharsets.US_ASCII)); 57 | } 58 | 59 | public static Map toOpenIdCompliantMap(Map mutableMap) { 60 | mutableMap.keySet() 61 | .parallelStream() 62 | .forEach(key -> { 63 | if (mutableMap.get(key) instanceof Instant) { 64 | Instant instant = (Instant) mutableMap.get(key); 65 | mutableMap.put(key, instant.getEpochSecond()); 66 | } 67 | 68 | if (mutableMap.get(key) instanceof LocalDate) { 69 | LocalDate localDate = (LocalDate) mutableMap.get(key); 70 | mutableMap.put(key, localDate.toString()); 71 | } 72 | 73 | if (mutableMap.get(key) == null) 74 | mutableMap.remove(key); 75 | }); 76 | return mutableMap; 77 | } 78 | 79 | public static String generateUUID() { 80 | return UUID.randomUUID().toString(); 81 | } 82 | 83 | public static String getTokenFromAuthorizationHeader(String authorization) { 84 | Objects.requireNonNull(authorization); 85 | return authorization.substring(7); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/additional-spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "oauth2.openid.implicit.enabled", 5 | "type": "java.lang.String", 6 | "description": "Enable ID token generation for implicit flow." 7 | } 8 | ] } -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8000 3 | spring: 4 | application: 5 | name: REX-AUTH 6 | data: 7 | mongodb: 8 | username: idea 9 | password: ideapass 10 | database: authserver 11 | auto-index-creation: true 12 | 13 | oauth2: 14 | openid: 15 | discovery: 16 | baseUri: http://127.0.0.1:8000 17 | implicit: 18 | enabled: true 19 | -------------------------------------------------------------------------------- /src/main/resources/application-docker.yml: -------------------------------------------------------------------------------- 1 | oauth2: 2 | openid: 3 | implicit: 4 | enabled: ${ENABLE_IMPLICIT_ID_TOKEN} 5 | spring: 6 | application: 7 | name: AUTHENTICATION_SERVER 8 | data: 9 | mongodb: 10 | username: ${MONGO_USERNAME} 11 | password: ${MONGO_PASSWORD} 12 | database: ${MONGO_DATABASE} 13 | host: ${MONGO_HOST} 14 | port: 27017 15 | auto-index-creation: true 16 | -------------------------------------------------------------------------------- /src/main/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8000 3 | spring: 4 | application: 5 | name: REX-AUTH 6 | data: 7 | mongodb: 8 | username: idea 9 | password: ideapass 10 | database: authserver 11 | auto-index-creation: true 12 | 13 | oauth2: 14 | openid: 15 | implicit: 16 | enabled: true 17 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | oauth2: 2 | openid: 3 | discovery: 4 | baseUri: ${SERVER_URL} 5 | issuer: ${oauth2.openid.discovery.baseUri}/openid 6 | tokenEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/token 7 | tokenKeyEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/token_key 8 | userinfoEndpoint: ${oauth2.openid.discovery.issuer}/userinfo 9 | checkTokenEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/check_token 10 | revocationEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/revoke 11 | authorizationEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/authorize 12 | introspectionEndpoint: ${oauth2.openid.discovery.baseUri}/oauth2/introspect 13 | jwksUri: ${oauth2.openid.discovery.issuer}/.well-known/jwks.json 14 | userinfoSigningAlgSupported: 15 | - RS256 16 | idTokenSigningAlgValuesSupported: 17 | - RS256 18 | tokenEndpointAuthSigningAlgorithmsSupported: 19 | - RS256 20 | scopesSupported: 21 | - openid 22 | - profile 23 | - email 24 | - read 25 | - write 26 | subjectTypesSupported: 27 | - public 28 | - pairwise 29 | responseTypesSupported: 30 | - code 31 | - token 32 | - id_token 33 | - code token 34 | - code id_token 35 | - id_token token 36 | - code id_token token 37 | claimsSupported: 38 | - iss 39 | - sub 40 | - iat 41 | - azp 42 | - exp 43 | - scope 44 | - at_hash 45 | - c_hash 46 | - nonce 47 | grantTypesSupported: 48 | - authorization_code 49 | - implicit 50 | tokenEndpointAuthMethodsSupported: 51 | - client_secret_basic 52 | - client_secret_post 53 | -------------------------------------------------------------------------------- /src/main/resources/static/css/confirmaccess.css: -------------------------------------------------------------------------------- 1 | form { 2 | position: relative; 3 | } 4 | .form-footer {margin: 20px -20px 0 -20px;} 5 | .button-row { 6 | position: absolute; 7 | bottom: 30px; 8 | right: 30px; 9 | } 10 | .approval-text { 11 | margin: 0; 12 | line-height: 1.6em; 13 | } 14 | .form-label { 15 | display: none; 16 | } 17 | .icon { 18 | width: 50px; 19 | } 20 | .icon > img { 21 | width: 100%; 22 | } 23 | .content { 24 | margin-left: 10px; 25 | } 26 | .title { 27 | margin-bottom: 0; 28 | font-size: 1.2rem; 29 | } 30 | 31 | .description { 32 | margin-top: 5px; 33 | } 34 | 35 | .mr10 { 36 | margin-right: 10px; 37 | } 38 | @media screen and (max-width: 767px) { 39 | .button-row { 40 | position: unset; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/resources/static/css/global.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --blue: #5e72e4; 3 | --indigo: #5603ad; 4 | --purple: #8965e0; 5 | --pink: #f3a4b5; 6 | --red: #f5365c; 7 | --orange: #fb6340; 8 | --yellow: #ffd600; 9 | --green: #2dce89; 10 | --teal: #11cdef; 11 | --cyan: #2bffc6; 12 | --white: #fff; 13 | --gray: #8898aa; 14 | --gray-dark: #32325d; 15 | --lighter: #e9ecef; 16 | --primary: #5e72e4; 17 | --secondary: #f7fafc; 18 | --success: #2dce89; 19 | --info: #11cdef; 20 | --warning: #fb6340; 21 | --danger: #f5365c; 22 | --light: #adb5bd; 23 | --dark: #212529; 24 | --default: #172b4d; 25 | --neutral: #fff; 26 | --darker: black; 27 | --breakpoint-xs: 0; 28 | --breakpoint-sm: 576px; 29 | --breakpoint-md: 768px; 30 | --breakpoint-lg: 992px; 31 | --breakpoint-xl: 1200px; 32 | --black: #161616; 33 | --border-radius: 0.375rem; 34 | --main-font: 'Slabo 27px', serif; 35 | --secondary-font: 'Roboto', sans-serif; 36 | --color-primary: darkslateblue; 37 | --color-secondary: darkslateblue; 38 | } 39 | 40 | * { 41 | box-sizing: border-box; 42 | font-family: var(--secondary-font); 43 | font-size: 16px; 44 | } 45 | *:focus { 46 | outline: unset; 47 | } 48 | body { 49 | display: flex; 50 | flex-direction: row; 51 | align-items: center; 52 | background-color: var(--light); 53 | } 54 | .text-center { 55 | text-align: center; 56 | } 57 | 58 | .header { 59 | font-family: var(--main-font); 60 | } 61 | 62 | input { 63 | 64 | } 65 | 66 | .button { 67 | padding: 10px; 68 | min-width: 80px; 69 | border-radius: var(--border-radius); 70 | border: 1px solid transparent; 71 | background-color: cadetblue; 72 | cursor: pointer; 73 | position: relative; 74 | text-transform: none; 75 | transition: background-color 0.15s ease; 76 | letter-spacing: 0.025em; 77 | font-size: 0.875rem; 78 | will-change: transform; 79 | box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08); 80 | } 81 | 82 | .btn-primary { 83 | background-color: var(--gray-dark); 84 | border-color: var(--gray-dark); 85 | color: var(--white); 86 | } 87 | .btn-primary:hover { 88 | transform: none; 89 | background-color: #505092; 90 | } 91 | 92 | .btn-secondary { 93 | border: 1px solid transparent; 94 | background-color: var(--white); 95 | color: var(--black); 96 | } 97 | .btn-secondary:hover { 98 | text-decoration: underline; 99 | font-weight: bold; 100 | } 101 | 102 | .form-container { 103 | background-color: var(--white); 104 | width: 400px; 105 | margin: 0 auto; 106 | border-radius: var(--border-radius); 107 | box-shadow: 108 | 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 109 | 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 110 | 0 12.5px 10px rgba(0, 0, 0, 0.06), 111 | 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 112 | 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 113 | 0 100px 80px rgba(0, 0, 0, 0.12) 114 | } 115 | .form { 116 | padding: 0 20px; 117 | background-color: var(--white); 118 | border-radius: var(--border-radius); 119 | margin: 0; 120 | --form-margin: 20px; 121 | } 122 | .form-header { 123 | font-size: 2rem; 124 | padding: 20px 30px; 125 | margin: 0 -20px 25px -20px; 126 | background-color: var(--gray-dark); 127 | border-top-left-radius: var(--border-radius); 128 | border-top-right-radius: var(--border-radius); 129 | color: var(--white); 130 | } 131 | 132 | .form-row { 133 | padding: 0 10px; 134 | margin-bottom: var(--form-margin); 135 | display: flex; 136 | flex-direction: column; 137 | } 138 | 139 | .form-row-linear { 140 | display: flex; 141 | flex-direction: row; 142 | margin-bottom: var(--form-margin); 143 | } 144 | 145 | .form-label { 146 | margin-bottom: 5px; 147 | margin-left: 2px; 148 | text-transform: uppercase; 149 | } 150 | 151 | .form-input { 152 | padding: 10px 10px 10px 10px; 153 | font-weight: normal; 154 | background: white; 155 | border: 1px solid #505092; 156 | outline: none; 157 | font-size: 1em; 158 | margin: 6px 0 17px 0; 159 | transition: border-color 0.5s ease; 160 | -webkit-transition: border-color 0.5s ease; 161 | border-radius: var(--border-radius); 162 | } 163 | .form-error { 164 | color: var(--red); 165 | } 166 | .form-footer { 167 | flex-direction: row; 168 | padding: 20px 30px; 169 | margin: 20px -20px 50px -20px; 170 | border-bottom-left-radius: var(--border-radius); 171 | border-bottom-right-radius: var(--border-radius); 172 | } 173 | 174 | /* Utility methods */ 175 | .w-100 {width: 100%;} 176 | .mt-1 {margin-top: 1em;} 177 | .mb-0 {margin-bottom: 0;} 178 | .d-flex {display: flex;} 179 | .d-flex-row{display: flex;flex-direction: row;} 180 | .d-flex-col{display: flex;flex-direction: column;} 181 | .f-justify-end { 182 | justify-content: flex-end; 183 | } 184 | /* Utility methods end*/ 185 | 186 | @media screen and (max-width: 767px) { 187 | * {font-size: 14px;} 188 | .form-header{padding:20px 28px;} 189 | .form-container{width:100vw;height:100%;} 190 | .form-row{padding:0;} 191 | .form-footer {padding: 20px 20px;} 192 | } 193 | 194 | @media screen and (max-width: 350px) { 195 | * {font-size: 12px;} 196 | } 197 | -------------------------------------------------------------------------------- /src/main/resources/static/css/login.css: -------------------------------------------------------------------------------- 1 | .login-btn {flex: 1;} -------------------------------------------------------------------------------- /src/main/resources/static/css/logout.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Recks11/spring-oauth2-authorization-server/fad45eec46982b68203e3509879c56ae58c4a833/src/main/resources/static/css/logout.css -------------------------------------------------------------------------------- /src/main/resources/static/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Recks11/spring-oauth2-authorization-server/fad45eec46982b68203e3509879c56ae58c4a833/src/main/resources/static/img/favicon.ico -------------------------------------------------------------------------------- /src/main/resources/static/img/read.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/static/img/write.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 7 | 9 | 11 | 12 | 14 | 15 | 17 | 18 | 20 | 21 | 23 | 24 | 26 | 28 | 29 | 30 | 32 | 34 | 35 | 37 | 39 | 41 | 42 | 45 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/resources/templates/confirmaccess.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | CONFIRM ACCESS 8 | 9 | 10 | 12 | 13 | 14 | 15 |

16 |
18 |

Approve Access

19 |
20 |

needs permission to access your 21 | information

22 |
23 | 24 | 25 | 26 |
27 |
28 | read 29 |
30 |
31 | READ 32 |

permission to read your data

33 | 36 | 39 |
40 |
41 | 42 | 46 |
47 | 89 |
90 | 91 | 92 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/400.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | OAuth2 6 | 7 | 8 | 9 |

Error!

10 |

I don't know what you did, but that wasn't it chief. that's a 400 for you

11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | OAuth2 6 | 7 | 8 | 9 |

Error 404

10 |

seriously, how on earth did you get here? (@ _ @` ).

11 |

I don't know what you wanted but it sure isn't here

12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/templates/error/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | OAuth2 500 6 | 7 | 8 | 9 |

Error (._. )

10 |

Okay something went wrong internally.. My bad. 500

11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | LOG IN 8 | 9 | 10 | 12 | 13 | 14 | 15 |
16 |
17 |

LOG IN

18 | 19 |
20 | 21 | 22 |
23 | 24 |
25 | 26 | 27 |
28 | 29 | 30 |
31 | BAD CREDENTIALS 32 |
33 | 34 | 37 |
38 |
39 | 40 | 41 | -------------------------------------------------------------------------------- /src/main/resources/templates/logout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | LOG OUT 8 | 9 | 10 | 12 | 13 | 14 | 15 |
16 |

LOGOUT

17 |
18 | 19 |
20 | 21 | -------------------------------------------------------------------------------- /src/test/java/dev/rexijie/auth/Oauth2ServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package dev.rexijie.auth; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class Oauth2ServerApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------