mirror of
https://github.com/Bubka/2FAuth.git
synced 2024-11-26 02:04:52 +01:00
Use FreshApiToken instead of Personal access token for front-end auth
This commit is contained in:
parent
62d223ef72
commit
d6306e5dd0
@ -69,8 +69,7 @@ public function login(CaseInsensitiveLogin $request)
|
||||
*/
|
||||
public function logout(Request $request)
|
||||
{
|
||||
$accessToken = Auth::user()->token();
|
||||
$accessToken->revoke();
|
||||
Auth::logout();
|
||||
|
||||
return response()->json(['message' => 'signed out'], Response::HTTP_OK);
|
||||
}
|
||||
@ -86,14 +85,12 @@ protected function sendLoginResponse(Request $request)
|
||||
{
|
||||
$this->clearLoginAttempts($request);
|
||||
|
||||
$success['token'] = $this->guard()->user()->createToken('2FAuth')->accessToken;
|
||||
$success['name'] = $this->guard()->user()->name;
|
||||
|
||||
$this->authenticated($request, $this->guard()->user());
|
||||
|
||||
return response()->json([
|
||||
'message' => 'authenticated',
|
||||
'token' => $success['token'],
|
||||
'name' => $success['name']
|
||||
], Response::HTTP_OK);
|
||||
}
|
||||
|
@ -4,14 +4,10 @@
|
||||
|
||||
use App\User;
|
||||
use App\Http\Requests\UserStoreRequest;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Foundation\Auth\RegistersUsers;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class RegisterController extends Controller
|
||||
{
|
||||
@ -40,9 +36,10 @@ public function register(UserStoreRequest $request)
|
||||
$validated = $request->validated();
|
||||
event(new Registered($user = $this->create($validated)));
|
||||
|
||||
$this->attemptLogin($request);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'account created',
|
||||
'token' => $user->createToken('2FAuth')->accessToken,
|
||||
'name' => $user->name,
|
||||
], 201);
|
||||
}
|
||||
|
@ -37,6 +37,7 @@ class Kernel extends HttpKernel
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
\App\Http\Middleware\CustomCreateFreshApiToken::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
|
20
app/Http/Middleware/CustomCreateFreshApiToken.php
Normal file
20
app/Http/Middleware/CustomCreateFreshApiToken.php
Normal file
@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Laravel\Passport\Http\Middleware\CreateFreshApiToken as CreateFreshApiToken;
|
||||
|
||||
class CustomCreateFreshApiToken extends CreateFreshApiToken
|
||||
{
|
||||
|
||||
/**
|
||||
* Determine if the request should receive a fresh token.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return bool
|
||||
*/
|
||||
protected function requestShouldReceiveFreshToken($request)
|
||||
{
|
||||
return $request->user($this->guard);
|
||||
}
|
||||
}
|
@ -25,8 +25,16 @@ class AuthServiceProvider extends ServiceProvider
|
||||
public function boot()
|
||||
{
|
||||
$this->registerPolicies();
|
||||
Passport::routes();
|
||||
|
||||
// Normally we should set the Passport routes here using Passport::routes().
|
||||
// If so the passport routes would be set for both 'web' and 'api' middlewares without
|
||||
// possibility to exclude the web middleware (we can only pass additional middlewares to Passport::routes())
|
||||
//
|
||||
// The problem is that 2Fauth front-end uses the Laravel FreshApiToken to consum its API as a first party app.
|
||||
// So we have a laravel_token cookie added to each response to perform the authentication.
|
||||
//
|
||||
// Don't know why but when passing through the web middleware the requests to Personal Access Tokens management routes return
|
||||
// responses with inconsistent cookies that make the next request unauthorized.
|
||||
// To avoid this the Passport routes for PAT management are set in the /routes/api.php file
|
||||
}
|
||||
}
|
||||
|
23
resources/js/api.js
vendored
23
resources/js/api.js
vendored
@ -7,27 +7,18 @@ Vue.use(VueAxios, axios)
|
||||
|
||||
Vue.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
|
||||
|
||||
let token = document.head.querySelector('meta[name="csrf-token"]');
|
||||
|
||||
if (token) {
|
||||
Vue.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
|
||||
} else {
|
||||
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
|
||||
}
|
||||
// let token = document.head.querySelector('meta[name="csrf-token"]');
|
||||
|
||||
// if (token) {
|
||||
// Vue.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
|
||||
// } else {
|
||||
// console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
|
||||
// }
|
||||
|
||||
Vue.axios.interceptors.request.use(function (request) {
|
||||
|
||||
const authToken = localStorage.getItem('jwt')
|
||||
|
||||
if(authToken) {
|
||||
request.headers.common['Authorization'] = 'Bearer ' + authToken
|
||||
}
|
||||
|
||||
request.headers.common['Content-Type'] = 'application/json'
|
||||
|
||||
return request
|
||||
|
||||
})
|
||||
|
||||
Vue.axios.interceptors.response.use(response => response, error => {
|
||||
@ -46,8 +37,6 @@ Vue.axios.interceptors.response.use(response => response, error => {
|
||||
let routeName = 'genericError'
|
||||
|
||||
if ( error.response.status === 401 ) {
|
||||
localStorage.removeItem('jwt');
|
||||
localStorage.removeItem('user');
|
||||
routeName = 'login'
|
||||
}
|
||||
|
||||
|
2
resources/js/mixins.js
vendored
2
resources/js/mixins.js
vendored
@ -12,7 +12,7 @@ Vue.mixin({
|
||||
|
||||
async appLogout(evt) {
|
||||
|
||||
await this.axios.get('api/user/logout')
|
||||
await this.axios.get('/user/logout')
|
||||
|
||||
this.$storage.clear()
|
||||
delete this.axios.defaults.headers.common['Authorization']
|
||||
|
14
resources/js/routes.js
vendored
14
resources/js/routes.js
vendored
@ -57,20 +57,8 @@ router.beforeEach((to, from, next) => {
|
||||
isFirstLoad = false;
|
||||
}
|
||||
|
||||
next()
|
||||
|
||||
if (to.matched.some(record => record.meta.requiresAuth)) {
|
||||
// Accesses to restricted pages without a jwt token are routed to the login page
|
||||
if ( !localStorage.getItem('jwt') ) {
|
||||
next({
|
||||
name: 'login'
|
||||
})
|
||||
}
|
||||
// If the jwt token is invalid, a 401 unauthorized is send by the php backend
|
||||
else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
else next()
|
||||
});
|
||||
|
||||
router.afterEach(to => {
|
||||
|
@ -37,14 +37,9 @@
|
||||
handleSubmit(e) {
|
||||
e.preventDefault()
|
||||
|
||||
this.form.post('/api/user/login', {returnError: true})
|
||||
this.form.post('/user/login', {returnError: true})
|
||||
.then(response => {
|
||||
localStorage.setItem('user',response.data.name)
|
||||
localStorage.setItem('jwt',response.data.token)
|
||||
|
||||
if (localStorage.getItem('jwt') != null){
|
||||
this.$router.push({ name: 'accounts', params: { toRefresh: true } })
|
||||
}
|
||||
this.$router.push({ name: 'accounts', params: { toRefresh: true } })
|
||||
})
|
||||
.catch(error => {
|
||||
if( error.response.status === 401 ) {
|
||||
@ -61,9 +56,9 @@
|
||||
},
|
||||
|
||||
beforeRouteEnter (to, from, next) {
|
||||
if (localStorage.getItem('jwt')) {
|
||||
return next('/');
|
||||
}
|
||||
// if (localStorage.getItem('jwt')) {
|
||||
// return next('/');
|
||||
// }
|
||||
|
||||
next(async vm => {
|
||||
const { data } = await vm.axios.get('api/user/name')
|
||||
|
@ -33,12 +33,7 @@
|
||||
|
||||
this.form.post('/api/user', {returnError: true})
|
||||
.then(response => {
|
||||
localStorage.setItem('user',response.data.name)
|
||||
localStorage.setItem('jwt',response.data.token)
|
||||
|
||||
if (localStorage.getItem('jwt') != null){
|
||||
this.$router.push({ name: 'accounts', params: { toRefresh: true } })
|
||||
}
|
||||
this.$router.push({ name: 'accounts', params: { toRefresh: true } })
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(error.response)
|
||||
|
@ -13,10 +13,17 @@
|
||||
|
|
||||
*/
|
||||
|
||||
Route::group(['middleware' => 'auth:api'], function () {
|
||||
|
||||
Route::get('oauth/personal-access-tokens', '\Laravel\Passport\Http\Controllers\PersonalAccessTokenController@forUser')->name('passport.personal.tokens.index');
|
||||
Route::post('oauth/personal-access-tokens', '\Laravel\Passport\Http\Controllers\PersonalAccessTokenController@store')->name('passport.personal.tokens.store');
|
||||
Route::delete('oauth/personal-access-tokens', '\Laravel\Passport\Http\Controllers\PersonalAccessTokenController@destroy')->name('passport.personal.tokens.destroy');
|
||||
|
||||
});
|
||||
|
||||
Route::group(['middleware' => 'guest:api'], function () {
|
||||
|
||||
Route::get('user/name', 'Auth\UserController@show')->name('user.show.name');
|
||||
Route::post('user/login', 'Auth\LoginController@login')->name('user.login');
|
||||
Route::post('user', 'Auth\RegisterController@register')->name('user.register');
|
||||
Route::post('user/password/lost', 'Auth\ForgotPasswordController@sendResetLinkEmail')->middleware('AvoidResetPassword')->name('user.password.lost');;
|
||||
Route::post('user/password/reset', 'Auth\ResetPasswordController@reset')->name('user.password.reset');
|
||||
@ -28,7 +35,6 @@
|
||||
Route::get('user', 'Auth\UserController@show')->name('user.show');
|
||||
Route::put('user', 'Auth\UserController@update')->name('user.update');
|
||||
Route::patch('user/password', 'Auth\PasswordController@update')->name('user.password.update');
|
||||
Route::post('user/logout', 'Auth\LoginController@logout')->name('user.logout');
|
||||
|
||||
Route::get('settings/{settingName}', 'SettingController@show')->name('settings.show');
|
||||
Route::get('settings', 'SettingController@index')->name('settings.index');
|
||||
|
@ -16,4 +16,13 @@
|
||||
// });
|
||||
|
||||
// Route::get('twofaccount/{TwoFAccount}', 'TwoFAccountController@show');
|
||||
|
||||
Route::group(['middleware' => 'guest:web'], function () {
|
||||
Route::post('user/login', 'Auth\LoginController@login')->name('user.login');
|
||||
});
|
||||
|
||||
Route::group(['middleware' => 'auth:web'], function () {
|
||||
Route::get('user/logout', 'Auth\LoginController@logout')->name('user.logout');
|
||||
});
|
||||
|
||||
Route::get('/{any}', 'SinglePageController@index')->where('any', '.*')->name('landing');
|
Loading…
Reference in New Issue
Block a user