spring cloud oauth2(五) 白名单设置

  • 新建IgnorenPath类 ,从配置文件中获取需要放行的白名单
package com.Lonni.resource.model;

import com.google.common.collect.Sets;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Set;

/**
 * 放行不需要拦截的资源
 * @author lonni
 * @Description: TODO
 * @date 2020/11/2016:41
 */
@Configuration
@ConfigurationProperties(prefix = "lonni.resource")
public class IgnorenPath {

    private static Set<String> igpath = Sets.newHashSet();

    public IgnorenPath() {
        igpath.add("/feign/**");
        igpath.add("/doc.html");
        igpath.add("/webjars/**");
        igpath.add("/api-docs-ext");
        igpath.add("/api-docs");
        igpath.add("/swagger-ui.html");
        igpath.add("/swagger-resources/**");
        igpath.add("/actuator/**");
        igpath.add("/v2/**");
        igpath.add("/css/**");
        igpath.add("/js/**");
        igpath.add("/images/**");
        igpath.add("/favicon.ico");
        igpath.add("/service-worker.js");
    }

    private String id;
    private List<String> ignoredPath;

    private String[] allIgnoredPath;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<String> getIgnoredPath() {
        return ignoredPath;
    }

    public void setIgnoredPath(List<String> ignoredPath) {
        this.ignoredPath = ignoredPath;
    }

    public String[] getAllIgnoredPath() {
        System.out.println("执行getAllIgnoredPath.....");
        if (this.ignoredPath != null && !this.ignoredPath.isEmpty()) {
            this.ignoredPath.forEach(p->{
                igpath.add(p);
            });
        }
        return igpath.toArray(new String[igpath.size()]);
    }

    public void setAllIgnoredPath(String[] allIgnoredPath) {

    }
}
  • 在ResourceServiceConfig中注入,并在 configure(HttpSecurity http) 配置
 @Autowired
    IgnorenPath ignorenPath;
  

/**
     * 配置资源服务需要拦截的请求 可以在这里增加白名单配置
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] allIgnoredPath = ignorenPath.getAllIgnoredPath();

        http.authorizeRequests().
                //设置白名单 其他全部都需要权限访问
             antMatchers(allIgnoredPath)
                .permitAll()
        .anyRequest().authenticated();
    }
原文地址:https://www.cnblogs.com/HiLzd/p/14367894.html