瀏覽器出于安全的考慮,使用 XMLHttpRequest對象發(fā)起 HTTP請求時必須遵守同源策略,否則就是跨
域的HTTP請求,默認(rèn)情況下是被禁止的。 同源策略要求源相同才能正常進(jìn)行通信,即協(xié)議、域名、端口號都完全一致。
前后端分離項目,前端項目和后端項目一般都不是同源的,所以肯定會存在跨域請求的問題。
所以我們就要處理一下,讓前端能進(jìn)行跨域請求。
一、SpringBoot配置
配置運行跨域請求
二、配置SpringSecurity
②開啟SpringSecurity的跨域訪問
由于我們的資源都會收到SpringSecurity的保護(hù),所以想要跨域訪問還要讓SpringSecurity運行跨域訪問。
三、修改端口
四、修改vue項目
vue項目:
阿里云盤:
文件太多了,百度網(wǎng)盤傳不上,用阿里云盤,嗯。2萬多個文件
https://www.alipan.com/t/la1A8NRdoGJjipuJwrZU
用postman是肯定不存在跨域問題的。因為它不是瀏覽器,所以我們要找一個前端的項目,就隨便找了一個vue工程。修改一下vue項目。
4.1 拿到token
創(chuàng)建一個登錄頁面
代碼如下:
<template>
<el-form style="width: 20%" :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="賬號" prop="userName">
<el-input v-model="ruleForm.userName"></el-input>
</el-form-item>
<el-form-item label="密碼" prop="password">
<el-input v-model="ruleForm.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
ruleForm: {
userName: '',
password: ''
}
};
},
methods: {
//這個是提交方法
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
axios.post('http://localhost:8888/user/login',this.ruleForm).then(res=>{
console.log(res.data.data.token);
if(res.data.code == '200'){
this.$alert(this.ruleForm.userName+'賬號登錄成功!', '消息', {
confirmButtonText: '確定',
})
}
})
} else {
return false;
}
});
}
}
}
</script>
<style scoped>
</style>
路由的配置就直接略過了,不是重點。。。。。
運行前端vue項目:
然后測試一下,登錄成功,解決跨域請求,拿到token
4.2 前端存儲token
修改一下登錄頁面,認(rèn)證登錄成功之后,把返回的token接收,存入localStorage
測試一下:沒有問題,本地存儲了token
4.3 前端請求頭攜帶token
先創(chuàng)建一個hello頁面
代碼如下:
<template>
<el-form style="width: 20%" label-width="100px" class="demo-ruleForm">
<el-form-item>
<el-button type="primary" @click="submitForm()">測試hallo接口</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
methods: {
//這個是提交方法
submitForm() {
axios.post('http://localhost:8888/hello',this.ruleForm).then(res=>{
})
}
}
}
</script>
<style scoped>
</style>
啟動項目,頁面測試一下:
認(rèn)證失敗,因為請求頭沒有攜帶任何token
創(chuàng)建一個utils文件夾,在utils下創(chuàng)建request.js
在main.js進(jìn)行全局引入
修改hello接口,只需要寫一個hello就行了,不需要寫全部的接口地址
五、測試
5.1 認(rèn)證測試
填一個錯誤的密碼,認(rèn)證失敗
填入一個正確的密碼,認(rèn)證成功
5.2 授權(quán)測試
然后,我們測試一下,請求頭已經(jīng)攜帶了token了
然后看一下,響應(yīng),都沒有問題,OK,這個賬號是有這個權(quán)限的。
我們把權(quán)限改了
再進(jìn)行一下測試:當(dāng)前賬號已經(jīng)沒有權(quán)限了。文章來源:http://www.zghlxwxcb.cn/news/detail-851858.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-851858.html
一鍵三連有沒有捏~~
到了這里,關(guān)于Spring Security——09,解決跨域的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!