[英]Spring Security - doesn't access database
我使用的是Spring Boot,並且是Spring Security的新手,但是我想要Web應用程序的基本安全性。 我所做的就是在pom.xml中添加所需的依賴項,並將此java類添加到我的項目中:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**","/event/**","/ticket/**")
.hasRole("USER")
.and()
.formLogin();
}
}
運行我的Web應用程序后,我進入登錄頁面,在其中輸入用戶名/密碼,然后轉到我的Web應用程序。 但是,這些命令不起作用。 我按了一些應該向MySql數據庫發送信號的按鈕,但是什么也沒有發生。 就像前端不再連接到后端一樣。 我正在使用AngularJS作為前端,以及在頁面之間導航的View Controller。 該應用程序的其余部分基於REST。 知道為什么會發生這種情況嗎?
稍后編輯:現在,我明白了,我遇到的問題是,在進行身份驗證之后,我在端點上獲得了403狀態代碼。 知道我該如何解決嗎?
以后的Editv2:看起來我未獲得POST請求的授權,我的GET請求工作正常...這是我的一些POST端點:/ event / buy_ticket / {id},/ ticket // cancel_ticket / { ID}
angular.min.js:101 POST http://localhost:8080/event/buy_ticket/2 403 ()
我什至試圖明確地說出它允許它,但我仍然得到403 ...
http.authorizeRequests()
.antMatchers("/**","/event/**","/ticket/**","/event/buy_ticket/2")
.permitAll()
.and()
.formLogin();
以后以后以后編輯:
禁用CSRF工作
得到403 Forbidden錯誤代碼意味着Spring正在接收您的請求,但選擇停止處理它們。 在HTTP 403的Wiki頁面上:
提供了身份驗證,但是不允許經過身份驗證的用戶執行請求的操作。
如果不得不下注,我會說問題是您尚未指定應訪問哪些資源和端點以及如何訪問。 如果內存適合我,那么默認情況下,Spring Security會非常緊密地鎖定所有內容,因此您需要明確告訴它保持打開狀態。 以下是我自己的安全配置的示例:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // require authorization
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // for the CORS preflight check
.antMatchers("/login", "/api/open/**", "/resources/**").permitAll() // the open API endpoints and resources
.antMatchers("/logout", "/api/secured/**").authenticated(); // lock down these endpoints
...additional configurations...
}
應該自由可用的所有端點都以"/api/open/"
開頭,而應該由Spring Security保護的所有端點都以"/api/secured/"
開頭。 登出和登錄端點是例外,因為它們直接綁定到Spring Security。
這是一篇很棒的博客文章 -及其相關的倉庫 -展示了如何實現與AngularJS配合使用的Spring Security,甚至作為單頁應用程序也是如此,這是眾所周知的煩人的安全方法。
編輯:您可能正在使用CSRF保護,該保護在Spring Security中默認啟用-請參閱此文章 。 CSRF將允許HTTP“安全”方法(例如GET,HEAD和OPTION),但會阻止“不安全”方法(例如PUT,POST,DELETE等),如果這些方法未提供正確的令牌(由於未配置CSRF,則這些請求不會擁有令牌->被阻止)。 為了進行測試,您可以通過將http.csrf().disable()
到configure()
方法中來禁用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.