kandi background
Explore Kits

spring-security-oauth2-client | OAuth2 client implementation for Spring Security | OAuth library

 by   pwheel Java Version: Current License: MIT

 by   pwheel Java Version: Current License: MIT

Download this library from

kandi X-RAY | spring-security-oauth2-client Summary

spring-security-oauth2-client is a Java library typically used in Security, OAuth applications. spring-security-oauth2-client has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has low support. You can download it from GitHub, Maven.
[![Build Status](https://travis-ci.org/pwheel/spring-security-oauth2-client.svg)](https://travis-ci.org/pwheel/spring-security-oauth2-client) [![Join the chat at https://gitter.im/pwheel/spring-security-oauth2-client](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/pwheel/spring-security-oauth2-client?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge). An OAuth2 client implementation for Spring Security that allows you to use an OAuth2 Provider (such as DailyCred) directly as an Authentication Provider.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • spring-security-oauth2-client has a low active ecosystem.
  • It has 16 star(s) with 33 fork(s). There are 4 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 0 open issues and 5 have been closed. On average issues are closed in 61 days. There are no pull requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of spring-security-oauth2-client 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-oauth2-client 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-oauth2-client has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • spring-security-oauth2-client 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-oauth2-client is licensed under the MIT 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-oauth2-client 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 are not available. Examples and code snippets are available.
  • It has 1526 lines of code, 132 functions and 19 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

kandi has reviewed spring-security-oauth2-client and discovered the below as its top functions. This is intended to give you an instant insight into spring-security-oauth2-client implemented functionality, and help decide if they suit your requirements.

  • Initiates the login request .
    • Loads the user information from the OAuth2 provider .
      • Performs OAuth authentication .
        • Authentication token .
          • Get an access token from the OAuth2 provider .
            • Gets user info from provider .
              • Check for errors .
                • Gets a response from the provider using the given authentication token .
                  • Construct the additional auth parameters .
                    • Gets user id .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      spring-security-oauth2-client Key Features

                      An OAuth2 client implementation for Spring Security that allows you to use an OAuth2 Provider (such as DailyCred) directly as an Authentication Provider

                      Usage

                      copy iconCopydownload iconDownload
                      <http entry-point-ref="oAuth2EntryPoint">
                          <logout logout-success-url="/index.shtml"/>
                          <custom-filter ref="oauth2AuthFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
                      </http>

                      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());
                      }
                      

                      500 Internal Server Error in redirect-uri request Webflux + OAuth2.0

                      copy iconCopydownload iconDownload
                      @Configuration(proxyBeanMethods = false)
                          @EnableWebFluxSecurity
                          @EnableReactiveMethodSecurity
                          public class WebFluxSecurityConfig {
                          
                              @Bean
                              public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, AuthenticationManager authenticationManager) {
                          
                                  return http
                                          .httpBasic().disable()
                                          .csrf().disable()
                                          .authorizeExchange(exchanges -> exchanges
                                                  .pathMatchers(HttpMethod.GET, "/oauth2/authorization/**",
                                                          "/actuator",
                                                          "/actuator/**",
                                                          "/auth/login",
                                                          "/login/**")
                                                  .permitAll()
                                                  .anyExchange()
                                                          .authenticated()
                                          .oauth2Login()
                                          .authenticationManager(authenticationManager)
                                          .and()
                                          .build();
                          
                              }
                      }
                      

                      Autogenerated OAuth2 login page for AWS Cognito in reactive Spring Boot application fails

                      copy iconCopydownload iconDownload
                      spring:
                        security:
                          oauth2:
                            client:
                              registration:
                                cognito:
                                  client-id: XXX
                                  client-secret: XXX
                                  scope: openid
                                  redirect-uri: http://localhost:8080/login/oauth2/code/cognito
                                  clientName: fitnesstest
                              provider:
                                cognito:
                                  issuerUri: https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_XXX
                      

                      How to avoid KeyLengthException when using Spring OAuth2 Resource Server and a symmetric key

                      copy iconCopydownload iconDownload
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      
                      Bytes.ensureCapacity(secretKey.getBytes(StandardCharsets.UTF_8), 128, 0);
                      
                        public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
                          Preconditions.checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
                          Preconditions.checkArgument(padding >= 0, "Invalid padding: %s", padding);
                          return array.length < minLength ? Arrays.copyOf(array, minLength + padding) : array;
                        }
                      
                      byte[] decodedBytes = Base64.decodeBase64(secret)
                      
                      Arrays.copyOf(decodedBytes, 128);
                      
                        private String generateToken(Map<String, Object> claims, String username) {
                      
                          Header header = Jwts.header();
                          header.setType("JWT");
                      
                          String jti = UUID.randomUUID().toString();
                          Date now = new Date(System.currentTimeMillis());
                      
                          return Jwts.builder()
                              .setClaims(claims)
                              .setHeader((Map<String, Object>) header)
                              .setSubject(username)
                              .setIssuedAt(now)
                              .setIssuer("issuer")
                              .setId(jti)
                              .signWith(SignatureAlgorithm.HS512, "asdf")
                              .compact();
                        }
                      
                        public JwtDecoder jwtDecoder() {
                        // base64 decoder from org.apache.tomcat.util.codec.binary.Base64;
                          byte[] key = Base64.decodeBase64("asdf");
                         // var key = "asdf".getBytes(StandardCharsets.UTF_8);
                          var paddedKey = Arrays.copyOf(key, 128);
                          return NimbusJwtDecoder
                              .withSecretKey(new SecretKeySpec(paddedKey, "HS512"))
                              .macAlgorithm(MacAlgorithm.HS512)
                              .build();
                        }
                      
                      Main s = new Main();
                      String token = s.generateToken(new HashMap<>(), "hatef");
                      JwtDecoder decoder = s.jwtDecoder();
                      System.out.println(decoder.decode(token));
                      

                      @RequestBody null can't understand why SpringBoot

                      copy iconCopydownload iconDownload
                      <file>
                              <fileDate>2020-12-25</fileDate>
                              <recordCount>2</recordCount>
                              <transactions>
                                  <transaction>
                                      <recordId>45</recordId>
                                  </transaction>
                              </transactions>
                          </file>
                      
                      package com.entities;
                      
                      import javax.xml.bind.annotation.XmlAccessType;
                      import javax.xml.bind.annotation.XmlAccessorType;
                      import javax.xml.bind.annotation.XmlElement;
                      import javax.xml.bind.annotation.XmlElementWrapper;
                      import javax.xml.bind.annotation.XmlRootElement;
                      import javax.xml.bind.annotation.XmlType;
                      import java.util.List;
                      
                      @XmlAccessorType(XmlAccessType.FIELD)
                      @XmlType(name = "", propOrder = {
                          "fileDate",
                          "recordCount",
                          "transactions"
                      })
                      @XmlRootElement(name = "file")
                      public class File {
                        @XmlElement(name = "fileDate", required = true)
                        protected String fileDate;
                        @XmlElement(name = "recordCount", required = true)
                        protected String recordCount;
                      
                        @XmlElementWrapper(name="transactions")
                        @XmlElement(name="transaction")
                        protected List<Transaction> transactions;
                      
                        public String getFileDate() {
                          return fileDate;
                        }
                      
                        public void setFileDate(String fileDate) {
                          this.fileDate = fileDate;
                        }
                      
                        public String getRecordCount() {
                          return recordCount;
                        }
                      
                        public void setRecordCount(String recordCount) {
                          this.recordCount = recordCount;
                        }
                      
                        public List<Transaction> getTransactions() {
                          return transactions;
                        }
                      
                        public void setTransactions(List<Transaction> transactions) {
                          this.transactions = transactions;
                      
                      
                           }
                          }
                      
                      package com.entities;
                      
                      import javax.xml.bind.annotation.XmlAccessType;
                      import javax.xml.bind.annotation.XmlAccessorType;
                      import javax.xml.bind.annotation.XmlElement;
                      import javax.xml.bind.annotation.XmlRootElement;
                      import javax.xml.bind.annotation.XmlType;
                      
                      @XmlAccessorType(XmlAccessType.FIELD)
                      @XmlType(name = "", propOrder = {
                          "recordId"
                      })
                      @XmlRootElement(name = "transaction")
                      public class Transaction {
                        @XmlElement(name = "recordId", required = true)
                        protected String recordId;
                      
                        public String getRecordId() {
                          return recordId;
                        }
                      
                        public void setRecordId(String recordId) {
                          this.recordId = recordId;
                        }
                      }
                      
                      <file>
                              <fileDate>2020-12-25</fileDate>
                              <recordCount>2</recordCount>
                              <transactions>
                                  <transaction>
                                      <recordId>45</recordId>
                                  </transaction>
                              </transactions>
                          </file>
                      
                      package com.entities;
                      
                      import javax.xml.bind.annotation.XmlAccessType;
                      import javax.xml.bind.annotation.XmlAccessorType;
                      import javax.xml.bind.annotation.XmlElement;
                      import javax.xml.bind.annotation.XmlElementWrapper;
                      import javax.xml.bind.annotation.XmlRootElement;
                      import javax.xml.bind.annotation.XmlType;
                      import java.util.List;
                      
                      @XmlAccessorType(XmlAccessType.FIELD)
                      @XmlType(name = "", propOrder = {
                          "fileDate",
                          "recordCount",
                          "transactions"
                      })
                      @XmlRootElement(name = "file")
                      public class File {
                        @XmlElement(name = "fileDate", required = true)
                        protected String fileDate;
                        @XmlElement(name = "recordCount", required = true)
                        protected String recordCount;
                      
                        @XmlElementWrapper(name="transactions")
                        @XmlElement(name="transaction")
                        protected List<Transaction> transactions;
                      
                        public String getFileDate() {
                          return fileDate;
                        }
                      
                        public void setFileDate(String fileDate) {
                          this.fileDate = fileDate;
                        }
                      
                        public String getRecordCount() {
                          return recordCount;
                        }
                      
                        public void setRecordCount(String recordCount) {
                          this.recordCount = recordCount;
                        }
                      
                        public List<Transaction> getTransactions() {
                          return transactions;
                        }
                      
                        public void setTransactions(List<Transaction> transactions) {
                          this.transactions = transactions;
                      
                      
                           }
                          }
                      
                      package com.entities;
                      
                      import javax.xml.bind.annotation.XmlAccessType;
                      import javax.xml.bind.annotation.XmlAccessorType;
                      import javax.xml.bind.annotation.XmlElement;
                      import javax.xml.bind.annotation.XmlRootElement;
                      import javax.xml.bind.annotation.XmlType;
                      
                      @XmlAccessorType(XmlAccessType.FIELD)
                      @XmlType(name = "", propOrder = {
                          "recordId"
                      })
                      @XmlRootElement(name = "transaction")
                      public class Transaction {
                        @XmlElement(name = "recordId", required = true)
                        protected String recordId;
                      
                        public String getRecordId() {
                          return recordId;
                        }
                      
                        public void setRecordId(String recordId) {
                          this.recordId = recordId;
                        }
                      }
                      

                      Spring WebClient does not read hypermedia links

                      copy iconCopydownload iconDownload
                      MockResponse mockResponse = new MockResponse()
                                      .addHeader("Content-Type", "application/hal+json") //      <-- hal+json! 
                                      .setBody(new String(personJson.getInputStream().readAllBytes()));
                      

                      Getting an exception when tried to implement Azure AD authentication and authorization in Spring Boot

                      copy iconCopydownload iconDownload
                      @EnableWebSecurity
                      @EnableGlobalMethodSecurity(prePostEnabled = true)
                      @SpringBootApplication
                      public class SpringBootSampleAdApplication extends SpringBootServletInitializer {
                      
                          public static void main(String[] args) {
                              SpringApplication.run(SpringBootSampleAdApplication.class, args);
                          }
                      
                          @Override
                          protected SpringApplicationBuilder configure(SpringApplicationBuilder 
                          application) {
                              return application.sources(SpringBootSampleAdApplication.class);
                          }
                      
                          @Configuration
                          public class DataSourceConfiguration {/*creds*/}
                      }
                      
                      @RestController
                      public class HelloController {
                      
                          @PreAuthorize("hasRole('ROLE_pamela-group1')"+"|| hasRole('ROLE_pamela-group2')")
                          @RequestMapping("/test")
                          public String helloWorld() {
                              return "Hello Users!";
                          }
                      }
                      
                      azure.activedirectory.tenant-id=xxxxx
                      azure.activedirectory.client-id=xxxxx
                      azure.activedirectory.client-secret=xxxxx
                      azure.activedirectory.user-group.allowed-groups=pamela-group1,pamela-group2
                      
                      @EnableWebSecurity
                      @EnableGlobalMethodSecurity(prePostEnabled = true)
                      @SpringBootApplication
                      public class SpringBootSampleAdApplication extends SpringBootServletInitializer {
                      
                          public static void main(String[] args) {
                              SpringApplication.run(SpringBootSampleAdApplication.class, args);
                          }
                      
                          @Override
                          protected SpringApplicationBuilder configure(SpringApplicationBuilder 
                          application) {
                              return application.sources(SpringBootSampleAdApplication.class);
                          }
                      
                          @Configuration
                          public class DataSourceConfiguration {/*creds*/}
                      }
                      
                      @RestController
                      public class HelloController {
                      
                          @PreAuthorize("hasRole('ROLE_pamela-group1')"+"|| hasRole('ROLE_pamela-group2')")
                          @RequestMapping("/test")
                          public String helloWorld() {
                              return "Hello Users!";
                          }
                      }
                      
                      azure.activedirectory.tenant-id=xxxxx
                      azure.activedirectory.client-id=xxxxx
                      azure.activedirectory.client-secret=xxxxx
                      azure.activedirectory.user-group.allowed-groups=pamela-group1,pamela-group2
                      
                      @EnableWebSecurity
                      @EnableGlobalMethodSecurity(prePostEnabled = true)
                      @SpringBootApplication
                      public class SpringBootSampleAdApplication extends SpringBootServletInitializer {
                      
                          public static void main(String[] args) {
                              SpringApplication.run(SpringBootSampleAdApplication.class, args);
                          }
                      
                          @Override
                          protected SpringApplicationBuilder configure(SpringApplicationBuilder 
                          application) {
                              return application.sources(SpringBootSampleAdApplication.class);
                          }
                      
                          @Configuration
                          public class DataSourceConfiguration {/*creds*/}
                      }
                      
                      @RestController
                      public class HelloController {
                      
                          @PreAuthorize("hasRole('ROLE_pamela-group1')"+"|| hasRole('ROLE_pamela-group2')")
                          @RequestMapping("/test")
                          public String helloWorld() {
                              return "Hello Users!";
                          }
                      }
                      
                      azure.activedirectory.tenant-id=xxxxx
                      azure.activedirectory.client-id=xxxxx
                      azure.activedirectory.client-secret=xxxxx
                      azure.activedirectory.user-group.allowed-groups=pamela-group1,pamela-group2
                      
                          <parent>
                              <groupId>org.springframework.boot</groupId>
                              <artifactId>spring-boot-starter-parent</artifactId>
                              <version>2.1.6.RELEASE</version>
                              <relativePath />
                              <!-- lookup parent from repository -->
                          </parent>
                      
                      <dependency>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-oauth2-client</artifactId>
                          <version>2.4.5</version>
                      </dependency>
                      <dependency>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-web</artifactId>
                          <version>2.4.5</version>
                      </dependency>
                      
                      
                          <parent>
                              <groupId>org.springframework.boot</groupId>
                              <artifactId>spring-boot-starter-parent</artifactId>
                              <version>2.1.6.RELEASE</version>
                              <relativePath />
                              <!-- lookup parent from repository -->
                          </parent>
                      
                      <dependency>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-oauth2-client</artifactId>
                          <version>2.4.5</version>
                      </dependency>
                      <dependency>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-web</artifactId>
                          <version>2.4.5</version>
                      </dependency>
                      
                      

                      Migrating from Tomcat to Undertow org.springframework.web.servlet lib issues

                      copy iconCopydownload iconDownload
                        <parent>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-parent</artifactId>
                          <version>2.4.5</version>
                        </parent>
                        ...
                        <dependencies>
                          ...
                          <dependency>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-starter-web</artifactId>
                            <exclusions>
                              <exclusion>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-tomcat</artifactId>
                              </exclusion>
                            </exclusions>
                          </dependency>
                          <dependency>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-starter-undertow</artifactId>
                          </dependency>
                        </dependencies>
                      
                      plugins {
                          id 'org.springframework.boot' version '2.4.5'
                          id 'io.spring.dependency-management' version '1.0.11.RELEASE'
                          ...
                      }
                      
                      dependencies {
                          implementation('org.springframework.boot:spring-boot-starter-web') {
                              exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
                          }
                          implementation 'org.springframework.boot:spring-boot-starter-undertow'
                          ...
                      }
                      
                        <parent>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-parent</artifactId>
                          <version>2.4.5</version>
                        </parent>
                        ...
                        <dependencies>
                          ...
                          <dependency>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-starter-web</artifactId>
                            <exclusions>
                              <exclusion>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-tomcat</artifactId>
                              </exclusion>
                            </exclusions>
                          </dependency>
                          <dependency>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-starter-undertow</artifactId>
                          </dependency>
                        </dependencies>
                      
                      plugins {
                          id 'org.springframework.boot' version '2.4.5'
                          id 'io.spring.dependency-management' version '1.0.11.RELEASE'
                          ...
                      }
                      
                      dependencies {
                          implementation('org.springframework.boot:spring-boot-starter-web') {
                              exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
                          }
                          implementation 'org.springframework.boot:spring-boot-starter-undertow'
                          ...
                      }
                      

                      Spring WebFlux Kotlin OAuth2 CORS

                      copy iconCopydownload iconDownload
                          fun corsConfigurationSource(): CorsConfigurationSource {
                              val cors = CorsConfiguration()
                              cors.allowedOrigins = List.of("*")
                              cors.allowedMethods = List.of("*")
                              cors.allowedHeaders = List.of("*")
                              cors.allowCredentials = true
                              cors.maxAge = 3600L
                              val source = UrlBasedCorsConfigurationSource()
                              source.registerCorsConfiguration("/**", cors)
                              return source
                          }
                      
                          @Bean
                          fun securityFilterChain(
                                  httpSecurity: ServerHttpSecurity
                          ): SecurityWebFilterChain = httpSecurity
                                  .cors(::withConfiguration)
                                  .csrf().disable()
                                  .authorizeExchange()
                                  .pathMatchers("/login", "/register", "/logout").permitAll()
                                  .anyExchange().authenticated()
                                  .and()
                                  .exceptionHandling(::withConfiguration)
                                  .oauth2Login(::withConfiguration)
                                  .logout(::withConfiguration)
                                  .build()
                      
                          fun withConfiguration(spec: ServerHttpSecurity.CorsSpec): Unit =
                                  spec.configurationSource(corsConfigurationSource())
                                          .run { }
                      
                          fun corsConfigurationSource(): CorsConfigurationSource {
                              val cors = CorsConfiguration()
                              cors.allowedOrigins = List.of("*")
                              cors.allowedMethods = List.of("*")
                              cors.allowedHeaders = List.of("*")
                              cors.allowCredentials = true
                              cors.maxAge = 3600L
                              val source = UrlBasedCorsConfigurationSource()
                              source.registerCorsConfiguration("/**", cors)
                              return source
                          }
                      
                          @Bean
                          fun securityFilterChain(
                                  httpSecurity: ServerHttpSecurity
                          ): SecurityWebFilterChain = httpSecurity
                                  .cors(::withConfiguration)
                                  .csrf().disable()
                                  .authorizeExchange()
                                  .pathMatchers("/login", "/register", "/logout").permitAll()
                                  .anyExchange().authenticated()
                                  .and()
                                  .exceptionHandling(::withConfiguration)
                                  .oauth2Login(::withConfiguration)
                                  .logout(::withConfiguration)
                                  .build()
                      
                          fun withConfiguration(spec: ServerHttpSecurity.CorsSpec): Unit =
                                  spec.configurationSource(corsConfigurationSource())
                                          .run { }
                      
                          fun corsConfigurationSource(): CorsConfigurationSource {
                              val cors = CorsConfiguration()
                              cors.allowedOrigins = List.of("*")
                              cors.allowedMethods = List.of("*")
                              cors.allowedHeaders = List.of("*")
                              cors.allowCredentials = true
                              cors.maxAge = 3600L
                              val source = UrlBasedCorsConfigurationSource()
                              source.registerCorsConfiguration("/**", cors)
                              return source
                          }
                      
                          @Bean
                          fun securityFilterChain(
                                  httpSecurity: ServerHttpSecurity
                          ): SecurityWebFilterChain = httpSecurity
                                  .cors(::withConfiguration)
                                  .csrf().disable()
                                  .authorizeExchange()
                                  .pathMatchers("/login", "/register", "/logout").permitAll()
                                  .anyExchange().authenticated()
                                  .and()
                                  .exceptionHandling(::withConfiguration)
                                  .oauth2Login(::withConfiguration)
                                  .logout(::withConfiguration)
                                  .build()
                      
                          fun withConfiguration(spec: ServerHttpSecurity.CorsSpec): Unit =
                                  spec.configurationSource(corsConfigurationSource())
                                          .run { }
                      

                      Spring security OAuth redirect endpoint not found

                      copy iconCopydownload iconDownload
                      @Override
                      protected void configure(HttpSecurity http) throws Exception {
                          http
                              .oauth2Login()
                                  .loginPage("/login/oauth2")
                                  ...
                                  .authorizationEndpoint()
                                      .baseUri("/login/oauth2/authorization")
                                      ....
                      }
                      

                      Community Discussions

                      Trending Discussions on spring-security-oauth2-client
                      • random NullPointerException / onErrorDropped using webClient, due to request.getSession() being null
                      • Spring Security 5 OAuth2 App with Keycloack 17 gets &quot;Connection Refused&quot; when run in Docker container with docker-compose
                      • 500 Internal Server Error in redirect-uri request Webflux + OAuth2.0
                      • Autogenerated OAuth2 login page for AWS Cognito in reactive Spring Boot application fails
                      • Vaadin 21 Flow + Spring Security OAuth2: Couldn't find route for 'oauth2/authorization/google'
                      • NoSuchMethodError after successful Login at Microsoft Azure Active Directory and while redirecting to Spring Boot application
                      • How to avoid KeyLengthException when using Spring OAuth2 Resource Server and a symmetric key
                      • @RequestBody null can't understand why SpringBoot
                      • Upgrading SpringBoot 2.1.4.Relase to 2.5.0 giving NoClassDefFoundError
                      • Postman gives 401 Unauthorized - Spring Boot &amp; MYSQL
                      Trending Discussions on spring-security-oauth2-client

                      QUESTION

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

                      Asked 2022-Mar-07 at 08:34

                      I have a Spring Boot (2.5) application in which I need to make a REST call to a remote system (a Solr instance where I store a denormalized view), in which I can either create or update records.

                      I don't really care about the response I get (and sometimes the remote system is slow to respond), so I am making an async call like this in createIndexForTicket / updateIndexForTicket :

                      public MyService(WebClient webClient, String solrUpdateUrl) {
                          this.webClient = webClient;
                          this.solrUpdateUrl = solrUpdateUrl;
                      }
                      
                        public void createIndexForTicket(TicketIndex ticketIndex) {
                          // build the request
                          var createRequest = webClient.post()
                              .uri(solrUpdateUrl);
                      
                          triggerRequest(createRequest, ticketIndex,"creation");
                      
                          log.info("payload sent, creating index for ticket {} : {}",ticketIndex.getUserFriendlyTicketId(),ticketIndex);
                        }
                      
                        
                        public void updateIndexForTicket(TicketIndex ticketIndex) {
                          // build the request
                          var updateRequest = webClient.put()
                              .uri(solrUpdateUrl + "/" + ticketIndex.getInternalTicketId());
                      
                          triggerRequest(updateRequest, ticketIndex,"update");
                      
                          log.info("payload sent, updating index for ticket {} : {}",ticketIndex.getUserFriendlyTicketId(),ticketIndex);
                        }
                      
                        private static void triggerRequest(RequestBodySpec requestToSolr,
                                                                                       TicketIndex ticketIndex,
                                                                                        String action) {
                      
                          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))
                              .subscribe();
                        }
                      

                      it works fine, most of the times. But I noticed that I sometimes get an Operator called default onErrorDropped error, with below stacktrace :

                      reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.NullPointerException
                      Caused by: java.lang.NullPointerException: null
                          at org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository.saveAuthorizedClient(HttpSessionOAuth2AuthorizedClientRepository.java:63)
                          Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
                      Error has been observed at the following site(s):
                          |_ checkpoint ⇢ Request to PUT https://myRemoteSolrSystem/services/v2/tickets/dGlja2V0aW5nLXNlcnZpY2UxNDEzNzM1 [DefaultWebClient]
                      Stack trace:
                              at org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository.saveAuthorizedClient(HttpSessionOAuth2AuthorizedClientRepository.java:63)
                              at org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository.saveAuthorizedClient(AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java:92)
                              at org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager.lambda$new$0(DefaultOAuth2AuthorizedClientManager.java:126)
                              at org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager.authorize(DefaultOAuth2AuthorizedClientManager.java:184)
                              at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$authorizeClient$24(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:552)
                              at reactor.core.publisher.MonoSupplier.call(MonoSupplier.java:86)
                              at reactor.core.publisher.FluxSubscribeOnCallable$CallableSubscribeOnSubscription.run(FluxSubscribeOnCallable.java:227)
                              at reactor.core.scheduler.SchedulerTask.call(SchedulerTask.java:68)
                              at reactor.core.scheduler.SchedulerTask.call(SchedulerTask.java:28)
                              at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
                              at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
                              at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
                              at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
                              at java.base/java.lang.Thread.run(Thread.java:834)
                      

                      Looking in source code, I find this leads to spring-security-oauth2-client 5.5.1, in HttpSessionOAuth2AuthorizedClientRepository.saveAuthorizedClient

                      @Override
                      public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
                              HttpServletRequest request, HttpServletResponse response) {
                          Assert.notNull(authorizedClient, "authorizedClient cannot be null");
                          Assert.notNull(request, "request cannot be null");
                          Assert.notNull(response, "response cannot be null");
                          Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
                          authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
                          request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
                      }
                      

                      l.63, where the exception happens is the last one :

                      request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
                      

                      So it looks like request.getSession() returns null... but I have no idea why, and I am not able to find a pattern. Sometimes I fire 2 consecutive calls from the same thread, one is successful while the other is not.. sometimes both fail, and sometimes both succeed. Some other time, I trigger only one call and it fails, while another thread does something similar more or less at the same time, and it works.

                      The webClient that gets injected is built like that :

                      @Bean
                      @Primary
                      WebClient servletWebClient(ClientRegistrationRepository clientRegistrations,
                                               OAuth2AuthorizedClientRepository authorizedClients) {
                      
                      var oauth = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
                      
                      oauth.setDefaultClientRegistrationId("keycloak");
                      
                      return WebClient.builder()
                          .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                          .apply(oauth.oauth2Configuration())
                          .build();
                      }
                      

                      Any hint on what I am not doing correctly, or on what I could try to understand better what is going on ?

                      Thanks

                      ANSWER

                      Answered 2022-Mar-07 at 08:34

                      Here's the workaround that seems to work :

                      declare a threadExecutor :

                       private final ExecutorService solrRequestExecutor = Executors.newSingleThreadExecutor();
                      

                      then, make the async call through it :

                      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());
                      }
                      

                      Since this doesn't execute the in the same thread anymore, the webClient has to be configured correctly, otherwise we get a servletRequest cannot be null error. see

                      test a Spring Boot WebClient outside of a HttpServletRequest context

                      I am still not sure why the original code fails randomly though... does it work only if the remote endpoint is also a reactive one ?

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

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

                      Vulnerabilities

                      No vulnerabilities reported

                      Install spring-security-oauth2-client

                      You can download it from GitHub, Maven.
                      You can use spring-security-oauth2-client like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the spring-security-oauth2-client component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      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
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Consider Popular OAuth Libraries
                      Try Top Libraries by pwheel
                      Compare OAuth Libraries with Highest Support
                      Compare OAuth Libraries with Highest Quality
                      Compare OAuth Libraries with Highest Security
                      Compare OAuth Libraries with Permissive License
                      Compare OAuth Libraries with Highest Reuse
                      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
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.