Hantsy
Hantsy

Reputation: 9311

authorizationGrantType cannot be null in Spring Security 5 OAuth Client and Spring Boot 2.0

I followed the Spring Security 5.0 official reference documentation and sample codes oauth2login to setup OAuth2/OIDC authentication in my project, but it failed and I got the following exception when I booted up my application by mvn spring-boot:run.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' 
    defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.class]: 
    Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: 
    Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: 
    Factory method 'clientRegistrationRepository' threw exception; 
    nested exception is java.lang.IllegalArgumentException: authorizationGrantType cannot be null

I was using the default configuration provided by Spring Boot and just added some basic dependencies into projects, such as spring-security-config, spring-security-oauth2-client, spring-security-oauth2-jsoe etc.

Updated:

I've found the reason, for custom OAuth2 providers, such as Gitlab, I have to add grant type, redirectUritemplate, scope, clientName etc, but OpenID Connect specification has a configuration endpoint protocol, eg: https://gitlab.com/.well-known/openid-configuration , is there possible to make Spring Security read this info automatically?

Update(5/15/2021): in the latest Spring Security 5.4 and Spring Boot 2.4, the OpenId configuration(.well-known/openid-configuration) is discovered by default, for most oauth2/oidc authorization servers, configure a issuer_uri is enough.

Upvotes: 12

Views: 23598

Answers (5)

Nestor Milyaev
Nestor Milyaev

Reputation: 6595

I had to add the following property to my application.properties:

spring.security.oauth2.client.registration.azure.authorization_grant_type=authorization_code

After which it started complaining that "Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'oidcUserService'"

At which point I had to add the following to the WebSecurityConfig:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.headers()
        .httpStrictTransportSecurity()
        .includeSubDomains(includeSubDomains)
        .maxAgeInSeconds(31536000);
    http.requestCache()
        .requestCache(new NullRequestCache())
        .and()
        .authorizeRequests()
        .antMatchers("Our permitted end points")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .oauth2Login()
        .userInfoEndpoint()
        .oidcUserService(oidcUserService());
  }

  private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
    final OidcUserService delegate = new OidcUserService();

    return userRequest -> {
      OidcUser oidcUser = delegate.loadUser(userRequest);

      Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

      oidcUser =
          new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());

      return oidcUser;
    };
  }

Then is started working... Reference: https://docs.spring.io/spring-security/site/docs/5.2.12.RELEASE/reference/html/oauth2.html

Upvotes: 0

Stewart Adam
Stewart Adam

Reputation: 343

To elaborate on Arpeet's answer, the properties you need to include in your application.yaml to resolve the original error are as shown below, in this case for Azure AD (note this ONLY works with Spring Security 5, NOT Spring Security OAuth2 2.x whose functionality is being merged directly into Spring Security 5):

spring:
  security:
    oauth2:
      client:
        registration:
          microsoft:
            client-id: a935ba7b-6aa4-4b0c-9e84-04f9acaa477b
            client-secret: redacted
            authorization-grant-type: authorization_code
            redirect-uri-template: '{baseUrl}/login/oauth2/code/{registrationId}'
            scope: User.Read
            client-name: Microsoft
            client-alias: microsoft
        provider:
          microsoft:
            authorization-uri: https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/
            token-uri: https://login.microsoftonline.com/common/oauth2/token
            user-info-uri: https://graph.microsoft.com/v1.0/me
            user-name-attribute: sub
            jwk-set-uri: https://login.microsoftonline.com/common/discovery/keys

Upvotes: 17

SurajB
SurajB

Reputation: 9

    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.4.5</version>
    </dependency>

Add this dependency in your pom and check

Upvotes: -1

Arpeet
Arpeet

Reputation: 221

use redirect-uri instead of redirect-uri-template if use SpringBoot v2.2.1 RELEASE

Upvotes: 21

SangHyouk Jin
SangHyouk Jin

Reputation: 61

redirect-uri-template -> redirect-uri it works SpringBoot 2.2.0.RELEASE

but it works spring 2.1.x with redirect-uri-template

Upvotes: 6

Related Questions