Spring-безопасность: OAuth2User NullPointerException - PullRequest
0 голосов
/ 03 августа 2020

Итак, я попытался использовать spring-boot-starter-oauth2-client для аутентификации моего приложения. И когда я попытался вызвать службу и использовать Oauth2User, у меня возникло исключение NullpointerException.

Test: Call service http://localhost/user приводит к NullPointer на principal.getName()

 @SuppressWarnings("deprecation")
    @RestController
    public class UserController {
        private Logger log = LoggerFactory.getLogger(UserRESTController.class);
         @PreAuthorize("isAuthenticated()")
@GetMapping("/user")
         public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
             return Collections.singletonMap("name", principal.getName()); // NullPoointer on Principal
         }
    }

    public class Application extends WebSecurityConfigurerAdapter {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors();
            http.csrf().disable();
    
            http.authorizeRequests(a -> a
                        .antMatchers("/","/index.html", "/error", "/webjars/**", "/oauth2/**", "/login/**", "/actuator/**")
                        .permitAll()
                        // Other calls secured
                        .antMatchers("/**")
                        .permitAll()
                        .anyRequest().authenticated()
                ).exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                ).csrf(c -> c.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
                .logout(l -> l.logoutSuccessUrl("/").permitAll())
                .oauth2Login(
                        o -> o.failureHandler(new CustomAuthenticationFailureHandler()).defaultSuccessUrl("/", true));
    }

application.yml

service:
      basepath: https://vcdcdcdc.execute-api.eu-west-1.amazonaws.com
      ping:
        url: /
    management:
      endpoints:
        enabled-by-default: false
      endpoint:
        health:
          enabled: true
          show-details: always 
          show-components: always    
        web:
          exposure:
            include: health, info
        jmx:
          exposure:
            exclude: "*"
    spring:
      security:
        oauth2:
          client:
            registration:
              cognito:
                client-id: azrifheifhefieheifhefieh
                client-secret: fefefgefebfjoefefoeifonxkhidhziddizhdz
                client-name: app-angular
                provider: cognito
                scope: openid
                redirect-uri: http://localhost:8080/login/oauth2/code/cognito
                authorization-grant-type: authorization_code
            provider:
              cognito:
                authorization-uri: https://app-angular.auth.eu-west-1.amazoncognito.com/oauth2/authorize
                token-uri:https://app-angular.auth.eu-west-1.amazoncognito.com/oauth2/token
                user-info-uri: https://app-angular.auth.eu-west-1.amazoncognito.com/oauth2/userInfo
                jwk-set-uri: https://app-angular.amazonaws.com/eu-west-1_wTGqKx2Sa/.well-known/jwks.json
                user-name-attribute: cognito:username


@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * Allow access to all authenticated tokens
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    /**
     * Auto-approve for users logged in with registered client
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("azrifheifhefieheifhefieh")
                .secret("fefefgefebfjoefefoeifonxkhidhziddizhdz")
                .scopes("openid", "eu.europarl.MyAPI/my.api").autoApprove(true);
    }
}
...