蚂蚁模式配置



我有这个Spring配置和OAuth2:

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";
    private static final String PUBLIC_PATTERN = "/api/*/public/**";
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                    .anonymous()
                .and()
                    .requestMatchers()
                        .antMatchers(SECURED_PATTERN)
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
                .anyRequest().access(SECURED_READ_SCOPE);
    }
}

现在我想将 Swagger 添加到我的项目中。我配置了一个 SwaggerController:

@Controller //note - this is a spring-boot controller, not @RestController
public class SwaggerController {
    public static final String SWAGGER_URL = "/api/v1/public/swagger/docs";
    public static final String SWAGGER_HTML = "/swagger-ui.html";
    @RequestMapping(SWAGGER_URL)
    public String home() {
        return "redirect:" + SWAGGER_HTML;
    }
}

问题是我无法使"/swagger-ui.html"路径不触发 Spring 登录。我试过这个(请注意,我为 Swagger html 添加了 antMatchers(:

@Override
    public void configure(HttpSecurity http) throws Exception {
        http
                ...
                .and().authorizeRequests()
                        .antMatchers(PUBLIC_PATTERN).permitAll()
                        .antMatchers("/swagger-ui.htm").permitAll()// No authentication

。 }

但它没有奏效。我需要如何配置HTTP安全?

所以招摇的主页应该重定向到/swagger-ui.html

如果是,则在配置 HttpSecurity 时有一个拼写错误,您只键入 htm。所以改为:

 .antMatchers("/swagger-ui.html").permitAll()

另一方面,如果招摇的主页是/swagger-ui.htm。然后将控制器中的SWAGGER_HTML更改为:

 public static final String SWAGGER_HTML = "/swagger-ui.htm";

添加此覆盖:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(SWAGGER_URL)
            .antMatchers(SWAGGER_HTML);
}

最新更新