Cannot send Authorization Bearer Token using Springfox

后端 未结 7 857
无人及你
无人及你 2021-02-08 05:59

I\'m having trouble understanding why \"Authorization: Bearer __\" is not being sent in my api using Springfox 2.5.0. I have the following configuration:

private         


        
7条回答
  •  我寻月下人不归
    2021-02-08 06:26

    The solution that worked for me with swagger versión 2.9.2 is the following:

    package com.example.springsocial;
    
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.core.annotation.AuthenticationPrincipal;
    import com.google.common.base.Predicates;
    import com.google.common.collect.Lists;
    
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiKey;
    import springfox.documentation.service.AuthorizationScope;
    import springfox.documentation.service.SecurityReference;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfiguration   {
    
        @Bean
        public Docket docket() {
            return new Docket(DocumentationType.SWAGGER_2)
                        .ignoredParameterTypes(AuthenticationPrincipal.class)
                        .select()
                        .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                        .paths(PathSelectors.any()).build()
                        .securitySchemes(Lists.newArrayList(apiKey()))
                        .securityContexts(Arrays.asList(securityContext()));
    
        }
    
        private ApiKey apiKey() {
            return new ApiKey("apiKey", "Authorization", "header");
        }
    
        private SecurityContext securityContext() {
            return SecurityContext.builder().securityReferences(defaultAuth())
                .forPaths(PathSelectors.any()).build();
        }
    
        private List defaultAuth() {
            AuthorizationScope authorizationScope = new AuthorizationScope(
                "global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            return Arrays.asList(new SecurityReference("apiKey",
                authorizationScopes));
            }
    }
    

    POM.XML

    
            
                io.springfox
                springfox-swagger2
                2.9.2
            
            
                io.springfox
                springfox-swagger-ui
                2.9.2
            
            
                io.springfox
                springfox-bean-validators
                2.9.2
            
    

    SecurityConfig.JAVA

    package com.example.springsocial.config;
    
    import com.example.springsocial.security.*;
    import com.example.springsocial.security.oauth2.CustomOAuth2UserService;
    import com.example.springsocial.security.oauth2.HttpCookieOAuth2AuthorizationRequestRepository;
    import com.example.springsocial.security.oauth2.OAuth2AuthenticationFailureHandler;
    import com.example.springsocial.security.oauth2.OAuth2AuthenticationSuccessHandler;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.BeanIds;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(
            securedEnabled = true,
            jsr250Enabled = true,
            prePostEnabled = true
    )
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private CustomUserDetailsService customUserDetailsService;
    
        @Autowired
        private CustomOAuth2UserService customOAuth2UserService;
    
        @Autowired
        private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;
    
        @Autowired
        private OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler;
    
        @Autowired
        private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;
    
        @Bean
        public TokenAuthenticationFilter tokenAuthenticationFilter() {
            return new TokenAuthenticationFilter();
        }
    
        /*
          By default, Spring OAuth2 uses HttpSessionOAuth2AuthorizationRequestRepository to save
          the authorization request. But, since our service is stateless, we can't save it in
          the session. We'll save the request in a Base64 encoded cookie instead.
        */
        @Bean
        public HttpCookieOAuth2AuthorizationRequestRepository cookieAuthorizationRequestRepository() {
            return new HttpCookieOAuth2AuthorizationRequestRepository();
        }
    
        @Override
        public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
            authenticationManagerBuilder
                    .userDetailsService(customUserDetailsService)
                    .passwordEncoder(passwordEncoder());
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
    
        @Bean(BeanIds.AUTHENTICATION_MANAGER)
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .cors()
                        .and()
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and()
                    .csrf()
                        .disable()
                    .formLogin()
                        .disable()
                    .httpBasic()
                        .disable()
                    .exceptionHandling()
                        .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                        .and()
                    .authorizeRequests()
                        .antMatchers("/",
                            "/error",
                            "/favicon.ico",
                            "/**/*.png",
                            "/**/*.gif",
                            "/**/*.svg",
                            "/**/*.jpg",
                            "/**/*.html",
                            "/**/*.css",
                            "/**/*.js",
                            // swagger
                            "/swagger-ui.html**", "/swagger-resources/**",
                            "/v2/api-docs**", "/webjars/**"
                             )
                            .permitAll()
                        .antMatchers("/auth/**", "/oauth2/**")
                            .permitAll()
                        .anyRequest()
                            .authenticated()
                        .and()
                    .oauth2Login()
                        .authorizationEndpoint()
                            .baseUri("/oauth2/authorize")
                            .authorizationRequestRepository(cookieAuthorizationRequestRepository())
                            .and()
                        .redirectionEndpoint()
                            .baseUri("/oauth2/callback/*")
                            .and()
                        .userInfoEndpoint()
                            .userService(customOAuth2UserService)
                            .and()
                        .successHandler(oAuth2AuthenticationSuccessHandler)
                        .failureHandler(oAuth2AuthenticationFailureHandler);
    
            // Add our custom Token based authentication filter
            http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/common/**", "/v2/api-docs", "/configuration/ui", "/swagger-resources",
                    "/configuration/security", "/swagger-ui.html", "/webjars/**");
        }
    
    }
    

提交回复
热议问题