kandi background
Explore Kits

spring-security-oauth | adding OAuth1 and OAuth2 features for Spring web applications | OAuth library

 by   spring-projects Java Version: Current License: Apache-2.0

 by   spring-projects Java Version: Current License: Apache-2.0

Download this library from

kandi X-RAY | spring-security-oauth Summary

spring-security-oauth is a Java library typically used in Security, OAuth, Spring Boot, Axios applications. spring-security-oauth has no bugs, it has build file available, it has a Permissive License and it has medium support. However spring-security-oauth has 2 vulnerabilities. You can download it from GitHub, Maven.
This project provides support for using Spring Security with OAuth (1a) and OAuth2. It provides features for implementing both consumers and providers of these protocols using standard Spring and Spring Security programming models and configuration idioms.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • spring-security-oauth has a medium active ecosystem.
  • It has 4559 star(s) with 4074 fork(s). There are 397 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 545 open issues and 933 have been closed. On average issues are closed in 220 days. There are no pull requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of spring-security-oauth is current.
This Library - Support
Best in #OAuth
Average in #OAuth
This Library - Support
Best in #OAuth
Average in #OAuth

quality kandi Quality

  • spring-security-oauth has 0 bugs and 0 code smells.
This Library - Quality
Best in #OAuth
Average in #OAuth
This Library - Quality
Best in #OAuth
Average in #OAuth

securitySecurity

  • spring-security-oauth has 2 vulnerability issues reported (0 critical, 0 high, 2 medium, 0 low).
  • spring-security-oauth code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
This Library - Security
Best in #OAuth
Average in #OAuth
This Library - Security
Best in #OAuth
Average in #OAuth

license License

  • spring-security-oauth is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
This Library - License
Best in #OAuth
Average in #OAuth
This Library - License
Best in #OAuth
Average in #OAuth

buildReuse

  • spring-security-oauth releases are not available. You will need to build from source code and install.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • It has 54665 lines of code, 4297 functions and 887 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
This Library - Reuse
Best in #OAuth
Average in #OAuth
This Library - Reuse
Best in #OAuth
Average in #OAuth
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

spring-security-oauth Key Features

Support for adding OAuth1(a) and OAuth2 features (consumer and provider) for Spring web applications.

Getting Started

copy iconCopydownload iconDownload
$ git clone ...
$ mvn install -P bootstrap

Samples

copy iconCopydownload iconDownload
$ cd samples/oauth2/tonr
$ mvn tomcat7:run

java.lang.ClassNotFoundException: org.apache.wicket.settings.def.JavaScriptLibrarySettings

copy iconCopydownload iconDownload
[INFO] +- org.wicketstuff:wicketstuff-tinymce:jar:6.30.0:compile
[INFO] |  +- org.apache.wicket:wicket-extensions:jar:6.30.0:compile
[INFO] |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  +- net.sf.jazzy:jazzy:jar:0.5.2-rtext-1.4.1:compile
[INFO] |  +- org.json:json:jar:20090211:compile
[INFO] |  \- org.apache.wicket:wicket:pom:6.30.0:compile

The page isn’t redirecting properly while trying to log in with Spring Authorization Server using custom user details service

copy iconCopydownload iconDownload
 @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

spring-security-oauth2-authorization-server + angular-auth-oidc-client

copy iconCopydownload iconDownload
// @formatter:off
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorizeRequests ->
            authorizeRequests.anyRequest().authenticated()
        )
        // Note: You can also make the corsConfigurationSource() non-static
        // and annotated with @Bean. Then use instead:
        // .cors(Customizer.withDefaults())
        .cors(cors -> cors.configurationSource(corsConfigurationSource()))
        .formLogin(Customizer.withDefaults());
    return http.build();
}
// @formatter:on
-----------------------

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@RestController
@RequestMapping()
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() {
        this.rsaKeyPair = generateRsaKey();
        this.jwkRsaPublicKey = generateRsa(this.rsaKeyPair);
    }

    /**
     * Note this method is currently not use, but here for future use.
     * We use the same URL as in the Keycloak, so we have not to change things when running the thing against ms-backend-test-openid-connect-mock or Keycloak.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/certs", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    /**
     * This is used in the SystemTest. There we download the private key and sign the JWT.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    public RSAKey getJwkRsaPublicKey() {
        return this.jwkRsaPublicKey;
    }

    private RSAKey generateRsa(KeyPair keyPair) {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
    }

    private KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class PersistedUserConfig {

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("U-294b70ca67df4c018f59950f35314944")
                .password("U-294b70ca67df4c018f59950f35314944")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

}


import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.*;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class TestAuthorizationServerConfig {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());


    @PostConstruct
    public void publicNote() {
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
        logger.info("Note that the current spring authorisation server does not support token renewal. If you want to test that, use the Keycloak");
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
    }

    public static CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        config.addAllowedOrigin("127.0.0.1:4201");
        config.addAllowedOrigin("http://127.0.0.1:4201");
        config.addAllowedOrigin("localhost:4201");

        config.addAllowedOrigin("127.0.0.1:4200");
        config.addAllowedOrigin("http://127.0.0.1:4200");
        config.addAllowedOrigin("localhost:4200");

        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        return http.cors().configurationSource(corsConfigurationSource()).and()
                .authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/login")
                .authenticated()
                .and()
                .formLogin(withDefaults())
                .build();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(withDefaults()).cors().configurationSource(corsConfigurationSource()).and().build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("medical-share-openid-connect-client-id")
                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)

                .redirectUri("http://127.0.0.1:4200")
                .redirectUri("http://127.0.0.1:4200/")

                .redirectUri("http://127.0.0.1:4201")
                .redirectUri("http://127.0.0.1:4201/")
                .scope(OidcScopes.OPENID)
                .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofDays(1)).build())
                .scope("offline_access")
//                .scope("message.read")
//                .scope("message.write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).requireProofKey(true).build())
                .build();

        // Save registered client in db as if in-memory
        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
        registeredClientRepository.save(publicClient);

        return registeredClientRepository;
    }

    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource(OpenIdConnectMockController openIdConnectMockController) {
        RSAKey rsaKey = openIdConnectMockController.getJwkRsaPublicKey();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://127.0.0.1:8088").build();
    }

    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
    }

    /**
     * This is a bit a hack, but as we do not know how we integrate the HealthPlattform this is a very easy way to solve the Problem for the moment.
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
                User user = (User) principal.getPrincipal();
                context.getClaims()
                        .claim("name", user.getUsername());
            }
        };
    }

}

import {NgModule} from '@angular/core';
import {AuthModule, LogLevel} from 'angular-auth-oidc-client';

@NgModule({
  imports: [
    AuthModule.forRoot({
      config: {
        configId: 'ms-angular-auth-oidc-client-lib-id',
        logLevel: LogLevel.Debug,
        historyCleanupOff: false,
        // Keycloak
        // authority: 'http://localhost:8088/realms/master',
        authority: 'http://127.0.0.1:8088',
        redirectUrl: 'http://127.0.0.1:4201/',
        // Keycloak
        // redirectUrl: 'http://localhost:4201/',
        postLogoutRedirectUri: 'http://127.0.0.1:4201/',
        clientId: 'medical-share-openid-connect-client-id',
        scope: 'openid',
        responseType: 'code',
        silentRenew: true,
        renewTimeBeforeTokenExpiresInSeconds: 10,
        autoUserInfo: false,
        useRefreshToken: true,
        secureRoutes: [
          'http://127.0.0.1:4201',
          'http://localhost:4201',
        ],
      },
    }),
  ],
  exports: [AuthModule],
})
export class AuthConfigModule {
}
-----------------------

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@RestController
@RequestMapping()
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() {
        this.rsaKeyPair = generateRsaKey();
        this.jwkRsaPublicKey = generateRsa(this.rsaKeyPair);
    }

    /**
     * Note this method is currently not use, but here for future use.
     * We use the same URL as in the Keycloak, so we have not to change things when running the thing against ms-backend-test-openid-connect-mock or Keycloak.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/certs", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    /**
     * This is used in the SystemTest. There we download the private key and sign the JWT.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    public RSAKey getJwkRsaPublicKey() {
        return this.jwkRsaPublicKey;
    }

    private RSAKey generateRsa(KeyPair keyPair) {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
    }

    private KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class PersistedUserConfig {

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("U-294b70ca67df4c018f59950f35314944")
                .password("U-294b70ca67df4c018f59950f35314944")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

}


import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.*;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class TestAuthorizationServerConfig {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());


    @PostConstruct
    public void publicNote() {
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
        logger.info("Note that the current spring authorisation server does not support token renewal. If you want to test that, use the Keycloak");
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
    }

    public static CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        config.addAllowedOrigin("127.0.0.1:4201");
        config.addAllowedOrigin("http://127.0.0.1:4201");
        config.addAllowedOrigin("localhost:4201");

        config.addAllowedOrigin("127.0.0.1:4200");
        config.addAllowedOrigin("http://127.0.0.1:4200");
        config.addAllowedOrigin("localhost:4200");

        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        return http.cors().configurationSource(corsConfigurationSource()).and()
                .authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/login")
                .authenticated()
                .and()
                .formLogin(withDefaults())
                .build();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(withDefaults()).cors().configurationSource(corsConfigurationSource()).and().build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("medical-share-openid-connect-client-id")
                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)

                .redirectUri("http://127.0.0.1:4200")
                .redirectUri("http://127.0.0.1:4200/")

                .redirectUri("http://127.0.0.1:4201")
                .redirectUri("http://127.0.0.1:4201/")
                .scope(OidcScopes.OPENID)
                .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofDays(1)).build())
                .scope("offline_access")
//                .scope("message.read")
//                .scope("message.write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).requireProofKey(true).build())
                .build();

        // Save registered client in db as if in-memory
        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
        registeredClientRepository.save(publicClient);

        return registeredClientRepository;
    }

    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource(OpenIdConnectMockController openIdConnectMockController) {
        RSAKey rsaKey = openIdConnectMockController.getJwkRsaPublicKey();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://127.0.0.1:8088").build();
    }

    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
    }

    /**
     * This is a bit a hack, but as we do not know how we integrate the HealthPlattform this is a very easy way to solve the Problem for the moment.
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
                User user = (User) principal.getPrincipal();
                context.getClaims()
                        .claim("name", user.getUsername());
            }
        };
    }

}

import {NgModule} from '@angular/core';
import {AuthModule, LogLevel} from 'angular-auth-oidc-client';

@NgModule({
  imports: [
    AuthModule.forRoot({
      config: {
        configId: 'ms-angular-auth-oidc-client-lib-id',
        logLevel: LogLevel.Debug,
        historyCleanupOff: false,
        // Keycloak
        // authority: 'http://localhost:8088/realms/master',
        authority: 'http://127.0.0.1:8088',
        redirectUrl: 'http://127.0.0.1:4201/',
        // Keycloak
        // redirectUrl: 'http://localhost:4201/',
        postLogoutRedirectUri: 'http://127.0.0.1:4201/',
        clientId: 'medical-share-openid-connect-client-id',
        scope: 'openid',
        responseType: 'code',
        silentRenew: true,
        renewTimeBeforeTokenExpiresInSeconds: 10,
        autoUserInfo: false,
        useRefreshToken: true,
        secureRoutes: [
          'http://127.0.0.1:4201',
          'http://localhost:4201',
        ],
      },
    }),
  ],
  exports: [AuthModule],
})
export class AuthConfigModule {
}
-----------------------

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@RestController
@RequestMapping()
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() {
        this.rsaKeyPair = generateRsaKey();
        this.jwkRsaPublicKey = generateRsa(this.rsaKeyPair);
    }

    /**
     * Note this method is currently not use, but here for future use.
     * We use the same URL as in the Keycloak, so we have not to change things when running the thing against ms-backend-test-openid-connect-mock or Keycloak.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/certs", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    /**
     * This is used in the SystemTest. There we download the private key and sign the JWT.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    public RSAKey getJwkRsaPublicKey() {
        return this.jwkRsaPublicKey;
    }

    private RSAKey generateRsa(KeyPair keyPair) {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
    }

    private KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class PersistedUserConfig {

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("U-294b70ca67df4c018f59950f35314944")
                .password("U-294b70ca67df4c018f59950f35314944")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

}


import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.*;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class TestAuthorizationServerConfig {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());


    @PostConstruct
    public void publicNote() {
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
        logger.info("Note that the current spring authorisation server does not support token renewal. If you want to test that, use the Keycloak");
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
    }

    public static CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        config.addAllowedOrigin("127.0.0.1:4201");
        config.addAllowedOrigin("http://127.0.0.1:4201");
        config.addAllowedOrigin("localhost:4201");

        config.addAllowedOrigin("127.0.0.1:4200");
        config.addAllowedOrigin("http://127.0.0.1:4200");
        config.addAllowedOrigin("localhost:4200");

        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        return http.cors().configurationSource(corsConfigurationSource()).and()
                .authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/login")
                .authenticated()
                .and()
                .formLogin(withDefaults())
                .build();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(withDefaults()).cors().configurationSource(corsConfigurationSource()).and().build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("medical-share-openid-connect-client-id")
                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)

                .redirectUri("http://127.0.0.1:4200")
                .redirectUri("http://127.0.0.1:4200/")

                .redirectUri("http://127.0.0.1:4201")
                .redirectUri("http://127.0.0.1:4201/")
                .scope(OidcScopes.OPENID)
                .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofDays(1)).build())
                .scope("offline_access")
//                .scope("message.read")
//                .scope("message.write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).requireProofKey(true).build())
                .build();

        // Save registered client in db as if in-memory
        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
        registeredClientRepository.save(publicClient);

        return registeredClientRepository;
    }

    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource(OpenIdConnectMockController openIdConnectMockController) {
        RSAKey rsaKey = openIdConnectMockController.getJwkRsaPublicKey();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://127.0.0.1:8088").build();
    }

    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
    }

    /**
     * This is a bit a hack, but as we do not know how we integrate the HealthPlattform this is a very easy way to solve the Problem for the moment.
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
                User user = (User) principal.getPrincipal();
                context.getClaims()
                        .claim("name", user.getUsername());
            }
        };
    }

}

import {NgModule} from '@angular/core';
import {AuthModule, LogLevel} from 'angular-auth-oidc-client';

@NgModule({
  imports: [
    AuthModule.forRoot({
      config: {
        configId: 'ms-angular-auth-oidc-client-lib-id',
        logLevel: LogLevel.Debug,
        historyCleanupOff: false,
        // Keycloak
        // authority: 'http://localhost:8088/realms/master',
        authority: 'http://127.0.0.1:8088',
        redirectUrl: 'http://127.0.0.1:4201/',
        // Keycloak
        // redirectUrl: 'http://localhost:4201/',
        postLogoutRedirectUri: 'http://127.0.0.1:4201/',
        clientId: 'medical-share-openid-connect-client-id',
        scope: 'openid',
        responseType: 'code',
        silentRenew: true,
        renewTimeBeforeTokenExpiresInSeconds: 10,
        autoUserInfo: false,
        useRefreshToken: true,
        secureRoutes: [
          'http://127.0.0.1:4201',
          'http://localhost:4201',
        ],
      },
    }),
  ],
  exports: [AuthModule],
})
export class AuthConfigModule {
}
-----------------------

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

@RestController
@RequestMapping()
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() {
        this.rsaKeyPair = generateRsaKey();
        this.jwkRsaPublicKey = generateRsa(this.rsaKeyPair);
    }

    /**
     * Note this method is currently not use, but here for future use.
     * We use the same URL as in the Keycloak, so we have not to change things when running the thing against ms-backend-test-openid-connect-mock or Keycloak.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/certs", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    /**
     * This is used in the SystemTest. There we download the private key and sign the JWT.
     */
    @GetMapping(path = "/realms/master/protocol/openid-connect/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    public RSAKey getJwkRsaPublicKey() {
        return this.jwkRsaPublicKey;
    }

    private RSAKey generateRsa(KeyPair keyPair) {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
    }

    private KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class PersistedUserConfig {

    @Bean
    UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("U-294b70ca67df4c018f59950f35314944")
                .password("U-294b70ca67df4c018f59950f35314944")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

}


import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.*;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.config.TokenSettings;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class TestAuthorizationServerConfig {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());


    @PostConstruct
    public void publicNote() {
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
        logger.info("Note that the current spring authorisation server does not support token renewal. If you want to test that, use the Keycloak");
        logger.info("****************************************************************************************************************************");
        logger.info("****************************************************************************************************************************");
    }

    public static CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        config.addAllowedOrigin("127.0.0.1:4201");
        config.addAllowedOrigin("http://127.0.0.1:4201");
        config.addAllowedOrigin("localhost:4201");

        config.addAllowedOrigin("127.0.0.1:4200");
        config.addAllowedOrigin("http://127.0.0.1:4200");
        config.addAllowedOrigin("localhost:4200");

        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        return http.cors().configurationSource(corsConfigurationSource()).and()
                .authorizeRequests()
                .antMatchers("/**")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/login")
                .authenticated()
                .and()
                .formLogin(withDefaults())
                .build();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        return http.formLogin(withDefaults()).cors().configurationSource(corsConfigurationSource()).and().build();
    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("medical-share-openid-connect-client-id")
                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)

                .redirectUri("http://127.0.0.1:4200")
                .redirectUri("http://127.0.0.1:4200/")

                .redirectUri("http://127.0.0.1:4201")
                .redirectUri("http://127.0.0.1:4201/")
                .scope(OidcScopes.OPENID)
                .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofDays(1)).build())
                .scope("offline_access")
//                .scope("message.read")
//                .scope("message.write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).requireProofKey(true).build())
                .build();

        // Save registered client in db as if in-memory
        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
        registeredClientRepository.save(publicClient);

        return registeredClientRepository;
    }

    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource(OpenIdConnectMockController openIdConnectMockController) {
        RSAKey rsaKey = openIdConnectMockController.getJwkRsaPublicKey();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
    }

    @Bean
    public ProviderSettings providerSettings() {
        return ProviderSettings.builder().issuer("http://127.0.0.1:8088").build();
    }

    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
    }

    /**
     * This is a bit a hack, but as we do not know how we integrate the HealthPlattform this is a very easy way to solve the Problem for the moment.
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return context -> {
            Authentication principal = context.getPrincipal();
            if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
                User user = (User) principal.getPrincipal();
                context.getClaims()
                        .claim("name", user.getUsername());
            }
        };
    }

}

import {NgModule} from '@angular/core';
import {AuthModule, LogLevel} from 'angular-auth-oidc-client';

@NgModule({
  imports: [
    AuthModule.forRoot({
      config: {
        configId: 'ms-angular-auth-oidc-client-lib-id',
        logLevel: LogLevel.Debug,
        historyCleanupOff: false,
        // Keycloak
        // authority: 'http://localhost:8088/realms/master',
        authority: 'http://127.0.0.1:8088',
        redirectUrl: 'http://127.0.0.1:4201/',
        // Keycloak
        // redirectUrl: 'http://localhost:4201/',
        postLogoutRedirectUri: 'http://127.0.0.1:4201/',
        clientId: 'medical-share-openid-connect-client-id',
        scope: 'openid',
        responseType: 'code',
        silentRenew: true,
        renewTimeBeforeTokenExpiresInSeconds: 10,
        autoUserInfo: false,
        useRefreshToken: true,
        secureRoutes: [
          'http://127.0.0.1:4201',
          'http://localhost:4201',
        ],
      },
    }),
  ],
  exports: [AuthModule],
})
export class AuthConfigModule {
}

Pass user id as a header in downstream request. Spring Cloud Gateway + Oauth2 Resource Server

copy iconCopydownload iconDownload
public class UserHeaderFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return ReactiveSecurityContextHolder.getContext()
                .filter(c -> c.getAuthentication() != null)
                .flatMap(c -> {
                    JwtAuthenticationToken jwt = (JwtAuthenticationToken) c.getAuthentication();

                    String user = (String) jwt.getTokenAttributes().get("user");
                    if (Strings.isNullOrEmpty(user)) {
                        return Mono.error(
                                new AccessDeniedException("Invalid token. User is not present in token.")
                        );
                    }

                    ServerHttpRequest request = exchange.getRequest().mutate()
                            .header("x-user", user).build();

                    return chain.filter(exchange.mutate().request(request).build());
                })
                .switchIfEmpty(chain.filter(exchange));
    }
}

Upgrading from springboot version 2.3.8.RELEASE to 2.4.0 and getting these errors for junit tests

copy iconCopydownload iconDownload
implementation "org.springframework.boot:spring-boot-starter-actuator"
compileOnly "org.springframework.boot:spring-boot-starter-actuator"
-----------------------
implementation "org.springframework.boot:spring-boot-starter-actuator"
compileOnly "org.springframework.boot:spring-boot-starter-actuator"

How to get JWT claims in a Spring Service or Controller

copy iconCopydownload iconDownload
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
-----------------------
 .addFilterBefore(new TokenAuthenticationFilter(tokenHelper, jwtUserDetailsService), BasicAuthenticationFilter.class);
@Override
public void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain chain
) throws IOException, ServletException {

    String username;
    String authToken = tokenHelper.getToken(request);

    if (authToken != null) {
        // get username from token
        username = tokenHelper.getUsernameFromToken(authToken);
        if (username != null) {
            // get user
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (tokenHelper.validateToken(authToken, userDetails)) {
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = getAuthHeaderFromHeader( request );
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
public String getUsernameFromToken(String token) {
    String username;
    try {
        final Claims claims = this.getAllClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}
private Claims getAllClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}+
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.KeyLengthException;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;

random NullPointerException / onErrorDropped using webClient, due to request.getSession() being null

copy iconCopydownload iconDownload
 private final ExecutorService solrRequestExecutor = Executors.newSingleThreadExecutor();
private void triggerRequest(RequestBodySpec requestToSolr,
                                                             TicketIndex ticketIndex,
                                                              String action) {

// performing calls to Solr asynchronously
solrRequestExecutor.submit(
    () ->
requestToSolr.bodyValue(ticketIndex)
    .retrieve()
    .onStatus(HttpStatus::is2xxSuccessful,
              resp -> logSuccess(ticketIndex,action))
    .bodyToMono(String.class)
    .doOnError(t ->
        log.error("problem while performing a "+action+", "
            + "calling Solr for ticket "+ticketIndex.getUserFriendlyTicketId(),t))
    .block());
}
-----------------------
 private final ExecutorService solrRequestExecutor = Executors.newSingleThreadExecutor();
private void triggerRequest(RequestBodySpec requestToSolr,
                                                             TicketIndex ticketIndex,
                                                              String action) {

// performing calls to Solr asynchronously
solrRequestExecutor.submit(
    () ->
requestToSolr.bodyValue(ticketIndex)
    .retrieve()
    .onStatus(HttpStatus::is2xxSuccessful,
              resp -> logSuccess(ticketIndex,action))
    .bodyToMono(String.class)
    .doOnError(t ->
        log.error("problem while performing a "+action+", "
            + "calling Solr for ticket "+ticketIndex.getUserFriendlyTicketId(),t))
    .block());
}

How to use AuthorizationServer in a SystemTest to create JWT tokens without Authentication

copy iconCopydownload iconDownload
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

@RestController
@RequestMapping("/openid-connect/mock")
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() throws NoSuchAlgorithmException, JOSEException {
        this.rsaKeyPair = generateRsaKeyPair(2048);
        logger.info("generate key {}", this.rsaKeyPair.getPublic());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) this.rsaKeyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) this.rsaKeyPair.getPrivate();
        this.jwkRsaPublicKey = new RSAKey.Builder(rsaPublicKey).build();
        logger.info("jwkRsaPublicKey (JWK-Format) {}", this.jwkRsaPublicKey);
    }

    @GetMapping(path = "/keys", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    @GetMapping(path = "/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    private KeyPair generateRsaKeyPair(int keyLengthInt) throws NoSuchAlgorithmException {
        KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
        keypairGenerator.initialize(keyLengthInt, new SecureRandom());
        return keypairGenerator.generateKeyPair();
    }

}
 public static Jwt jwtTokenClient(String userId) {
        byte[] privateKey = OpenIdConnectMockService.privateKey(openIdConnectMockWebClient);
        return JwtUtil.createJWT(privateKey, UUID.randomUUID().toString(), "MS-SystemTest-Issuer", userId);
    }
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;

public class JwtUtil {

    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;

    private JwtUtil() {
    }

    public static Jwt createJWT(byte[] privateKey, String id, String issuer, String subject) {
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;

        long nowMillis = System.currentTimeMillis();

        //We will sign our JWT with our ApiKey secret
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory rsaFact = null;
        try {
            rsaFact = KeyFactory.getInstance("RSA");
            RSAPrivateKey key = (RSAPrivateKey) rsaFact.generatePrivate(spec);

            JwtBuilder builder = Jwts.builder().setId(id)
                    .setIssuedAt(new Date(nowMillis))
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .setExpiration(new Date(nowMillis + DAY_IN_MILLIS))
                    .signWith(signatureAlgorithm, key);

            //Builds the JWT and serializes it to a compact, URL-safe string
            return new Jwt(builder.compact());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }

}
-----------------------
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

@RestController
@RequestMapping("/openid-connect/mock")
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() throws NoSuchAlgorithmException, JOSEException {
        this.rsaKeyPair = generateRsaKeyPair(2048);
        logger.info("generate key {}", this.rsaKeyPair.getPublic());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) this.rsaKeyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) this.rsaKeyPair.getPrivate();
        this.jwkRsaPublicKey = new RSAKey.Builder(rsaPublicKey).build();
        logger.info("jwkRsaPublicKey (JWK-Format) {}", this.jwkRsaPublicKey);
    }

    @GetMapping(path = "/keys", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    @GetMapping(path = "/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    private KeyPair generateRsaKeyPair(int keyLengthInt) throws NoSuchAlgorithmException {
        KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
        keypairGenerator.initialize(keyLengthInt, new SecureRandom());
        return keypairGenerator.generateKeyPair();
    }

}
 public static Jwt jwtTokenClient(String userId) {
        byte[] privateKey = OpenIdConnectMockService.privateKey(openIdConnectMockWebClient);
        return JwtUtil.createJWT(privateKey, UUID.randomUUID().toString(), "MS-SystemTest-Issuer", userId);
    }
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;

public class JwtUtil {

    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;

    private JwtUtil() {
    }

    public static Jwt createJWT(byte[] privateKey, String id, String issuer, String subject) {
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;

        long nowMillis = System.currentTimeMillis();

        //We will sign our JWT with our ApiKey secret
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory rsaFact = null;
        try {
            rsaFact = KeyFactory.getInstance("RSA");
            RSAPrivateKey key = (RSAPrivateKey) rsaFact.generatePrivate(spec);

            JwtBuilder builder = Jwts.builder().setId(id)
                    .setIssuedAt(new Date(nowMillis))
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .setExpiration(new Date(nowMillis + DAY_IN_MILLIS))
                    .signWith(signatureAlgorithm, key);

            //Builds the JWT and serializes it to a compact, URL-safe string
            return new Jwt(builder.compact());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }

}
-----------------------
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.RSAKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.invoke.MethodHandles;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

@RestController
@RequestMapping("/openid-connect/mock")
public class OpenIdConnectMockController {

    static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private KeyPair rsaKeyPair;
    private RSAKey jwkRsaPublicKey;

    @PostConstruct
    public void generateKey() throws NoSuchAlgorithmException, JOSEException {
        this.rsaKeyPair = generateRsaKeyPair(2048);
        logger.info("generate key {}", this.rsaKeyPair.getPublic());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) this.rsaKeyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) this.rsaKeyPair.getPrivate();
        this.jwkRsaPublicKey = new RSAKey.Builder(rsaPublicKey).build();
        logger.info("jwkRsaPublicKey (JWK-Format) {}", this.jwkRsaPublicKey);
    }

    @GetMapping(path = "/keys", produces = "application/json")
    public String keys() {
        logger.info("Keys was called {}", this.jwkRsaPublicKey.toString());
        return "{\"keys\":[" + this.jwkRsaPublicKey.toString() + "]}";
    }

    @GetMapping(path = "/private-key", produces = "application/json")
    public byte[] getPrivateKey() throws JOSEException {
        RSAKey privateKey = new RSAKey.Builder((RSAPublicKey) this.rsaKeyPair.getPublic()).privateKey(this.rsaKeyPair.getPrivate()).build();
        return privateKey.toRSAPrivateKey().getEncoded();
    }

    private KeyPair generateRsaKeyPair(int keyLengthInt) throws NoSuchAlgorithmException {
        KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
        keypairGenerator.initialize(keyLengthInt, new SecureRandom());
        return keypairGenerator.generateKeyPair();
    }

}
 public static Jwt jwtTokenClient(String userId) {
        byte[] privateKey = OpenIdConnectMockService.privateKey(openIdConnectMockWebClient);
        return JwtUtil.createJWT(privateKey, UUID.randomUUID().toString(), "MS-SystemTest-Issuer", userId);
    }
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;

public class JwtUtil {

    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;

    private JwtUtil() {
    }

    public static Jwt createJWT(byte[] privateKey, String id, String issuer, String subject) {
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;

        long nowMillis = System.currentTimeMillis();

        //We will sign our JWT with our ApiKey secret
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory rsaFact = null;
        try {
            rsaFact = KeyFactory.getInstance("RSA");
            RSAPrivateKey key = (RSAPrivateKey) rsaFact.generatePrivate(spec);

            JwtBuilder builder = Jwts.builder().setId(id)
                    .setIssuedAt(new Date(nowMillis))
                    .setSubject(subject)
                    .setIssuer(issuer)
                    .setExpiration(new Date(nowMillis + DAY_IN_MILLIS))
                    .signWith(signatureAlgorithm, key);

            //Builds the JWT and serializes it to a compact, URL-safe string
            return new Jwt(builder.compact());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }

}

JHipster - Spring. Oauth2 resource server configuration. Create resource server

copy iconCopydownload iconDownload
.oauth2ResourceServer()
    .jwt()
    .jwtAuthenticationConverter(authenticationConverter())
    .and()
.and()
    .oauth2Client();

Spring Authorization Server: How to use login form hosted on a separate application?

copy iconCopydownload iconDownload
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        // @formatter:off
        http
            .exceptionHandling(exceptionHandling -> exceptionHandling
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("https://some-other-sso.example/login"))
            );
        // @formatter:on
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        // @formatter:on

        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder(PublicKey publicKey) {
        return NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build();
    }

    @Bean
    public BearerTokenResolver bearerTokenResolver() {
        DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
        bearerTokenResolver.setAllowUriQueryParameter(true);
        return bearerTokenResolver;
    }
@Controller
public class SsoController {
    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        this.successHandler.onAuthenticationSuccess(request, response, authentication);
    }
}
-----------------------
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        // @formatter:off
        http
            .exceptionHandling(exceptionHandling -> exceptionHandling
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("https://some-other-sso.example/login"))
            );
        // @formatter:on
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        // @formatter:on

        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder(PublicKey publicKey) {
        return NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build();
    }

    @Bean
    public BearerTokenResolver bearerTokenResolver() {
        DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
        bearerTokenResolver.setAllowUriQueryParameter(true);
        return bearerTokenResolver;
    }
@Controller
public class SsoController {
    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        this.successHandler.onAuthenticationSuccess(request, response, authentication);
    }
}

Community Discussions

Trending Discussions on spring-security-oauth
  • java.lang.ClassNotFoundException: org.apache.wicket.settings.def.JavaScriptLibrarySettings
  • The page isn’t redirecting properly while trying to log in with Spring Authorization Server using custom user details service
  • spring-security-oauth2-authorization-server + angular-auth-oidc-client
  • Pass user id as a header in downstream request. Spring Cloud Gateway + Oauth2 Resource Server
  • spring-authorization-server and OpenId Connect and angular-oauth2-oidc
  • Upgrading from springboot version 2.3.8.RELEASE to 2.4.0 and getting these errors for junit tests
  • How to get JWT claims in a Spring Service or Controller
  • random NullPointerException / onErrorDropped using webClient, due to request.getSession() being null
  • How to use AuthorizationServer in a SystemTest to create JWT tokens without Authentication
  • JHipster - Spring. Oauth2 resource server configuration. Create resource server
Trending Discussions on spring-security-oauth

QUESTION

java.lang.ClassNotFoundException: org.apache.wicket.settings.def.JavaScriptLibrarySettings

Asked 2022-Apr-14 at 18:20

I have wicket application and it sometimes fails on :

java.lang.NoClassDefFoundError: org/apache/wicket/settings/def/JavaScriptLibrarySettings java.base/java.lang.ClassLoader.defineClass1(Native Method) java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)

I have this mvn configuration :

[INFO] com.dhl.crdb:crdb:war:1.2.2-SNAPSHOT
[INFO] +- com.dhl.webcommon:dhl-wc:jar:1.2.30.0:compile
[INFO] |  +- org.springframework:spring-tx:jar:5.3.18:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-webmvc:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-core:jar:5.3.18:compile
[INFO] |  |  \- org.springframework:spring-jcl:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-orm:jar:5.1.6.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:5.1.6.RELEASE:compile
[INFO] |  +- org.springframework:spring-web:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-expression:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-aop:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-aspects:jar:5.3.18:compile
[INFO] |  |  \- org.aspectj:aspectjweaver:jar:1.9.7:compile
[INFO] |  +- org.springframework:spring-jms:jar:5.3.18:compile
[INFO] |  |  \- org.springframework:spring-messaging:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-context:jar:5.3.18:compile
[INFO] |  +- org.springframework:spring-context-support:jar:5.3.18:compile
[INFO] |  +- org.springframework.security:spring-security-core:jar:3.2.3.RELEASE:compile
[INFO] |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework.security:spring-security-web:jar:3.2.3.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-config:jar:3.2.3.RELEASE:compile
[INFO] |  +- org.springframework.batch:spring-batch-core:jar:2.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.batch:spring-batch-infrastructure:jar:2.2.1.RELEASE:compile
[INFO] |  |  |  \- org.springframework.retry:spring-retry:jar:1.0.2.RELEASE:compile
[INFO] |  |  +- com.thoughtworks.xstream:xstream:jar:1.3:compile
[INFO] |  |  |  \- xpp3:xpp3_min:jar:1.1.4c:compile
[INFO] |  |  \- org.codehaus.jettison:jettison:jar:1.1:compile
[INFO] |  +- org.springframework.ldap:spring-ldap-core:jar:1.3.2.RELEASE:compile
[INFO] |  +- org.apache.wicket:wicket-core:jar:8.14.0:compile
[INFO] |  |  +- com.github.openjson:openjson:jar:1.0.11:compile
[INFO] |  |  +- org.apache.wicket:wicket-request:jar:8.14.0:compile
[INFO] |  |  +- org.apache.wicket:wicket-util:jar:8.14.0:compile
[INFO] |  |  \- org.danekja:jdk-serializable-functional:jar:1.8.6:compile
[INFO] |  +- org.apache.wicket:wicket-spring:jar:8.14.0:compile
[INFO] |  |  \- org.apache.wicket:wicket-ioc:jar:8.14.0:compile
[INFO] |  |     +- cglib:cglib-nodep:jar:3.2.12:compile
[INFO] |  |     +- javax.inject:javax.inject:jar:1:compile
[INFO] |  |     \- org.ow2.asm:asm-util:jar:7.1:compile
[INFO] |  |        +- org.ow2.asm:asm:jar:7.1:compile
[INFO] |  |        +- org.ow2.asm:asm-tree:jar:7.1:compile
[INFO] |  |        \- org.ow2.asm:asm-analysis:jar:7.1:compile
[INFO] |  +- org.wicketstuff:wicketstuff-minis:jar:8.14.0:compile
[INFO] |  +- org.apache.wicket:wicket-bean-validation:jar:8.13.0:compile
[INFO] |  +- com.vaynberg.wicket.select2:wicket-select2:jar:4.1:compile
[INFO] |  +- cas:casclient:jar:2.1.1:compile
[INFO] |  |  \- commons-logging:commons-logging:jar:1.0.4:compile
[INFO] |  +- org.jasig.cas:cas-client-core:jar:3.1.2:compile
[INFO] |  +- joda-time:joda-time-hibernate:jar:1.3:compile
[INFO] |  +- org.jadira.usertype:usertype.jodatime:jar:2.0.1:compile
[INFO] |  |  \- org.jadira.usertype:usertype.spi:jar:2.0.1:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.3.6.Final:compile
[INFO] |  |  +- javax.persistence:javax.persistence-api:jar:2.2:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.23.1-GA:compile
[INFO] |  |  +- net.bytebuddy:byte-buddy:jar:1.8.17:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.1.1.Final:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.5.Final:compile
[INFO] |  |  +- javax.activation:javax.activation-api:jar:1.2.0:compile
[INFO] |  |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.4.Final:compile
[INFO] |  +- commons-dbcp:commons-dbcp:jar:1.4:compile
[INFO] |  |  \- commons-pool:commons-pool:jar:1.5.4:compile
[INFO] |  +- org.hibernate:hibernate-ehcache:jar:5.3.6.Final:compile
[INFO] |  |  \- net.sf.ehcache:ehcache:jar:2.10.3:compile
[INFO] |  +- com.ibm.icu:icu4j:jar:4.0.1:compile
[INFO] |  +- org.apache.xmlbeans:xmlbeans:jar:2.6.0:compile
[INFO] |  |  \- stax:stax-api:jar:1.0.1:compile
[INFO] |  +- com.oracle:ojdbc16:jar:11.2.0.3.0:runtime
[INFO] |  +- commons-lang:commons-lang:jar:2.6:compile
[INFO] |  +- org.aspectj:aspectjrt:jar:1.5.4:compile
[INFO] |  +- log4j:log4j:jar:1.2.17:compile
[INFO] |  +- commons-io:commons-io:jar:2.4:compile
[INFO] |  +- org.hibernate:hibernate-envers:jar:5.3.6.Final:compile
[INFO] |  +- javax.mail:mail:jar:1.4.4:compile
[INFO] |  |  \- javax.activation:activation:jar:1.1:compile
[INFO] |  +- com.code-troopers:wicket-editable-grid:jar:0.1:compile
[INFO] |  +- org.apache.cxf:cxf-rt-databinding-jaxb:jar:2.7.3:compile
[INFO] |  |  +- org.apache.cxf:cxf-api:jar:2.7.3:compile
[INFO] |  |  |  +- org.codehaus.woodstox:woodstox-core-asl:jar:4.1.4:runtime
[INFO] |  |  |  |  \- org.codehaus.woodstox:stax2-api:jar:3.1.1:runtime
[INFO] |  |  |  +- org.apache.ws.xmlschema:xmlschema-core:jar:2.0.3:compile
[INFO] |  |  |  \- wsdl4j:wsdl4j:jar:1.6.2:compile
[INFO] |  |  +- org.apache.cxf:cxf-rt-core:jar:2.7.3:compile
[INFO] |  |  +- com.sun.xml.bind:jaxb-impl:jar:2.1.13:compile
[INFO] |  |  \- com.sun.xml.bind:jaxb-xjc:jar:2.1.13:compile
[INFO] |  +- org.apache.cxf:cxf-rt-frontend-jaxws:jar:2.7.3:compile
[INFO] |  |  +- xml-resolver:xml-resolver:jar:1.2:compile
[INFO] |  |  +- asm:asm:jar:3.3.1:compile
[INFO] |  |  +- org.apache.cxf:cxf-rt-bindings-soap:jar:2.7.3:compile
[INFO] |  |  +- org.apache.cxf:cxf-rt-bindings-xml:jar:2.7.3:compile
[INFO] |  |  +- org.apache.cxf:cxf-rt-frontend-simple:jar:2.7.3:compile
[INFO] |  |  \- org.apache.cxf:cxf-rt-ws-addr:jar:2.7.3:compile
[INFO] |  |     \- org.apache.cxf:cxf-rt-ws-policy:jar:2.7.3:compile
[INFO] |  |        \- org.apache.neethi:neethi:jar:3.0.2:compile
[INFO] |  +- org.apache.cxf:cxf-rt-transports-http:jar:2.7.3:compile
[INFO] |  +- org.apache.httpcomponents:httpclient:jar:4.4:compile
[INFO] |  |  \- org.apache.httpcomponents:httpcore:jar:4.4:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-core:jar:2.9.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.1:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.1:compile
[INFO] |  +- com.fasterxml.jackson.datatype:jackson-datatype-joda:jar:2.9.1:compile
[INFO] |  |  \- joda-time:joda-time:jar:2.7:compile
[INFO] |  +- com.googlecode.wicket-jquery-ui:wicket-jquery-ui:jar:8.13.0:compile
[INFO] |  |  \- com.googlecode.wicket-jquery-ui:wicket-jquery-ui-core:jar:8.13.0:compile
[INFO] |  +- com.dhl.webcommon:saml-filter:jar:1.0.10.0:compile
[INFO] |  +- com.dhl.webcommon:dhl-dbc:jar:1.1.82.0:compile
[INFO] |  +- com.dhl.webcommon:dhl-resources:jar:1.1.160.0:compile
[INFO] |  \- org.flywaydb:flyway-core:jar:4.0.3:compile
[INFO] +- org.codehaus.mojo:animal-sniffer-annotations:jar:1.14:compile
[INFO] +- javax.validation:validation-api:jar:2.0.1.Final:compile
[INFO] +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] +- javax.xml.ws:jaxws-api:jar:2.2.12:compile
[INFO] |  \- javax.xml.soap:javax.xml.soap-api:jar:1.3.5:compile
[INFO] +- javax.jws:javax.jws-api:jar:1.1:compile
[INFO] +- net.logstash.logback:logstash-logback-encoder:jar:6.3:compile
[INFO] +- org.codehaus.janino:janino:jar:3.0.6:compile
[INFO] |  \- org.codehaus.janino:commons-compiler:jar:3.0.6:compile
[INFO] +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.12.RELEASE:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.9:compile
[INFO] |  \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |     \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] +- net.ttddyy:datasource-proxy:jar:1.4.1:compile
[INFO] |  \- org.mockito:mockito-core:jar:1.9.5:compile
[INFO] |     \- org.objenesis:objenesis:jar:1.0:compile
[INFO] +- junit:junit:jar:4.11:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.hsqldb:hsqldb:jar:2.2.8:test
[INFO] +- org.mockito:mockito-all:jar:1.9.5:test
[INFO] +- javax.servlet:javax.servlet-api:jar:3.0.1:test
[INFO] +- com.jayway.jsonpath:json-path:jar:0.8.1:test
[INFO] |  \- net.minidev:json-smart:jar:1.1.1:test
[INFO] +- com.jayway.jsonpath:json-path-assert:jar:0.8.1:test
[INFO] |  \- org.hamcrest:hamcrest-library:jar:1.2.1:test
[INFO] +- org.wicketstuff:wicketstuff-tinymce:jar:6.30.0:compile
[INFO] |  +- org.apache.wicket:wicket-extensions:jar:6.30.0:compile
[INFO] |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  +- net.sf.jazzy:jazzy:jar:0.5.2-rtext-1.4.1:compile
[INFO] |  +- org.json:json:jar:20090211:compile
[INFO] |  \- org.apache.wicket:wicket:pom:6.30.0:compile
[INFO] +- javax.servlet:servlet-api:jar:2.5:provided
[INFO] +- org.apache.tika:tika-core:jar:1.17:compile
[INFO] +- org.hibernate.validator:hibernate-validator:jar:6.0.12.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.3.2.Final:compile
[INFO] |  \- com.fasterxml:classmate:jar:1.3.4:compile
[INFO] +- org.hibernate.validator:hibernate-validator-annotation-processor:jar:6.0.12.Final:compile
[INFO] +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.2.Final:compile
[INFO] +- org.apache.poi:poi:jar:3.17:compile
[INFO] +- org.apache.poi:poi-ooxml:jar:3.17:compile
[INFO] |  \- com.github.virtuald:curvesapi:jar:1.04:compile
[INFO] +- org.apache.poi:ooxml-schemas:jar:1.1:compile
[INFO] +- org.apache.poi:poi-ooxml-schemas:jar:3.14:compile
[INFO] +- javax.xml.bind:jaxb-api:jar:2.2.11:compile
[INFO] +- io.springfox:springfox-swagger2:jar:2.9.2:compile
[INFO] |  +- io.swagger:swagger-annotations:jar:1.5.20:compile
[INFO] |  +- io.swagger:swagger-models:jar:1.5.20:compile
[INFO] |  +- io.springfox:springfox-spi:jar:2.9.2:compile
[INFO] |  |  \- io.springfox:springfox-core:jar:2.9.2:compile
[INFO] |  +- io.springfox:springfox-schema:jar:2.9.2:compile
[INFO] |  +- io.springfox:springfox-swagger-common:jar:2.9.2:compile
[INFO] |  +- io.springfox:springfox-spring-web:jar:2.9.2:compile
[INFO] |  +- org.springframework.plugin:spring-plugin-core:jar:1.2.0.RELEASE:compile
[INFO] |  +- org.springframework.plugin:spring-plugin-metadata:jar:1.2.0.RELEASE:compile
[INFO] |  \- org.mapstruct:mapstruct:jar:1.2.0.Final:compile
[INFO] +- io.springfox:springfox-swagger-ui:jar:2.9.2:compile
[INFO] +- com.google.guava:guava:jar:21.0:compile
[INFO] +- io.jsonwebtoken:jjwt:jar:0.7.0:compile
[INFO] +- com.google.code.findbugs:jsr305:jar:3.0.2:compile
[INFO] +- org.apache.commons:commons-collections4:jar:4.1:compile
[INFO] +- io.swagger:swagger-jaxrs:jar:1.6.0:compile
[INFO] |  +- io.swagger:swagger-core:jar:1.6.0:compile
[INFO] |  |  +- org.apache.commons:commons-lang3:jar:3.2.1:compile
[INFO] |  |  \- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:jar:2.10.1:compile
[INFO] |  |     \- org.yaml:snakeyaml:jar:1.24:compile
[INFO] |  +- javax.ws.rs:jsr311-api:jar:1.1.1:compile
[INFO] |  \- org.reflections:reflections:jar:0.9.11:compile
[INFO] +- org.owasp.esapi:esapi:jar:2.2.3.1:compile
[INFO] |  +- com.io7m.xom:xom:jar:1.2.10:compile
[INFO] |  +- commons-beanutils:commons-beanutils:jar:1.9.4:compile
[INFO] |  +- commons-configuration:commons-configuration:jar:1.10:compile
[INFO] |  +- commons-fileupload:commons-fileupload:jar:1.3.3:compile
[INFO] |  +- org.apache-extras.beanshell:bsh:jar:2.0b6:compile
[INFO] |  +- org.owasp.antisamy:antisamy:jar:1.6.3:compile
[INFO] |  |  +- net.sourceforge.nekohtml:nekohtml:jar:1.9.22:compile
[INFO] |  |  +- org.apache.xmlgraphics:batik-css:jar:1.14:compile
[INFO] |  |  |  +- org.apache.xmlgraphics:batik-shared-resources:jar:1.14:compile
[INFO] |  |  |  +- org.apache.xmlgraphics:batik-util:jar:1.14:compile
[INFO] |  |  |  |  +- org.apache.xmlgraphics:batik-constants:jar:1.14:compile
[INFO] |  |  |  |  \- org.apache.xmlgraphics:batik-i18n:jar:1.14:compile
[INFO] |  |  |  \- org.apache.xmlgraphics:xmlgraphics-commons:jar:2.6:compile
[INFO] |  |  +- xerces:xercesImpl:jar:2.12.1:compile
[INFO] |  |  \- xml-apis:xml-apis-ext:jar:1.3.04:compile
[INFO] |  \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] \- org.springframework:spring-test:jar:4.3.1.RELEASE:test

Can someone please give me a point how to solve this issue? Im little stuck with it. In org.apache.wicket.settings there is JavaScriptLibrarySettings in wicket core. I dont know how to solve this issue, maybe there is some obsolate dependency. Thanks for help.

ANSWER

Answered 2022-Apr-14 at 18:20

Almost all Wicket dependencies are 8.14.0 but few are 8.13.0 (not really a problem but better keep them in sync):

  • org.apache.wicket:wicket-bean-validation:jar:8.13.0:compile
  • com.googlecode.wicket-jquery-ui:wicket-jquery-ui:jar:8.13.0:compile
  • com.googlecode.wicket-jquery-ui:wicket-jquery-ui-core:jar:8.13.0:compile

The real problem is:

[INFO] +- org.wicketstuff:wicketstuff-tinymce:jar:6.30.0:compile
[INFO] |  +- org.apache.wicket:wicket-extensions:jar:6.30.0:compile
[INFO] |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  +- net.sf.jazzy:jazzy:jar:0.5.2-rtext-1.4.1:compile
[INFO] |  +- org.json:json:jar:20090211:compile
[INFO] |  \- org.apache.wicket:wicket:pom:6.30.0:compile

Do not mix Wicket deps with differences in the major version (8 vs 6)!

Source https://stackoverflow.com/questions/71872709

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

Spring Security OAuth, versions 2.3 prior to 2.3.5, and 2.2 prior to 2.2.4, and 2.1 prior to 2.1.4, and 2.0 prior to 2.0.17, and older unsupported versions could be susceptible to an open redirector attack that can leak an authorization code. A malicious user or attacker can craft a request to the authorization endpoint using the authorization code grant type, and specify a manipulated redirection URI via the "redirect_uri" parameter. This can cause the authorization server to redirect the resource owner user-agent to a URI under the control of the attacker with the leaked authorization code. This vulnerability exposes applications that meet all of the following requirements: Act in the role of an Authorization Server (e.g. @EnableAuthorizationServer) and uses the DefaultRedirectResolver in the AuthorizationEndpoint. This vulnerability does not expose applications that: Act in the role of an Authorization Server and uses a different RedirectResolver implementation other than DefaultRedirectResolver, act in the role of a Resource Server only (e.g. @EnableResourceServer), act in the role of a Client only (e.g. @EnableOAuthClient).
Spring Security OAuth versions 2.3 prior to 2.3.6, 2.2 prior to 2.2.5, 2.1 prior to 2.1.5, and 2.0 prior to 2.0.18, as well as older unsupported versions could be susceptible to an open redirector attack that can leak an authorization code. A malicious user or attacker can craft a request to the authorization endpoint using the authorization code grant type, and specify a manipulated redirection URI via the redirect_uri parameter. This can cause the authorization server to redirect the resource owner user-agent to a URI under the control of the attacker with the leaked authorization code.

Install spring-security-oauth

Download or clone from GIT and then use Maven (3.0.*) and Java (1.6 or better):. Use the bootstrap profile only the first time - it enables some repositories that can't be exposed in the poms by default. You may find it useful to add this profile to your local settings.xml. You need to run Redis to get the build to work. You can install this using homebrew. Without Redis running the build will lots of Jedis connection exceptions. SpringSource ToolSuite users (or Eclipse users with the latest m2eclipse plugin) can import the projects as existing Maven projects. Spring Security OAuth is released under the terms of the Apache Software License Version 2.0 (see license.txt).

Support

Here are some ways for you to get involved in the community:. Before we accept a non-trivial patch or pull request we will need you to sign the contributor's agreement. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Reuse Pre-built Kits with spring-security-oauth
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.