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();
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM