我有一个针对laravel的Rest and Vue SPA教程Tutorial here for reference
,并通过laravel实现了半工作JWT-auth如果我在本地运行php artisan serve
并访问我的浏览器localhost:8000/
,则注册和登录方法可以正常工作-即使我上载app.js文件,这也可以在实时服务器上运行。如果我尝试使用localhost:8000/
进行注册,也可以。当我尝试从本地主机登录并连接到服务器以获取授权时,就会出现问题。
控制台输出
XHR POST https://test.mydomain.co.uk/api/auth/login?email=test@email.com&password=password [HTTP/1.1 200 OK 391ms]
XHR GET https://test.mydomain.co.uk/api/auth/user [HTTP/1.1 400 Bad Request 121ms]
对于本地来说都是本地的,对于服务器来说都是本地的,但是对于服务器来说不是本地的
除非有要求,否则我不会将工作控制台的输出放在这里。
/routes/api.php
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('auth/register', 'AuthController@register');
Route::post('auth/login', 'AuthController@login');
Route::group(['middleware' => 'jwt.auth'], function(){
Route::get('auth/user', 'AuthController@user');
Route::post('auth/logout', 'AuthController@logout');
});
Route::group(['middleware' => 'jwt.refresh'], function(){
Route::get('auth/refresh', 'AuthController@refresh');
});
/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\RegisterFormRequest;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use JWTAuth;
use Log;
class AuthController extends Controller
{
/*
*/
private function generateVerification($name, $username) {
return md5( $name.substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"), 0, 9).$username );
}
public function register(RegisterFormRequest $request){
$user = new User;
$user->email = $request->email;
$user->name = $request->name;
$user->password = bcrypt($request->password);
if(!$request->signupcode) {
$user->registration_voucher = '0';
} else {
$user->registration_voucher = $request->signupcode;
}
$user->username = $request->name;
$user->firstname = 'First '.$request->name;
$user->lastname = 'Last '.$request->name;
$user->avatar = '';
$user->bids = '5';
$user->provider = '0';
$user->provider_id = '0';
$user->enabled = '0';
$user->verification = $this->generateVerification($request->name.$request->name, $request->name);
$user->save();
return response([
'status' => 'success',
'data' => $user
], 200);
}
public function login(Request $request){
$credentials = $request->only('email', 'password');
Log::debug('Info: '.$request['email'].' - '.$request['password']);
if ( ! $token = JWTAuth::attempt($credentials)) {
return response([
'status' => 'error',
'error' => 'invalid.credentials',
'msg' => 'Invalid Credentials.'
], 400);
}
Log::debug('Success! '.$token);
return response([
'status' => 'success'
])
->header('Authorization', $token);
}
public function user(Request $request){
Log::debug('request '.$request);
$user = User::find(Auth::user()->id);
return response([
'status' => 'success',
'data' => $user
]);
}
public function refresh() {
return response([
'status' => 'success'
]);
}
public function logout(){
JWTAuth::invalidate();
return response([
'status' => 'success',
'msg' => 'Logged out Successfully.'
], 200);
}
}
httpd.conf(Apache)(已包含,因为我有许多错误已被修复)
<IfModule mod_headers.c>
<Directory />
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
Header always set Access-Control-Allow-Headers "*"
Header always set X-XSS-Protection "1; mode=block"
Header always set x-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set Referrer-Policy "strict-origin"
</Directory>
</IfModule>
/resources/assets/js/app.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
import VueAxios from 'vue-axios';
import App from './App.vue';
import Dashboard from './components/Dashboard.vue';
import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
axios.defaults.baseURL = 'https://test.mydomain.co.uk/api'; // 'localhost:8000/api'
const router = new VueRouter({
routes: [{
path: '/',
name: 'home',
component: Home
},{
path: '/register',
name: 'register',
component: Register,
meta: {
auth: false
}
},{
path: '/login',
name: 'login',
component: Login,
meta: {
auth: false
}
},{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
auth: true
}
}]
});
Vue.router = router
Vue.use(require('@websanova/vue-auth'), {
auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
});
App.router = Vue.router 新的Vue(App)。$ mount('#app');
/resources/assets/js/components/Login.vue
<template>
<div>
<div class="alert alert-danger" v-if="error">
<p>There was an error, unable to sign in with those credentials.</p>
</div>
<form autocomplete="off" @submit.prevent="login" method="post">
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control" placeholder="user@example.com" v-model="email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" v-model="password" required>
</div>
<button type="submit" class="btn btn-default">Sign in</button>
</form>
</div>
</template>
<script>
export default {
data(){
return {
email: null,
password: null,
error: false
}
},
methods: {
login(){
var app = this
this.$auth.login({
params: {
email: app.email,
password: app.password
},
success: function () {},
error: function () {},
rememberMe: true,
redirect: '/dashboard',
fetchUser: true,
});
},
}
}
</script>