Authenticate a user in AWS Cognito - amazon-web-services

Here is the sample code provided by AWS for authenticating a user
var authenticationData = {
Username : 'username',
Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n',
ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/
var idToken = result.idToken.jwtToken;
},
onFailure: function(err) {
alert(err);
},
});
However, if I'm using AWS Lambda to handle the event, in this case, I can't retrieve the password from the event. What can I do to authenticate a user? Thank you : )

You don't need to create a lambda to authenticate users. Cognito will take care of that. The code you have shared is for front end applications where it connects with the cognito service to authenticate user.

Related

How to update Auth.currentUserCredentials from AWS amplify and cognito?

I have an issue where all my end-users have the same identityId when calling
await Auth.currentUserCredentials()).identityId
For instance, if I signin user1, signOut user1 by calling signOut()
, and signing in user2, the identityId for both users is the same. So I suspect that Auth.signOut() does explicitly clear the current session or user info? Im not sure whats happening but I expect the identityId to be unique for all users.
import {Auth} from 'aws-amplify';
...
const signOut = async (user) => {
await Auth.signOut()
.catch((err) => {
console.log(err)
})
}
ty in advance!

A token request using ember-simple-auth-token won't include the identification field

A have an Ember (v2.12.0-beta.1) app that uses ember-simple-auth-token to request a JWT.
The important part happens in the login controller.
export default Ember.Controller.extend({
session: Ember.inject.service(),
// Properties
username: 'user1',
password: 'password123',
// Actions
actions: {
login(username, password) {
console.log('Attempting login...');
let creds = this.getProperties('username', 'password');
let authenticator = 'authenticator:jwt';
this.get('session').authenticate(authenticator, creds).then(function() {
console.log('LOGIN SUCCESS')
}, function() {
console.log('LOGIN FAIL')
});
}
}
});
When submitting the form, there is a request that is being made by the browser and my backend receives it.
The problem is that only the password is included in the request. The body of the request has the form {"password":"password123"}, but it should look like {"username":"user1","password":"password123"}. Of course, the login attempt fails and LOGIN FAIL is printed.
Why is the username not included in the token request?
I tried using earlier versions of ember-simple-auth-token and ember-simple-auth.
Here is my configuration:
ENV['ember-simple-auth'] = {
authorizer: 'authorizer:token',
};
ENV['ember-simple-auth-token'] = {
serverTokenEndpoint: 'http://127.0.0.1:6003/token',
identificationField: 'username',
passwordField: 'password',
tokenPropertyName: 'token',
authorizationPrefix: 'Bearer ',
authorizationHeaderName: 'Authorization',
refreshAccessTokens: false,
};
ember-simple-auth-token expects credentials object passed to authenticate to be in format:
{
identification: <username>,
password: <password>
}
So your code should look something like this:
actions: {
login(username, password) {
console.log('Attempting login...');
let creds = {
identification: username,
password: password
};
let authenticator = 'authenticator:jwt';
this.get('session').authenticate(authenticator, creds).then(function() {
console.log('LOGIN SUCCESS')
}, function() {
console.log('LOGIN FAIL')
});
}
}
The request sent in this case is:
{
"password":"password123",
"username":"user1"
}
There are some pull requests about this issue.

Django session authentication with Angular 2

I've been looking all around for session based authentication with Angular 2.
I'm building an application that has Django on backend and Angular 2 on the frontend. To keep the process simple I'm trying to implement Django session authentication.
// Angular 2 authentication service
import { Injectable } from "#angular/core";
import { Headers, Http, Response } from "#angular/http";
import "rxjs/add/operator/toPromise";
import 'rxjs/add/operator/map'
import { AppSettings } from "../../app.settings";
#Injectable()
export class UserAuthService {
private headers = new Headers({'Content-Type': 'application/json'});
private loginUrl = `${AppSettings.BACKEND_URL}` + '/api/v1/users/login/';
constructor(
private http: Http
) { }
login(username, password) {
let data = {
username: username,
password: password
};
return this.http.post(this.loginUrl, data, this.headers)
.map((response: Response) => response.json());
}
}
# Django Login view
def login(self, request):
username = request.data['username']
password = request.data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
serializer = self.serializer_class(user)
return Response(serializer.data, status=status.HTTP_200_OK)
raise AuthenticationFailed
I'm successfully calling backend API and my login view returns the successful response.
Also request.user gets updated after the login but when I try to call the other APIs using Angular or directly browse Django rest API user is not logged in.
The answer to this question is to append CSRF token to the X-CSRF header, because django uses X-CSRF token header to verify the sessions.
I don't exactly remember where I saw this but Iachieved this by using angular2-cookie and writing a custom request options service like this
// Custom request options service
import { CookieService } from "angular2-cookie/services/cookies.service";
import { Headers, RequestOptions } from "#angular/http";
import { Injectable } from "#angular/core";
#Injectable()
export class CustomRequestOptionsService {
constructor(
private cookieService: CookieService
) { }
defaultRequestOptions() {
return new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json',
}),
withCredentials: true
});
}
authorizationRequestOptions() {
return new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.cookieService.get('csrftoken')
}),
withCredentials: true
});
}
}
and then in your service where you hit secure APIs use it like this
// Officer service
import { Http, Response} from "#angular/http";
import { Injectable } from "#angular/core";
import "rxjs/add/operator/map";
// Services
import { CustomRequestOptionsService } from "../shared/custom-request-options.service";
#Injectable()
export class OfficerService {
private officerDashboardUrl = `http://${process.env.API_URL}` + '/api/v1/officers/detail';
constructor(
private http: Http,
private customRequestOptionService: CustomRequestOptionsService
) { }
getOfficer(officerId: number) {
return this.http.get(`${this.officerDashboardUrl}/${officerId}/`,
this.customRequestOptionService.authorizationRequestOptions())
.toPromise()
.then((response: Response) => {
return response.json();
})
.catch((error: any) => {
return Promise.reject(error.message || error)
});
}
}

Emberjs route is unable to access authenticated user

My Ember app will show user's information after they are authenticated. I am doing authentication with Firebase and the user the is being authenticated, but the route seems to trying to find the user before this happens. It gives me this error:
Assertion Failed: You cannot pass `undefined` as id to the store's find method
Any idea how to fix this/ why it is happening?
Here is my application route with the login function:
login: function(email, password) {
this.get('session').open('firebase', {
provider: 'password',
email: email,
password: password
}).then(function() {
this.transitionTo('index');
}.bind(this));
},
logout: function() {
this.get('session').close().then(function() {
this.transitionTo('application');
}.bind(this));
}
Here is my index route:
model: function(params){
return this.store.find('user', params.user_id);
}

Ember output vars form other controllers / models in a view

I think i have a fundamental problem of understanding how to access vars in a View form other controllers.
I read the Ember-Documentation many times and "hundreds" of Blog-Entries, but i did not find a solution.
After Submitting a Loginform, i want to set the var "isLoggedIn" from Auth Controller / Model and output it in the Login View. Auth will be used later from many other Components, thats why i want to separete it from Login.
Here is a small part of my code:
Template: Login
Authenticated: {{controllers.auth.isLoggedIn}} <--- after Login this should be TRUE, but how ?
...LoginForm: here is the login form with input fields (email and password)...
Controller: Login
var LoginController = Ember.Controller.extend({
needs: "auth",
// LoginForm Submit-Event
login: function() {
App.Login.createRecord(this.getProperties("email", "password"));
DS.defaultStore.commit(); // on server respond, id of model.login is changed, see "idObserver"
}
});
Model: Login
var Login = DS.Model.extend({
email : DS.attr("string"),
password : DS.attr("string"),
// Because of Ember Bug i have to use idObserver after "DS.defaultStore.commit()"
// to get the ID responded from the server.
idObserver: function() {
var auth = App.Auth.create();
auth.set("id", this.get("id"));
}.observes("id")
});
Controller: Auth
var AuthController = Ember.Controller.extend({
isLoggedIn: false // What should i write here to connect to isLoggedIn of Auth.Model ???
}); // Controller
Model: Auth
var Auth = Ember.Object.extend({
isLoggedIn: DS.attr("boolean"),
idObserver: function() {
if(this.get("id")) this.set("isLoggedIn", true);
else this.set("isLoggedIn", false);
}.observes("id")
});
How can i output "controllers.auth.isLoggedIn" in the Login Template ?
Normally the instance of the auth model would be set on the content property of your auth controller (typically handled by the router). Once the content is set then your template would work with no modifications.
This gist might help you out as it as a login example using the router:
https://gist.github.com/machty/5647589