簡體   English   中英

Spring REST Security:僅在特定端點上啟用基本身份驗證

[英]Spring REST Security : Enable Basic Authentication only on a specific endpoint

我已經為我的REST API配置了Spring Security(使用HeaderHttpSessionStrategy)。

我的'WebSecurityConfigurerAdapter'實現如下所示。

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http

            .csrf().disable()

            .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/**").permitAll()

                .and()
            .requestCache()
                .requestCache(new NullRequestCache())
                .and()

            .httpBasic()
            ;

    }

現在,我如何配置'HttpSecurity'對象,以便只有特定端點才能進行基本身份驗證。

例如:

/ user / login :只能在此端點進行基本身份驗證。在進行成功身份驗證后,將返回x-auth-token標頭。

/ user / create :客戶端不應該能夠在此端點上進行身份驗證。只能返回401.Can只能使用/ user / login端口創建的“x-auth-token”訪問。

您可以定義多個WebSecurityConfigurerAdapter 具有請求匹配器以限制對/user/login適用性的優先級之一,例如: http.requestMatcher(new AntPathRequestMatcher("/user/login")) ,另一個作為其余的全部。 您可以省略requestMatcher以使http定義不受限制。

您必須始終定義從特定到通用的限制。 在您的情況下,它應該是對通用安全檢查的特定URL檢查。

  1. 您應該配置並允許登錄/注冊URL。
  2. 你應該避免使用pattern / **來允許所有人。 而是分別配置靜態資源URL。
  3. 您應該最終應用更多通用限制,例如您在URL,/ user / **上提到的要進行身份驗證並具有某些角色的限制。

      @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/user/login, /user/signup, /logout").permitAll() .antMatchers("/user/**").hasRole("ADMIN") .and() .requestCache() .requestCache(new NullRequestCache()) .and() .httpBasic(); 

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM