[英]How do I get my user_id from the authorised client
我想檢索當前在線的用戶的ID。 但是我不能用以下代碼來做到這一點:
Route::middleware('auth:api')->post('/optionelections', function (Request $request) {
return $request->user();
});
原因是我不斷從Laravel收到相同的未經授權的錯誤。 我一直在嘗試修復此錯誤數天,但似乎找不到解決方案。 所以我正在嘗試以不同的方式來做,但是我不知道怎么做。 我目前正在使用Passport將令牌和client_id
存儲在本地存儲中。
這是我的apply_election.vue
import {apiDomain} from '../../config'
export default {
name: 'applyForElection',
data () {
return {
election: {},
newOption: {'election_id': ''},
//this is where the user_id should come
newOption: {'user_id': ''}
}
},
methods: {
createOption: function () {
var itemId = this.$route.params.id
this.newOption.election_id = itemId
this.$http.post(apiDomain + 'optionelections', this.newOption)
.then((response) => {
this.newOption = {'election_id': itemId}
alert('you applied!')
this.$router.push('/electionsnotstarted')
}).catch(e => {
console.log(e)
alert('there was an error')
this.$router.push('/electionsnotstarted')
})
}
},
created: function () {
var itemId = this.$route.params.id
this.$http.get('http://www.nmdad2-05-elector.local/api/v1/elections/' + itemId)
.then(function (response) {
this.election = response.data
})
}
}
而這在我的OptionElectionsController.php
public function store(Request $request)
{
$optionElection = new OptionElection();
$optionElection->user_id = $request['user_id'];
$optionElection->option = "something";
$optionElection->votes = 0;
$optionElection->election_id = $request['election_id'];
$optionElection->accepted = 0;
if ($optionElection->save()) {
return response()
->json($optionElection);
}
}
這是我的Auth.js
export default function (Vue) {
Vue.auth = {
setToken (token, expiration) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
},
getToken () {
var token = localStorage.getItem('token')
var expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
} else {
return token
}
},
destroyToken () {
localStorage.removeItem('token')
localStorage.removeItem('expiration')
},
isAuthenticated () {
if (this.getToken()) {
return true
} else {
return false
}
}
}
Object.defineProperties(Vue.prototype, {
$auth: {
get: () => {
return Vue.auth
}
}
})
}
您正在使用TokenGuard
的TokenGuard,有多種方法可以讓防護人員識別身份驗證和最佳方法:
在請求的查詢中在api_token
屬性中發送令牌。
this.newOption.api_token = token;
在帶有Bearer
前綴的Authorization
標頭中發送令牌。
{ headers: { Authorization: 'Bearer THE_TOKEN' } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.