无法使用SAML身份提供程序将Amazon-Cognito-Auth-JS配置为angular 4应用程序 [英] Cannot configure amazon-cognito-auth-js to angular 4 application with SAML Identity provider
问题描述
我正在尝试将SAML Service provider与AWS cognito pool集成。我浏览了许多文档并尝试实现。但是,当我单击登录时,重定向没有发生。[方案是应该重定向到Microsoft登录页面]
认知池和身份提供者已正确配置。
问题来了,当我需要从前端应用程序
进行身份验证时,有人可以帮助我进行纠正吗?
这是我的代码
步骤1:
npm install amazon-cognito-auth-js-保存
步骤2:在angularcli.json中添加以下行
../ node_modules / 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
从'amazon-cognito-auth-js'导入{CognitoAuth};
步骤4:
authData = {
ClientId:'2 ****************** *** u',
AppWebDomain:'https://myApplication***********.com',
TokenScopesArray:['email'],
RedirectUriSignIn :'https // google.com',
RedirectUriSignOut:'https // google.com',
IdentityProvider:'SAML',//例如‘Facebook’,
UserPoolId:‘ap-south-1 _ ****’//您的用户池ID
};
步骤5:在app.html
< button(click)= login()> click< / button>
步骤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!);
}
};
我的问题在我单击登录按钮时页面未重定向。请帮助我
检查您的 AppWebDomain
, TokenScopesArray
和 IdentityProvider
authData值(请在下面检查我的评论):
authData = {
ClientId:'2 ********************* u',
AppWebDomain:'https:// myApplication * **********。com,//应该来自Cognito Console->您的用户池->应用集成->域名
TokenScopesArray:[电子邮件],//应该来自Cognito控制台->您的用户池->应用集成-> App Client设置->允许的OAuth范围
RedirectUriSignIn: https // google.com,
RedirectUriSignOut: https // google.com,
IdentityProvider: SAML,//例如‘Facebook’,//应该来自Cognito Console->您的用户池->联盟->身份提供者-> SAML->提供商名称
UserPoolId:‘ap-south-1 _ ****’//您的用户池ID
};
检查 GitHub 以获取更多参考。在 AUTHORIZATION 端点文档中,请注意 identity_provider
可以是:
- 对于社交登录,有效值为Facebook,Google,和
LoginWithAmazon。 - 对于Amazon Cognito用户池,值是COGNITO。
- 对于其他身份提供商,这就是您的名字
解决方案
以下解决方案适用于Angular 7中的Google登录。
> npm install -g @ angular / cli
> ng new auth-app
Angular Routing:是
> cd auth-app
> ng g c登录
> ng g c home
> ng g s cognito
> npm install-在 auth-app / src中保存amazon-cognito-auth-js
/app/cognito.service.ts
import {Injectable} from'@ angular / core';
从 @ angular / router导入{Router};从 amazon-cognito-auth-js导入
{CognitoAuth};
@ Injectable(
{
提供在:'root'
}
)
出口类别CognitoService {
authData:任何;
auth:任何;
会话:任何;
构造函数(专用路由器:路由器){
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(登录成功);
this.signedIn(session);
},
onFailure:错误=> {
console.log(’Error:’+ error);
this.onFailureMethod();
}
}
//警告(this.router.url);
//this.auth.useCodeGrantFlow();
this.auth.parseCognitoWebResponse(this.router.url);
}
signatureIn(session){
this.session =会话;
}
onFailureMethod(){
this.session = undefined;
}
get accessToken(){
返回this.session&& this.session.getAccessToken()。getJwtToken();
}
get isAuthenticated(){
返回this.auth.isUserSignedIn();
}
login(){
this.auth.getSession();
this.auth.parseCognitoWebResponse(this.router.url);
}
signOut(){
this.auth.signOut();
}
}
在 auth-app / src / app中/app.component.html
< router-outlet>< / router-outlet>
在 auth-app / src / app / login / login.component.ts
import {Component,OnInit}从'@ angular / core';从 ../cognito.service导入
{CognitoService};
从'@ angular / router'导入{Router}
@Component({
选择器:'app-login',
templateUrl:'./login。 component.html',
styleUrls:['./ login.component.scss']
})
导出类LoginComponent实现OnInit {
构造函数(私有cognitoService :CognitoService,专用路由器:路由器){
if(!this.cognitoService.isAuthenticated){
console.log( Not authenticated)
} else {
console.log (已通过身份验证)
this.router.navigateByUrl(this.router.url + / home);
}
}
ngOnInit(){}
loginWithGoogle(){
this.cognitoService.login();
}
}
在 auth-app / src / app中/login/login.component.html
< h1>登录< / h1>
< button(click)= loginWithGoogle()>使用Google登录< / button>
在 auth-app / src / app / home / home.component.ts
import {Component,OnInit}从'@ angular / core';从 ../cognito.service导入
{CognitoService};
从 @ angular / router导入{Router};
@Component({
选择器:'app-home',
templateUrl:'./home.component.html',
styleUrls:['./ home.component.scss']
})
出口类HomeComponent实现OnInit {
构造函数(私有cognitoService:CognitoService,私有路由器:路由器){
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();
}
}
在 auth-app / src / app中/home/home.component.html
< button(click)= printToken()>打印令牌< / button>
< button(click)= signOut()>退出< / button>
在 auth-app / src / app / app-routing.module.ts
从 @ angular / core导入{NgModule};
从 @ angular / router导入{Routes,RouterModule};
从 ./login/login.component导入{LoginComponent};
从 ./home/home.component导入{HomeComponent};
常量路线:路线= [
{路径:’,组件:LoginComponent},
{路径:家,组件:HomeComponent}
];
@NgModule({
进口:[RouterModule.forRoot(路线)],
出口:[RouterModule]
})
出口类AppRoutingModule { }
要使用 HTTPS 运行应用程序(因为回调URL应该为HTTPS为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
请注意,您应该在Cognito中配置以下回调和注销URL。转到Cognito控制台->您的用户池->应用集成->应用客户端设置
- 回调URL: https:// localhost:4200 / home
- 退出网址:< a href = https:// localhost:4200 rel = nofollow noreferrer> https:// localhost:4200
参考:
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
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:
这篇关于无法使用SAML身份提供程序将Amazon-Cognito-Auth-JS配置为angular 4应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!