[英]Client-side cookie-based authentication with Spring Security
我們擁有一個可以正常使用的后端登錄POST服務,該服務使用Spring Security以及Spring Boot和Spring Session來實現。 用戶需要登錄才能訪問其他服務。 登錄操作有效,限制/允許訪問其他服務的機制也有效。 這已經用Postman進行了測試,它足夠“聰明”,可以在后續請求中保留會話cookie。
現在,我們正在嘗試在React上構建客戶端。 使用瀏覽器的調試時,我們可以看到會話cookie在響應頭中發送,沒有問題。 我們試圖從標頭中獲取會話cookie並將其存儲為后續請求,但它不起作用。 在調查中,我們了解到, 我們並不是要從代碼中讀取響應標頭 ,如此處和此處所述 。
我們的登錄操作應重定向到/ customer / home,它在Postman中有效,但不適用於我們的應用程序。 我們得到的行為是403禁止,並且我們評估它的方式是因為重定向時未設置cookie,因此第二個操作(GET / customer / home)失敗並返回403。我們的理解正確嗎? 但是,瀏覽器似乎並沒有自動保留會話cookie。 如果未自動設置cookie,並且不應該手動讀取它,我們應該如何維護后續請求的會話? 我們是否不應該為此目的使用cookie,而是發出身份驗證令牌?
我們顯然是誤會或遺漏了一些東西。 有指針嗎?
我們的WebSecurityConfigurerAdapter:
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationProviderService authenticationProviderService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/customer/register").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.permitAll()
.defaultSuccessUrl("/customer/home", false)
.and()
.logout()
.permitAll()
.and()
.httpBasic();
http.csrf().disable();
}
//[ . . . ]
}
我們的客戶嘗試執行POST:
const mw = store => next => action => {
if(action.type == 'SUBMIT_LOGIN_USER') {
var payload = {
username: action.user.username,
password: action.user.password
};
// Build formData object.
let formData = new FormData();
formData.append('username', action.user.username);
formData.append('password', action.user.password);
return fetch('http://192.168.0.34:8080/login', {
method: 'POST',
body: formData
}).then(
r => (r)
)
.then(function(response) {
console.log(document.cookie) //empty
console.log(response.headers.get('Set-Cookie')) //null
next(action)
})
.catch(function(err) {
console.info(err);
});
} else {
next(action)
}
}
使用JWT(Jason Web令牌)是在像React這樣的單頁應用程序上實現安全性的好方法。
如果您要使用JWT方法,則使用axios之類的包來接收來自客戶端的http請求將非常有效。 Axios允許您輕松地向所有請求添加授權令牌,而無需麻煩。
即使您沒有使用JWT,也請嘗試使用axios有效地發送授權令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.