82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
|
import { HttpClient } from '@angular/common/http';
|
||
|
import { Injectable } from '@angular/core';
|
||
|
import { resolve } from 'dns';
|
||
|
import { KeycloakService } from 'keycloak-angular';
|
||
|
|
||
|
@Injectable({
|
||
|
providedIn: 'root'
|
||
|
})
|
||
|
export class D4sAuthService {
|
||
|
|
||
|
redirectUrl: string = 'http://localhost:8100/'; //'d4sworkspace://org.gcube.workspace/';
|
||
|
|
||
|
umaUrl : string = " https://accounts.dev.d4science.org/auth/realms/d4science/protocol/openid-connect/token";
|
||
|
|
||
|
audience: string = '%2Fgcube';
|
||
|
|
||
|
config: any = undefined;
|
||
|
|
||
|
uma : UmaToken | undefined ;
|
||
|
|
||
|
constructor(private keycloak: KeycloakService, private httpClient: HttpClient) {
|
||
|
}
|
||
|
|
||
|
async login() {
|
||
|
if (!this.isAuthorized()) {
|
||
|
this.keycloak.login({
|
||
|
redirectUri: this.redirectUrl
|
||
|
});
|
||
|
}
|
||
|
|
||
|
if (!this.isAuthorized())
|
||
|
throw("error authorizing");
|
||
|
|
||
|
await this.entitlement(this.audience).then( res => this.uma = res);
|
||
|
}
|
||
|
|
||
|
isAuthorized(): boolean {
|
||
|
var auth = this.keycloak.getKeycloakInstance()?.authenticated;
|
||
|
if (!auth) return false;
|
||
|
else
|
||
|
return auth;
|
||
|
}
|
||
|
|
||
|
getSecureHeader(): string{
|
||
|
return "Bearer "+this.uma?.access_token;
|
||
|
}
|
||
|
|
||
|
entitlement(resourceServerId: any): Promise<UmaToken> {
|
||
|
return new Promise((resolve, reject) => {
|
||
|
const keycloak = this.keycloak.getKeycloakInstance();
|
||
|
|
||
|
var params = "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket"
|
||
|
|
||
|
const audience = encodeURIComponent(resourceServerId)
|
||
|
params += "&audience=" + audience;
|
||
|
|
||
|
console.log("params "+params);
|
||
|
|
||
|
this.httpClient.post<UmaToken>(this.umaUrl, params , { headers: {
|
||
|
"Content-type": "application/x-www-form-urlencoded",
|
||
|
"Authorization": "Bearer " + this.keycloak.getKeycloakInstance().token
|
||
|
} }).subscribe(
|
||
|
{
|
||
|
error: (err) => reject("error getting uma token "+err),
|
||
|
next: (res:UmaToken) => resolve(res)
|
||
|
}
|
||
|
);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
class UmaToken{
|
||
|
|
||
|
constructor(public upgraded :boolean,
|
||
|
public access_token:string,
|
||
|
public expires_in: number,
|
||
|
public refresh_expires_in: number,
|
||
|
public refresh_token: string,
|
||
|
public token_type: string,
|
||
|
public not_before_policy:number){}
|
||
|
}
|