in a web app we have used 2 Auth methods
default is JWT which we are using for API’s
but for website we are using session
somehow session are not destroying on logout
i can still access session by
auth.authenticator('session').getUser()
even after this doing in logout
await auth.authenticator('session').logout()
Here is my full code for login
Route.get('/login', async ({ view ,auth,response}) => {
try{
await auth.authenticator('session').check()
response.route('/feed')
}
catch(e){
return view.render('user.login') // User login page in web
}
})
Logout route
Route.get('/logout', async ({ auth, response }) => {
await auth.authenticator('session').logout()
response.route('/login')
})
i have noticed that if i disable chrome cache from dev tools then web app works fine
Related
I configured and initialized AWS Amplify for my ReactNative/Expo app and added a REST Api. Im new to AWS in general, but im assuming that once I add the API, my project is populated with amplify/backend folders and files and is ready for consumption.
So i tried to create a simple post request to create an item in my DynamoDB table with
import { Amplify, API } from "aws-amplify";
import awsconfig from "./src/aws-exports";
Amplify.configure(awsconfig);
const enterData = async () => {
API.post("API", "/", {
body: {
dateID: "testing",
},
headers: {
Authorization: `Bearer ${(await Auth.currentSession())
.getIdToken()
.getJwtToken()}`
}
})
.then((result) => {
// console.log(JSON.parse(result));
})
.catch((err) => {
console.log(err);
});
};
const signIn = async () => {
Auth.signIn('test#test.com', 'testpassword')
.then((data) => {
console.log(data)
enterData() //enterData is attempted after signin is confirmed.
})
.catch((err) => {
console.log(err)
})
}
signIn()
I did not touch anything else in my project folder besides including the above in my App.tsx because im unsure if i need to and where. I got a 403 error code and it "points" to the axios package but im not sure if issue is related to aws integration.
I configured the REST Api with restricted access where Authenticated users are allowed to CRUD, and guests are allowed to Read. How could I even check if I am considered an "Authorized User" .
Yes, AWS Amplify API category uses Axios under the hood so axios is related to your problem.
Probably you get 403 because you didn't authorized, for Rest API's you need to set authorization headers,
I don't know how is your config but you can take help from this page. Please review the "Define Authorization Rules" section under the API(REST) section.
https://docs.amplify.aws/lib/restapi/authz/q/platform/js/#customizing-http-request-headers
To check authorization methods, you can use "Auth" class like that also you can see auth class usage in the above link.
import { Amplify, API, Auth } from "aws-amplify";
https://aws-amplify.github.io/amplify-js/api/classes/authclass.html
I'm building a separated VueJS/Django app where Django will communicate with the Vue frontend using JSON. In order to be able to use the standard session authentication and django-allauth i will deploy the two apps on the same server and on the same port.
Here is my problem: after i log in from the Vue app using Axios, i don't receive any response but i notice that a session is created on the db, so i'm assuming that i'm getting logged in. But if i try to reach and endpoint that prints request.user.is_authenticatedi get False, and request.user returns Anonymous, so i'm not logged in anymore. How can i solve this?
Here is my Axios code:
bodyFormData.append('login', 'root');
bodyFormData.append('password', 'test');
axios({
method: "post",
url: "http://127.0.0.1:8000/accounts/login/",
data: bodyFormData,
withCredentials: true,
headers: { "Content-Type": "application/json" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I think Django-Allauth supports AJAX authentication on its urls, but i don't understand how to make it return something and how can my Vue app stay authenticated once i submit the Axios form. Any advice is welcome!
I'm trying to implement session based authentication the first time using React and Django Rest Framework, but there's some weird thing I don't understand.
I have a pretty standard Login view, so I send POST request from React with username and password, I got response with status 200 and I can see cookies in the response with Chrome developer tools.
But these cookies aren't being saved.If I do the same POST request with Rest plugin for Chrome - it saves them.
Am missing something here since it's my first time? Or should I save it manually somehow?
Here's my request with axios. Do I need to add something here?
const sendLogin = () => {
if (login && password) {
axios.post(SERVER_ADDRESS + 'login/', {username: login, password: password})
.then(response => {
if (response.status !== 200) {
handleClick();
}
else {
history.push('/');
}
})
}
}
I create a app thet need to implement authentification with email/password on all pages except one page (mobile_messages), where need to authenticate with refresh token.
I extend from JWT authenticator and override authenticate method. So it looks like:
authenticate (credentials, headers) {
return new Ember.RSVP.Promise((resolve, reject) => {
this.makeRequest('/auth/mobile_token', credentials, headers)
.then((response) => {
Ember.run(() => {
try {
const sessionData = this.handleAuthResponse(response)
resolve(sessionData)
} catch (error) {
reject(error)
}
})
}, (xhr) => {
Ember.run(() => { reject(xhr.responseJSON || xhr.responseText) })
})
})
}
On mobile_messages route I try to authenticate in before model hook.
beforeModel (transition) {
const authenticator = 'authenticator:api-token'
return this.get('session').authenticate(authenticator, {api_token: transition.queryParams.api_token}).then(() => {
}, (reason) => {
transition.abort()
this.get('notifications').error('Permission denied.', {
autoClear: true,
clearDuration: 6200
})
})
},
I need to stay on mobile_messages route if authenticate rejected. But when I enter to route with wront token I got next backtrase:
Preparing to transition from '' to 'mobileMessages'
index.js:169 generated -> controller:mobileMessages {fullName:
"controller:mobileMessages"}
index.js:169 generated -> controller:aut`enter code here`henticated
{fullName: "controller:authenticated"}
index.js:169 generated -> controller:loading {fullName:
"controller:loading"}
router.js:300 Intermediate-transitioned into 'authenticated.loading'
index.js:169 generated -> route:messages-faxes {fullName:
"route:messages-faxes"}
router.js:190 Transitioned into 'login'
jquery.js:9600 POST http://localhost:3000/auth/mobile_token 500
(Internal Server Error)
It looks like I was redirected before got response from server. An I can't find who is redirect me from route. I try to check ApplicationRouteMixin but i got that sessionInvalidated method calls only if you click logout button. And sessionAuthenticated after success authentification.
If I push to route correct token, then I first redirect to login page and then sessionAuthenticated fires. After that i redirect to baseURL.
Hot to solve issue with redirection to login page?
Ember Simple Auth uses Mixins to determine the route transition behavior that should happen if a user is authenticated/unauthenticated.
For example, this mixin will not allow the user to stay on the route if they are unauthenticated:
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
// route code
});
What you probably want to use is the UnauthenticatedRouteMixin
This mixin is used to make routes accessible only if the session is
not authenticated (e.g., login and registration routes). It defines a
beforeModel method that aborts the current transition and instead
transitions to the routeIfAlreadyAuthenticated if the session is
authenticated.
Include UnauthenticatedRouteMixin in your routes, which needs to accessed if the session is not validated. For example:
// app/routes/login.js
import UnauthenticatedRouteMixin from 'ember-simple-
auth/mixins/unauthenticated-route-mixin';
export default Ember.Route.extend(UnauthenticatedRouteMixin);
It was an error with loading hook. I make an error with naming routes. I created route with name loading to redirect to messages-faxes route. In this case when before model hook return promise ember generate route:application_loading. In application_loading route I run transition to messages-faxes route which has UnauthenticatedRouteMixin. This mixin see that user is not Authenticated and redirect to loading page.
I'm using ember-simple-auth and I can see that the authentication token is returned and that my custom authenticator is putting it (code-wise) into the session.
I can use wireshark to see that the token comes back but I can't debug into the authenticator code - I can't even use debug statements as the redirect wipes the network session on google chrome.
However, it isn't in the session (google chrome tools) and the session isn't considered authenticated.
Why is the lock code correctly popping up the auth0 dialog but not saving the session? I don't really think it is something with this code but rather a config or initialization setting I'm unaware of.
I expect the session to be saved in the _setupFutureEvents as the first thing it does.
Any ideas what I can try to get it to work?
(/app/authenticators/lock.js) authenticate (options) {
return new Ember.RSVP.Promise((res) => {
this.get('lock').show(options, (err, profile, jwt, accessToken, state, refreshToken) => {
if (err) {
this.onAuthError(err);
} else {
var sessionData = { profile, jwt, accessToken, refreshToken };
// pass the NEW auth0 session data into future events
this.afterAuth(sessionData).then(response => res(this._setupFutureEvents(response)));
}
});
});
},
afterAuth (data) {
return Ember.RSVP.resolve(data);
},
_setupFutureEvents (data) {
// set the session info here
this.get('sessionData').setProperties(data);
this._clearJobs();
this._scheduleExpire();
if (this.get('hasRefreshToken')) {
this._scheduleRefresh();
}
return this.get('sessionData');
},