问题
I am trying to integrate SAML Service provider with AWS cognito pool.I have gone through lot of documents and tried to implement .However redirecting is not happening when i click on log in .[scenario is it should redirect to Microsoft login Page] Cognito pool and identity providers are configured correctly. Problem comes when i need to authenticate from front end application could anyone please help me to rectify the same..? here is my code
step 1:
npm install amazon-cognito-auth-js --save
step 2:add below line in angularcli.json
"../node_modules/amazon-cognito-auth-js/dist/amazon-cognito-auth.js",
"../node_modules/amazon-cognito-auth-js/dist/amazon-cognito-auth.min.js.map",
"../node_modules/amazon-cognito-auth-js/dist/aws-cognito-sdk.js"
step3:app.component.ts
import {CognitoAuth} from 'amazon-cognito-auth-js';
step 4:
authData = {
ClientId : '2*********************u',
AppWebDomain : 'https://myApplication***********.com',
TokenScopesArray : ['email'],
RedirectUriSignIn : 'https//google.com',
RedirectUriSignOut : 'https//google.com',
IdentityProvider : 'SAML', // e.g. 'Facebook',
UserPoolId : 'ap-south-1_****' // Your user pool id here
};
step 5:in app.html
<button (click)="login()">click</button>
step 6:
login() {
var auth = new CognitoAuth(this.authData);
console.log("hello");
auth.userhandler = {
onSuccess: function(result) {
alert("Sign in success");
},
onFailure: function(err) {
alert("Error!");
}
};
my problem comes here when i click on login button the page is not redirecting .Please help me
回答1:
Check your AppWebDomain
, TokenScopesArray
and IdentityProvider
authData values (check my comments below):
authData = {
ClientId : '2*********************u',
AppWebDomain : 'https://myApplication***********.com', // this should be from Cognito Console -> Your user pool -> App Integration -> Domain Name
TokenScopesArray : ['email'], // this should be from Cognito Console -> Your user pool -> App Integration -> App Client Settings -> Allowed OAuth Scopes
RedirectUriSignIn : 'https//google.com',
RedirectUriSignOut : 'https//google.com',
IdentityProvider : 'SAML', // e.g. 'Facebook', // this should be from Cognito Console -> Your user pool -> Federation -> Identity Providers -> SAML -> Provider Name
UserPoolId : 'ap-south-1_****' // Your user pool id here
};
Check GitHub for more reference. From AUTHORIZATION endpoint documentation, note that identity_provider
can be either:
- For social sign-in the valid values are Facebook, Google, and LoginWithAmazon.
- For Amazon Cognito user pools, the value is COGNITO.
- For other identity providers this would be the name you assigned to the IdP in your user pool.
Solution
The below-mentioned solution is for Google Sign-In in Angular 7.
> npm install -g @angular/cli
> ng new auth-app
Angular Routing: Yes
> cd auth-app
> ng g c login
> ng g c home
> ng g s cognito
> npm install --save amazon-cognito-auth-js
In auth-app/src/app/cognito.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CognitoAuth } from 'amazon-cognito-auth-js';
@Injectable(
{
providedIn: 'root'
}
)
export class CognitoService {
authData: any;
auth: any;
session: any;
constructor(private router : Router) {
this.getAuthInstance();
}
getAuthInstance() {
this.authData = {
ClientId: '...',
AppWebDomain: '...',
TokenScopesArray: ['openid', 'email', 'profile'],
RedirectUriSignIn: 'https://localhost:4200/home',
UserPoolId: '...',
RedirectUriSignOut: 'https://localhost:4200',
AdvancedSecurityDataCollectionFlag: false
}
this.auth = new CognitoAuth(this.authData);
this.auth.userhandler = {
onSuccess: session => {
console.log('Signin success');
this.signedIn(session);
},
onFailure: error => {
console.log('Error: ' + error);
this.onFailureMethod();
}
}
//alert(this.router.url);
//this.auth.useCodeGrantFlow();
this.auth.parseCognitoWebResponse(this.router.url);
}
signedIn(session) {
this.session = session;
}
onFailureMethod() {
this.session = undefined;
}
get accessToken() {
return this.session && this.session.getAccessToken().getJwtToken();
}
get isAuthenticated() {
return this.auth.isUserSignedIn();
}
login() {
this.auth.getSession();
this.auth.parseCognitoWebResponse(this.router.url);
}
signOut() {
this.auth.signOut();
}
}
In auth-app/src/app/app.component.html
<router-outlet></router-outlet>
In auth-app/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { CognitoService } from '../cognito.service';
import { Router } from '@angular/router'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private cognitoService : CognitoService, private router : Router) {
if(!this.cognitoService.isAuthenticated) {
console.log("Not authenticated")
} else {
console.log("Already authenticated")
this.router.navigateByUrl(this.router.url + "/home");
}
}
ngOnInit() { }
loginWithGoogle() {
this.cognitoService.login();
}
}
In auth-app/src/app/login/login.component.html
<h1>Login</h1>
<button (click)="loginWithGoogle()">Login with Google</button>
In auth-app/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { CognitoService } from '../cognito.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(private cognitoService : CognitoService, private router : Router) {
if(this.router.url.indexOf('?') !== -1) {
this.router.navigateByUrl(this.router.url.substring(0, this.router.url.indexOf('?')));
} else {
this.cognitoService.login();
}
}
ngOnInit() { }
printToken() {
alert(this.cognitoService.accessToken);
}
signOut() {
this.cognitoService.signOut();
}
}
In auth-app/src/app/home/home.component.html
<button (click)="printToken()">Print Token</button>
<button (click)="signOut()">Signout</button>
In auth-app/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path:'', component: LoginComponent },
{ path:'home', component: HomeComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
To run the application with HTTPS (because Callback URL should be HTTPS for Cognito):
> npm install browser-sync --save-dev
> ng serve --ssl true --ssl-key /node_modules/browser-sync/lib/server/certs/server.key --ssl-cert /node_modules/browser-sync/lib/server/certs/server.crt
Please note that you should configure following Callback and signout URL in Cognito. Go to Cognito console -> Your user pool -> App Integration -> App Client settings
- Callback URL(s): https://localhost:4200/home
- Sign out URL(s): https://localhost:4200
Go to https://localhost:4200
References:
https://github.com/aws/amazon-cognito-auth-js/issues/13
https://github.com/aws/amazon-cognito-auth-js
https://stackoverflow.com/a/53398097/1605917
回答2:
You can try in this way... working code for me.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { CognitoAuth } from 'amazon-cognito-auth-js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
auth: any;
constructor() {
//
}
ngOnInit() {
this.auth = this.initCognitoSDK();
const curUrl = window.location.href;
this.auth.parseCognitoWebResponse(curUrl);
}
initCognitoSDK() {
const authData = {
ClientId: 'xyz',
AppWebDomain: 'xyz',
TokenScopesArray: ['openid'],
RedirectUriSignIn: 'xyz',
UserPoolId: 'xyz',
RedirectUriSignOut: 'xyz',
IdentityProvider: 'xyz',
AdvancedSecurityDataCollectionFlag: false
};
const auth = new CognitoAuth(authData);
auth.userhandler = {
onSuccess: (result) => {
alert('Sign in success');
this.showSignedIn(result);
},
onFailure: (err) => {
alert('Sign in failed');
}
};
auth.useCodeGrantFlow();
return auth;
}
login() {
this.auth.getSession();
}
showSignedIn(session) {
console.log('Session: ', session);
}
}
app.component.html
<button (click)="login()">Login</button>
回答3:
Try this
install the types so could have intellisense to amazon-sdk
npm i @types/amazon-cognito-auth-js --save-dev
then change your login method to this
login() {
const auth = new CognitoAuth(this.authData);
console.log("hello");
auth.userhandler.onSuccess = (result) => {
alert("Sign in success");
};
auth.userhandler.onFailure = (err) => {
alert("Error!");
};
}
来源:https://stackoverflow.com/questions/54132833/cannot-configure-amazon-cognito-auth-js-to-angular-4-application-with-saml-ident