Not getting the okta groups in angular oktasignin widget - javascript

I am trying to get the users group in the okta auth response.
In okta authorization server I set up the claims and scope correctly.
but in angular Okta-sign-in widget I am getting all the users properties except the users group . Any help will be greatly appreciated. Thanks in advance.
import { Component, OnInit } from "#angular/core";
import { Router, NavigationStart } from "#angular/router";
import { environment } from "#env";
import { OktaAuthService } from "#okta/okta-angular";
import * as OktaSignIn from "#okta/okta-signin-widget";
#Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.scss"]
})
export class LoginComponent implements OnInit {
signIn;
widget = new OktaSignIn({
baseUrl: environment.OKTA_ISSUER,
authParams: {
responseType: 'id_token',
responseMode: 'okta_post_message',
pkce: true,
scopes: ['groups']
},
logo:'assets/images/resmac_newlogo.png'
});
constructor(oktaAuth: OktaAuthService, public router: Router) {
this.signIn = oktaAuth;
}
ngOnInit() {
this.widget.renderEl(
{
el: "#okta-signin-container"
},
res => {
//alert(JSON.stringify(res));
if (res.status === "SUCCESS") {
this.signIn.loginRedirect("corporate/home", {
sessionToken: res.session.token
});
// this.widget.hide();
}
},
err => {
throw err;
}
);
}
}
User Details in angular

Related

Get user data with Angular httpClient

I want to fetch user data, but I always get null. Here's my route:
router.get('/user', (req,res)=>{
res.send(req.user);
})
Don't want to go into the details, but on http://localhost:4000/auth/user, I have my user data, when I am logged in.
Here's my web service("framework" to all services) get part :
constructor(private http:HttpClient) { }
get(uri:string) {
return this.http.get(`${this.devUri}/${uri}`)
}
and AuthService(whole, because it's short):
import { Injectable } from '#angular/core';
import { WebService } from './web.service';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private webService: WebService) { }
getUser(){
return this.webService.get('auth/user');
}
}
And component with this data:
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
#Component({
selector: 'app-public',
templateUrl: './public.component.html',
styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {
user: any;
constructor(private authService: AuthService) { }
ngOnInit(): void {
this.authService.getUser().subscribe( user => {
this.user = user;
console.log(user);
})
}
}
I am sure, that there is no problem with addresses or typos, but I suspect, that the problem is connected with asynchronism, but I don't know how to fix it.
I think it's server side code issue try changing that as followed.
router.get('/user', (req,res)=>{
res.status(200).json({
result: true,
user: 'Test result'
});
});
And in you component while onInit method add as followed
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
#Component({
selector: 'app-public',
templateUrl: './public.component.html',
styleUrls: ['./public.component.css']
})
export class PublicComponent implements OnInit {
user: any;
constructor(private authService: AuthService) { }
ngOnInit(): void {
this.authService.getUser().subscribe( result => {
let temp:any = result;
this.user = temp.user;
console.log(this.user);
})
}
}
Hopefully this should work. Happy Coding!
Found the solution:
In server.js
app.use(
cors({
origin: "http://localhost:4200",
credentials: true
})
);
In webService.ts:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
withCredentials: true
}
get(uri:string) {
return this.http.get(`${this.devUri}/${uri}`, httpOptions)
}
and it's working now.

What's the correct way to load and open a component inside a modal dialog in Angular4 --

I have a component called NewCustomerComponent and I want to load and display it through a modal popup in another page/component when a button is clicked. I have written the relevant bit of code [or so it seems]. But I am getting the following error --
this._childInstance.dialogInit is not a function
at ModalDialogComponent.dialogInit (modal-dialog.component.js:65)
at ModalDialogService.openDialog (modal-dialog.service.js:26)
at OrderNewComponent.newCl (order-new.component.ts:85)
My code is pretty simple too, in the component where I am trying to open the modal popup.
I'll just post the relevant portions --
import { Component, Inject, ViewContainerRef, ComponentRef } from
'#angular/core';
import { Http, Headers } from '#angular/http';
import { Router } from '#angular/router';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import { CustomerSearchService } from '../../../shared/services/customer-
search.service';
import { ICustomer, Customer, CustomerD } from
'../../../shared/models/customer';
import { ModalDialogModule, ModalDialogService, IModalDialog } from 'ngx-
modal-dialog';
import { NewCustomerComponent } from
'../../../components/popups/customer/customer-new.component';
#Component({
selector: 'order-new',
templateUrl: './order-new.component.html'
})
export class OrderNewComponent {
public reference: ComponentRef<IModalDialog>;
constructor(private cusService: CustomerSearchService, private http:
Http, private modalService: ModalDialogService, private viewRef:
ViewContainerRef) {
}
ngOnInit(): void {
}
** this is where I am trying to load the newcustomercomponent and open it
in the popup. not working.
newCl() {
this.newC = true;
this.exiC = false;
this.modalService.openDialog(this.viewRef, {
title: 'Add New Customer',
childComponent: NewCustomerComponent
});
}
}
** edits. NewCustomerComponent code added for reference.
import { Component, Input, Output, EventEmitter, OnInit,
ChangeDetectorRef, Directive, ElementRef, Renderer, AfterViewInit }
from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { NgFor } from '#angular/common';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';
import { PlatformLocation } from '#angular/common';
import { Http } from '#angular/http';
import { ICustomer, Customer } from '../../../shared/models/customer';
import { UserService } from '../../../shared/services/UserService';
import { IModalDialog, IModalDialogOptions, IModalDialogButton } from
'ngx-modal-dialog';
#Component({
selector: 'new-customer',
templateUrl: './customer-new.component.html'
})
export class NewCustomerComponent implements IModalDialog {
model: Customer = new Customer();
errors: any;
submitResponse: any;
actionButtons: IModalDialogButton[];
constructor(private userService: UserService, private http: Http) {
this.actionButtons = [
{ text: 'Close', onAction: () => true }
];
}
ngOnInit() {
}
dialogInit(reference: ComponentRef<IModalDialog>, options:
Partial<IModalDialogOptions<any>>)
{
// no processing needed
}
createCustomer() {
this.userService.createCustomer(this.model)
.take(1)
.subscribe(
(response: any) => {
this.submitResponse = response;
if (response.success) {
console.log('New customer added!');
}
else {
console.log('Unable to add customer!');
}
},
(errors: any) => this.errors = errors
);
return false;
}
cancelClicked() {
}
}
What did I do wrong here? Has it got something to do with the element reference I added in terms of the viewRef? Which portion is erroneous? What about that child component? Does it require to have some specific configuration/markup/component for this to work? I am very new to angular; I am not sure whatever the reason is.
Kindly help me rectify this scenario.
Thanks in advance,
Can you please ensure that the NewCustomerComponent is implementing the IModalDialoginterface. Also, if this is not the case can you please share the code of NewCustomerComponent as well.
edits
Looks like you have not defined the dialogInit method in the NewCustomerComponent and it didn't pop up before as you have not implemented the interface IModalDialog. I would request you to define the dialogInit method in the component class as suggested on the link.

Angular 5 component expecting an argument

Im trying a simple profile app, and all the sudden Im getting error TS2554
ERROR in /app/components/profile/profile.component.ts(25,3): error TS2554: Expected 1 arguments, but got 0.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private auth: AuthService,
private flashMsg: FlashMessagesService,
private router: Router
) {
}
ngOnInit() {
this.auth.getProfile().subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';
#Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(
private http: Http
) {
}
getProfile(user) {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers:headers})
.map(res => res.json());
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
Your getProfile is expecting an argument named user but you are not passing it from the component
You need to pass an argument as follows,
this.auth.getProfile(user).subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
or if you don't need an argument , remove it from your service method.

Angular 2 share Service between components in different routes

I have a behaviour in Angular 2 project that i don't know how to solve. I'm using webpack with Angular 2 2.3 (if this helps).
I have a complex project with structure like this:
- index.ts
- app.module.ts
- app.component.ts
- app.routes.ts
- services
- login.service.ts
- +innerapp
- inner.routes.ts
- inner.module.ts
- inner.component.ts
- inner.component.html
- services
-inner.service.ts
- insideinner
- insideinner.component.ts
- insideinner.component.html
- header
- header.component.ts
- header.component.html
- form
- form.component.ts
- form.component.html
When you execute shows login and then route to +innerapp. Inner.component.ts loads inner.services.ts and do a http call for data. A lot of data is moved from server and a let of BehaivorSubjects are initialized inside inner.service.ts.
All works fine, but in a moment user clicks button and loads form.component.ts with a big form. User fills form and click submit, in this moment inner.service is called to add data form. My surprise is inner.service haven't data, it's just initialised.
Code below.
//inner.routes.ts
export const routes = [
{ path: '', children: [
{ path: '', component: InnerComponent },
{ path: 'form', component: FormComponent },
]},
];
inner.module.ts
import { routes } from './inner.routes';
import { InnerComponent } from './inner.component';
import { FormComponent } from './insideinner/form/form.component';
// Services
import { InnerService } from './service/inner.service';
#NgModule({
declarations: [
// Components / Directives/ Pipes
InnerComponent,
FormComponent
],
imports: [
RouterModule.forChild(routes),
],
providers: [
InnerService
]
})
export class InnerModule {
public static routes = routes;
}
inner.component.ts:
#Component({
selector: 'inner',
templateUrl: './inner.component.html'
})
export class InnerComponent implements OnInit {
constructor ( private innerService: innerService ) {
this.innerService.fetchData()
.subscribe(
(response) => {
this.innerService.addData(response.json());
},
(error) => {
alert(error);
}
);
}
services/inner.services.ts
import { Injectable } from '#angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { Headers, RequestOptions, Http, Response } from '#angular/http';
#Injectable()
export class InnerService {
// Observable string streams
public readonly data: Observable<string>;
// Observable string sources
private _data: BehaviorSubject<string> = new BehaviorSubject(null);
// private properties
private options: RequestOptions;
constructor( public http: Http ) {
this.data = this._user.asObservable();
// http standard values
let token = localStorage.getItem('token');
let cabs = new Headers({ Authorization: 'Bearer ' + token });
this.options = new RequestOptions({ headers: cabs });
}
// Service message commands
public addData (t: string) {
this._data.next(t);
}
public saveData(t: string) {
return this.http.post(blabla,
{
data: t
},
this.options
).map((res: Response) => {
this.addData(t);
return true;
}).catch(this.handleError);
}
private handleError (error: any) {
//code
}
public fetchData(): Observable<any> {
return this.http.get(blabla, this.options)
.map((res) => { return res.body })
.catch(this.handleError);
}
}
insideinner/form/form.component.ts
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
// services & others
import { InnerService } from '../../services/inner.service';
#Component({
selector: 'add-members',
templateUrl: './form.component.html',
encapsulation: ViewEncapsulation.None
})
export class FormComponent implements OnInit {
constructor(
private fb: FormBuilder,
private innerService: InnerService
) {}
public ngOnInit() {
this.showForm = false;
}
public onSubmit(value: string) {
this.innerService.saveData(value); //Fail here, inner service are without data
}
public showAdd() {
this.showForm = true;
}
}
I read a lot of docs and read here similar problems, but solutions aren't working for me.
EDIT 2017-05-31
I think that is dupe question. I see that problem is related with lazyload in routes. I try this solution:
Angular 2 lazy loaded module - service not singleton
and this solution:
Angular 2 How to make singleton service available to lazy loaded modules
But no one work for me. I want to say that this project is in garbage and I began again with Angular 1.6 but I'm really interested in solve this problem to make future projects.

Sharing an object from cone component to another Angular 2

I want to share an object from my first component to the second. I am able to log the 'strVal'(string) defined in the Login Component, in my Home Component but I am unable to log the value of 'abc'(Object) from the Login Component, in the HomeComponent. I am confused why one value from Login Component gets available to Home Component and other does not! The code for Login Component in below
Login.Component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { AuthenticationService } from '../_services/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
loading = false;
error = '';
us: User[];
abc: any[];
strVal: string = "Rehan";
current: any;
constructor(
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
// reset login status
this.authenticationService.logout();
this.getUs();
}
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
if (result) {
this.router.navigate(['/']);
}
else {
alert('Username and Password Incorrect');
this.loading = false;
this.model = [];
this.router.navigate(['/login']);
}
});
}
getUs() {
this.authenticationService.getUsers().subscribe(
res => this.us = res
);
}
chek() {
this.abc = this.us.filter(a => a.Login === this.model.username);
console.log(this.abc);
}
}
Home.Component.ts
import { Component, OnInit, Input } from '#angular/core';
import { AuthenticationService } from '../_services/index';
import { LoginComponent } from '../login/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'home.component.html',
providers: [LoginComponent]})
export class HomeComponent implements OnInit {
users: User[];
constructor(private userService: AuthenticationService, private Log: LoginComponent) { }
ngOnInit() {
this.userService.getUsers().subscribe(
res => this.users = res
);
console.log(this.Log.strVal);
console.log(this.Log.abc);
}
}
Any hint or help will be appreciated. Thanks!

Categories

Resources