我有一個 Spring/Vuejs 專案,它將前端和后端耦合到一個 warFile 中,由于某種原因,當我運行 warFile 時,我的 Spring Security 設定阻止了 Vue.js 頁面。
當我以這種方式設定配置時,它會阻止頁面 -
@Override
public void configure(HttpSecurity security) throws Exception {
security.csrf().disable()
.cors().and()
.authorizeRequests()
.antMatchers("/api/v1/authenticate", "/api/v1/register").permitAll()
.anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
當我以這種方式設定它時,它會顯示來自我的 api 的頁面和資料(它創建 JWT,但仍然允許未經授權的 api 呼叫) -
@Override
public void configure(HttpSecurity security) throws Exception {
security.csrf().disable()
.cors().and()
.authorizeRequests()
.antMatchers("/api/v1/authenticate", "/api/v1/register", "/**","/css/**","/js/**").permitAll()
.anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
當我以第一種方式設定它并在不同的埠上運行前端和后端時,它可以完美運行。它顯示頁面并阻止沒有授權 JWT 的所有 API 呼叫。
我想要在同一個warFile中與后端/前端相同型別的結果
有解決辦法嗎???
uj5u.com熱心網友回復:
當我以第一種方式設定它并在不同的埠上運行前端和后端時,它可以完美運行。
我想知道這是否是由于呼叫了 CORS 策略。否則,Spring Security 在做出授權決定時不會考慮埠號。
當我以這種方式設定配置時,它會阻止頁面 -
那是因為你有這條線:
.anyRequest().authenticated()
這意味著任何 URL,包括 JS 檔案,都需要身份驗證。
當我以這種方式設定它時,它會顯示頁面和來自我的 api 的資料
那是因為你有這條線:
.antMatchers("/**").permitAll()
這意味著允許任何 URL。
DSL按照宣告路徑的順序處理 URL 。我想你想要兩者的混合體。像這樣的東西:
.antMatchers("/api/v1/authenticate", "/api/v1/register", "/css/**","/js/**").permitAll()
.anyRequest().authenticated()
這意味著兩個/api端點所有/css端點和所有/js端點都不需要身份驗證,但其他一切都需要。
考慮permitAll盡可能縮小范圍——我不清楚您是否真的希望所有 JS 檔案都不需要身份驗證。
uj5u.com熱心網友回復:
@jzheaux 你的根評論讓我找到了答案。
這是我所做的改變,它就像我現在需要的那樣作業。謝謝指導!
@Override
public void configure(HttpSecurity security) throws Exception {
security.csrf().disable()
.cors().and()
.authorizeRequests()
.antMatchers("/api/v1/authenticate","/api/v1/register","/static/**","/").permitAll()
.anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411841.html
標籤:
