Where have I to authenticate in a SPA application using laravel and vuejs? I'm developing a normal web application with laravel and blade. Nothing out of ordinary, but, now, I'm trying to make a spa application using laravel and vuejs - backend separeted from frontend. Where would I have to authenticate in this example? In php routes or vuejs routes or both? My laravel app, only laravel, it works as expected, user permissions, user session, a normal application but in vuejs, how I can do the same verifications as well?
Without knowing you exact Laravel authentication setup I would just say you authenticate through ajax at the same route as you do in Laravel. In a fairly standard setup using axios I do it like this.
ajaxLogin(){
axios.post('/login',{
email: this.loginEmail,
password: this.loginPassword
}).then(function (res) {
this.getCrsfToken(); //refresh crsf token
}.bind(this));
}
Notice the getCrsfToken function here. This may be necessary if your SPA (page) is not being refreshed when logging out and back in. Like in the case of the session expiring while the browser window is open. You would use something like the following to refresh the crsf token if you are including it the standard Laravel way in the header.
In your Routes or Controller
Route::get('/getToken', function(){
return csrf_token();
})->middleware('auth');
In your Vue component
getCrsfToken(){
axios.get('/getToken')
.then(function(res){
// Refresh crsf token from session after login
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = res.data;
});
},
Related
I had created a project before now and want to make API of it also I had a default laravel auth login module too now wants to generate sanctum auth for APIs but 2 auth running I guess.
pic shows working sanctum which I created for api
"account-settings", route in middleware not getting access but redirecting to "/login" page as shown in response, below I am providing api.php code too
In the pic this commit code // Route::group(['middleware' => ['auth', 'roles'],'roles' => ['admin','user','developer']], function () { is default laravel auth which have i commited in trying to make code working
I am want to build an app which has a static frontend ( target: 'static' in nuxt.config.js ), and a backend using ktor. The app will need to authenticate users but I do not want to manage passwords and things myself, so I would like to integrate with AWS Cognito. Based on my understanding, I think this is the workflow I want:
User is browsing the site anonymously (no login)
They do some action which requires login or explicitly click on login button.
User gets redirected to AWS Cognito ui for login. They may register for new account, login with their existing, or login using another provider (after configuring cognito for it).
Cognito ui redirects user back to the app ui but with JWT tokens in query params (I think this is just how cognito does it)
The JWT token (s?) get stored in vuex store / nuxt auth
The token is used when making requests to the backend. As well as showing some additional components / actions if the user is authenticated and their basic info like username (part of jwt?)
I think I have cognito and the ktor backend setup correctly but I don't know how to get started for the frontend.
The nuxt auth module guide says to set up middleware, but afaik middleware is only for server side rendered apps.
I need to activate the vuex store but I don't know what to put there. Are there some specific things the auth module expects or do I just create an empty file in the directory?
How do I tell it when to redirect or read the token from query param?
How to parse the JWT token (if it doesn't automatically) and get some payload info like username from it?
Does the axios module get configured automatically to make use of this?
I found this old github issue 195 in the auth module repo, but I believe that's for when the "login form"/ui is part of the nuxt app and client is making use of the cognito api without 'redirect'.
Unfortunately everything in this stack is new for me so any help is appreciated. If there is already a project doing something similar, I look at the code and try to figure it out but right now I'm lost.
update 2020-12-31, mainly so that I can put a bounty on this soon: The live demo at https://auth0.nuxtjs.org/ seems to be doing what i'm looking for but then the github page read me shows something else https://github.com/nuxt/example-auth0. Also i don't see middleware / plugins used anywhere. it's all mostly configured through nuxt config, so it only works for the auth0 custom provider?
I was having the same issue as you:
How do I tell it when to redirect or read the token from query param?
I solved this by configuring auth.redirect.callback to match the endpoint that cognito will callback with the token. I believe this will tell the middleware when to look for a new token in the query param.
nuxt.config.js:
auth: {
redirect: {
callback: '/signin',
...
},
strategies: {
awsCognito: {
redirectUri: "http://localhost:8080/signin",
...
}
}
}
And to answer your other questions:
The nuxt auth module guide says to set up middleware, but afaik middleware is only for server side rendered apps.
I tried this setup with ssr: false and it still works fine.
I need to activate the vuex store but I don't know what to put there. Are there some specific things the auth module expects or do I just create an empty file in the directory?
An empty index.js file is fine.
How do I tell it when to redirect or read the token from query param?
See first answer above.
How to parse the JWT token (if it doesn't automatically) and get some payload info like username from it?
From my initial testing I found that the middleware will automatically call the userInfo endpoint when user data is requested e.g. this.$auth.user.email
strategies: {
awsCognito: {
scheme: "oauth2",
endpoints: {
userInfo: "https://x.amazoncognito.com/oauth2/userInfo",
ref: https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.html
Does the axios module get configured automatically to make use of this?
Yes.
I'm trying to use the #nuxtjs/auth module for OAuth2 authentication from Okta in a web app.
My app has a URL structure like: /browse/{folder} to view images from a particular folder, where {folder} can be any string of text. This is accomplished by creating a top-level view called browse.vue, a folder called browse, and a child component within that folder called _folder.vue. See more on nested routes in the Nuxt.js documentation in more detail here.
I've added the auth guard to the _folder.vue file. When I navigate to /browse, I'm redirected to /login and everything works perfectly from here with OAuth2 and Okta. When I'm returned to the app after logging in, I'm taken back to the /browse page.
However, when I navigate to a folder, like /browse/Test, I'm not redirected back to that folder after logging in. Instead, I'm returned to the / view of the app. From here, if I type the path in the address bar again, I am able to successfully view it as a logged in user. This indicates that the login was successful, but something about the redirect wasn't.
I noticed by looking at the cookies in the Firefox developer tools that an auth.redirect cookie is not created when I navigate to /browse/Test, so I think the auth module is not aware of where to redirect the user after logging in. When I navigate to /browse, the auth.redirect cookie is created, and the redirect occurs successfully.
Is there something I can do to make the auth module work for redirecting to these dynamic routes, or is this a bug with the module? Everything else about the module has worked perfectly in my app.
My auth configuration in nuxt.config.js, using #nuxtjs/auth version 4.9.1:
auth: {
fullPathRedirect:true,
redirect:{
callback:"/login",
logout:"/"
},
strategies: {
social:{
_scheme: 'oauth2',
authorization_endpoint: "https://{my-subdomain}.okta.com/oauth2/v1/authorize",
scope: ['openid', 'profile', 'email'],
access_token_endpoint: "https://{my-subdomain}.okta.com/oauth2/v1/token",
response_type: 'id_token',
token_type: 'Bearer',
client_id: process.env.CLIENT_ID,
client_secret:process.env.CLIENT_SECRET,
token_key: 'id_token'
}
}
}
I am building an API using Laravel which will be used by both my Mobile and Web Applications. I am confused regarding authentication.
Basically the web application will be used by users both in logged in state and visitor state.
How would authentication work in that case? If the API uses username/password to authenticate a user what about visitors?
Also, how do I make sure its the webapp and mobile app thats making a request to the API? How do I ensure that someone doesn't programatically doesn't access the API and its only my apps that can request access to data?
You have a routes file, and you will be able to apply a filter (Laravel 4) / middleware (Laravel 5) to those routes to protect them. Assuming that you are using L5 -
Route::group('api/v1', function() {
Route::group(['middleware' => 'api.auth'], function() {
Route::get('protected', function() {
return response()->json(['Authenticated Response'], 200);
});
});
Route::get('guest', function() {
return response()->json(['Guest Response'], 200);
});
});
Then you would need to create a middleware for api.auth - See http://laravel.com/docs/5.1/routing#route-group-middleware and http://laravel.com/docs/5.1/middleware
So what happens now is when you try to visit /api/v1/protected, Laravel will run the api.auth middleware before it lets the user go any further.
api/v1/guest will of course be able to be accessed by authenticated users and guest users because there is no middleware applied.
How do I ensure that a user is logged in before I render a view using loopback?
I can loggin in the front end using my angular app. But I wanted to block anonymous users from viewing the page.
I thought it would be a header, something like headers.authorization_token, but it does not seem to be there.
I am looking for something like connect-ensurelogin for passport, without having to use passport.
This is the $interceptor that solves your problem.
This code detects 401 responses (user not logged in or the access token is expired) from Loopback REST server and redirect the user to the login page:
// Inside app config block
$httpProvider.interceptors.push(function($q, $location) {
return {
responseError: function(rejection) {
if (rejection.status == 401) {
$location.nextAfterLogin = $location.path();
$location.path('/login');
}
return $q.reject(rejection);
}
};
});
And this code will redirect to the requested page once the user is logged in
// In the Login controller
User.login($scope.credentials, function() {
var next = $location.nextAfterLogin || '/';
$location.nextAfterLogin = null;
$location.path(next);
});
Here is one possible approach that has worked for me (details may vary):
Design each of the Pages in your Single Page Angular App to make at one of your REST API calls when the Angular Route is resolved.
Secure all of your REST API Routes using the AccessToken/User/Role/ACL scheme that LoopBack provides.
When no valid Access Token is detected on the REST Server side, pass back a 401 Unauthorized Error.
On the Client Side Data Access, when you detect a 401 on your REST Call, redirect to your Logic Route.
For the smoothest User Experience, whenever you redirect to Login, store the Route the User wanted to access globally
(localStore, $RootScope, etc.) and redirect back there when the User
Logs in and gets a valid Access Token.
Here is the LoopBack Access Control sample: https://github.com/strongloop/loopback-example-access-control