spring-security (401)无法找到页面(401)返回首页

siotufzp  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(170)

Swagger OpenAPI 3.0正在使用springdoc-openapi-ui和一个自定义的OpenAPI Bean。

pom.xml

<parent>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-parent</artifactId>
  <version>Hoxton.SR10</version>
</parent>
...
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.5.5</version>
</dependency>

摆动配置:

相同配置的spring-security的问题

我们面临着一个问题,当使用springdoc-openapi-ui,springdoc-openapi-security与spring-boot-starter-security和keycloak-spring-boot-starter一起使用时。
pom.xml

<dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-security</artifactId>
      <version>1.5.5</version>
</dependency>
<dependency>
      <groupId>org.keycloak</groupId>
      <artifactId>keycloak-spring-boot-starter</artifactId>
      <version>12.0.2</version>
</dependency>
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
      <version>2.4.2</version>
</dependency>

DummySecurityConfig(当前正在使用配置文件设备):

@Profile({"test", "dev"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true,
        securedEnabled = true,
        jsr250Enabled = true)
@EnableWebMvc
public class DummySecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    protected static final String[] ACTUATOR_WHITELIST = {
        "/actuator/**"
    };

    protected static final String[] SWAGGER_WHITELIST = {
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui.html",
    };

    @Value("${client.cors.allowed-origins:*}")
    private String[] allowedOrigins;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic(); //or anything else, e.g. .oauth2ResourceServer().jwt()
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers(SWAGGER_WHITELIST)
                .antMatchers(ACTUATOR_WHITELIST);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins);
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        AuthenticationProvider authenticationProvider = new AuthenticationProvider() {
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + authentication.getPrincipal().toString().toUpperCase());

                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                        authentication.getPrincipal(), authentication.getCredentials(), Collections.singleton(authority));
                token.setDetails(authentication);
                return token;
            }

            @Override
            public boolean supports(Class<?> aClass) {
                return true;
            }
        };

        return authenticationProvider;
    }
}

SecurityConfig(示例中未使用,但将来也会使用):

@Profile({"staging", "devstaging"})
@KeycloakConfiguration
@EnableGlobalMethodSecurity(
    prePostEnabled = true,
    securedEnabled = true,
    jsr250Enabled = true)
@EnableWebMvc
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter implements WebMvcConfigurer {

    protected static final String[] ACTUATOR_WHITELIST = {
        "/actuator/**"
    };

    protected static final String[] SWAGGER_WHITELIST = {
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui.html",
    };

    @Value("${client.cors.allowed-origins:*}")
    private String[] allowedOrigins;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
        grantedAuthorityMapper.setConvertToUpperCase(true);
        grantedAuthorityMapper.setPrefix("ROLE_");

        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(SWAGGER_WHITELIST)
            .antMatchers(ACTUATOR_WHITELIST);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
            .csrf().disable()
            .cors().and()
            .authorizeRequests().anyRequest().authenticated();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins(allowedOrigins);
    }
}

application-dev.yml:

server:
  port: 8083
  servlet:
    context-path: /planning
keycloak:
  enabled: false
springdoc:
  show-actuator: true

我们已经尝试使用以下链接来解决此问题:

打开swagger-ui URL(配置文件开发)的示例:

(不起作用):

应用程序的程式码片段:

2021-03-05 09:27:01,530 [http-nio-8083-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/planning] threw exception [Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config' in servlet with name 'dispatcherServlet'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config' in servlet with name 'dispatcherServlet'
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1138)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1077)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)

(可以正常工作,但比较复杂):

(也可以手动添加api-docs“/planning/v3/api-docs”):

你有什么想法,还有什么可能是错误的配置或我们应该改变什么?我们在我们的拉丁语结束。

nnt7mjpx

nnt7mjpx1#

如日志所示,Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=**/planning/v3/api-docs/swagger-config'**。在您的Web安全配置中,您仅给予对/v3/api-docs/**的访问权限。请尝试添加/planning/**或修改路径。

相关问题