How to integrate in Angular ?

Estimated reading: 9 minutes 522 views

How to Install VGAngular npm package and Configure VGAngularSecurity in Angular Project

Angular version: 15.1.4

  1. Open Command Prompt and set angular project path.
  2. Run below command for installing NPM package
  1. Open environment.ts File (FilePath: : ~\ClientApp\environments\environment.ts)

For the version VG 2019

export const environment = 
{ 
           VG_Authentication_URL: 'http://localhost:8199', 
           VG_Login_URL: '/login', 
           VGExcludeExtensions: '.css,.png,.jpg,.js', 
           AllowWindowsAuthentication: true, 
           AllowRouteGuard: true, 
           VGExcludePages: '/,login,home' ,
};

For the version VG 2019.2

New configuration for VGRuntime

export const environment = 
{ 
         VG_Authentication_URL: 'http://localhost:8199', 
         VG_Login_URL: '/login', 
         VGExcludeExtensions: '.css,.png,.jpg,.js', 
         AllowWindowsAuthentication: true, 
         AllowRouteGuard: true, 
         VGExcludePages: '/,login,home' ,

         // Store the VGToken in the cookie of the internet browser
         VG_CreateVGTokenCookie: true, // Only on VG 2019.2

         // Store the VGToken in the localstorage of the internet browser
         VG_AllowLocalStorage: false, // Only on VG 2019.2
          
         // Refresh the VGToken automatic, when the user navigate on the website
         VG_AutoRefreshOnRouting: true, // Only on VG 2019.2

         // It is use with VG_AutoRefreshOnRouting by Minutes
         VG_RefreshTokenTime: 2 // Only on VG 2019.2
};

New method to refresh the VGToken manually (Only for VG 2019.2)

this.vgSecurityRuntime.RefreshToken();

For the version VG 2020 and more

export const environment = {
  production: true,
  //all requests with any of these extensions will be excluded from authentication
  VG_ExcludeExtensions: '.css,.png,.jpg,.js',

  /**
   * true to allow windows authentication,
   * false – will redirect to url mentioned in VG_Login_Route for authentication
   * */
  VG_AllowWindowsAuthentication: true,

  /**
   * set true then route interceptor will automatically set route guard for all routes and all routes will be protected for authentication.
   * false then angular module will not set route interceptor automatically for all routes, it has to be setup in the route configuration for all required routes manually.
   */
  VG_AllowRouteGuard: true,

  //all comma separated pages will be matched for exclusion from authentication
  VG_ExcludePages: 'login,HomeComponent,vg-angular,calculate,manualSubscription,asyncPipe,vgcontextual-group,vgcontextual-role,vg-api,signout-callback-oidc,vgidentity-server-api,user-detail',

  // Redirect to change password page when required to change password
  VG_MustChangePasswordAtNextLogon_URL: '/newpassword',

  // Set true for allow write log
  VG_AllowLog: true,

  // Redirect to login route if allow authentication redirection set true
  VG_AllowAuthenticationRedirection: true,

  // for API mode redirect to login page 
  VG_Login_Route: '/login',

  // redirect to group selection page when group selection required for authentication 
  VG_ContextualGroup_Route: '/vgcontextual-group',

  // redirect to role selection page when role selection required for authentication 
  VG_ContextualRole_Route: '/vgcontextual-role',

  // authentication success redirect route
  VG_Authentication_Success_Redirect_Route: '/vg-api',

  // signout success redirect route
  VG_Redirect_Upon_SignOut_Route: '/',

  //application id which is configured in OIDC
  VG_ApplicationId: '4395b0a5-a5f4-4fac-84e0-5e0285e92e1d',

  // Set Url of the Identity Provider
  VG_AuthConfig_ISSUER: 'https://identityserver.<Your Company DNS>', /* Like https://identityserver.visual-guard.com **/ 

  /**
   * The client s redirectUri as registered with the auth server
   * URL of the SPA to redirect the user to after login
   */
  VG_AuthConfig_Redirect_Route: '/vgidentity-server-api',

  /**
  * The client s id as registered with the auth server
  * The SPA s id. The SPA is registerd with this id at the auth-server
  * clientId: 'server.code',
  */
  VG_AuthConfig_ClientId: '<Application ID>_SPA',

  /**
   * Some auth servers don t allow using password flow
   * w|o a client secret while the standards do not
   * demand for it. In this case, you can set a password
   * here. As this password is exposed to the public
   * it does not bring additional security and is therefore
   * as good as using no password.
   * 
   * Just needed if your auth server demands a secret. In general, this
   * is a sign that the auth server is not configured with SPAs in mind
   * and it might not enforce further best practices vital for security
   * such applications.
   * dummyClientSecret: 'secret',
   */
  VG_AuthConfig_DummyClientSecret: 'secret',

  /**
   * The requested scopes
   * 
   * set the scope for the permissions the client should request
   * The first four are defined by OIDC.
   * Important: Request offline_access to get a refresh token
   * The api scope is a usecase specific one
   */
  VG_AuthConfig_Scope: 'IdentityServerApi openid profile VGActivityDate VGApplications VGIsApproved VGIsLocked VGPermissions VGProfile VGRoles VGToken offline_access',

  /**
   * Defines whether additional debug information should
   * be shown at the console. Note that in certain browsers
   * the verbosity of the console needs to be explicitly set
   * to include Debug level messages.
   */
  VG_AuthConfig_ShowDebugInformation: true,

  /**
   * The client"s logout redirect Uri as registered with the auth server
   * An optional second redirectUri where the auth server
   * redirects the user to after logging out.
   */
  VG_AuthConfig_PostLogoutRedirect_Route: '/signout-callback-oidc',

  /**
   * Set UI Login Mode for redirect to Identity Server login page for authentication
   * Set API Login Mode for redirecting to current app login page
   */
  VG_Login_Mode: 'UI',

  /**
   * Defines whether to use OpenId Connect during
   * implicit flow.
   * 
   * for API mode set it false
   * for UI mode set it true
   */
  VG_AuthConfig_OIDC: true,

  /**
   * Defines whether https is required.
   * The default value is remoteOnly which only allows
   * http for localhost, while every other domains need
   * to be used with https.
   */
  VG_AuthConfig_RequireHttps: false,

  //Set ResponseType
  VG_AuthConfig_ResponseType: 'code', // id_token','code','token'
};

  • VG_Authentication_URL: Url of the server where VGAngularSecurity apis are available for authentication
    (Url of the WebApi where Security.Angular.dll is referenced and configured in startup.cs)
  • VG_LOGIN_URL: Login route where it will redirect for login (note: it should start with ?/?, e.g., /login)
  • VG_ExcludeExtensions: All requests with any of these extensions will be excluded from authentication
  • VG_AllowWindowsAuthentication: If true then it allows windows authentication, If false then it will redirect to url mentioned in VG_LOGIN_URL
    for authentication
  • VG_AllowRouteGuard : If false then angular module will not set route interceptor automatically for all routes,
    it has to be setup in the route configuration for all required routes manually, If true then route interceptor will automatically set route guard for all routes
    and all routes will be protected for authentication
  • VG_ExcludePages : All comma separated pages will be matched for exclusion from authentication as follows:
    • ‘/’ : will match route
    • ‘login’: will match login route
    • ‘purchase/pd/:id/pdpc’: will match URL like: purchase/pd/100/pdpc
    • ‘purchase/pd/:id/po/:name’: will match URL like: purchase/pd/200/po/cycle

How to integrate ?

You need to open your Angular application

1 – Import VGAngular module in app.module.ts file (File: ~\ClientApp\app\app.module.ts)Add lines shown below to import VGAngular module, service and interceptor, route guard etc.

  • Add VGAngularModule.forRoot() in imports under @NgModule
  • Add providers { provide: ‘env’, useValue: environment} in providers under @NgModule
@NgModule({ 
    declarations: [
        AppComponent,
        LoginComponent,
        HomeComponent,
        VGPermissionComponent,
        CookiesComponent,
        NavMenuComponent,
        DataProcessor,CalculateComponent
    ], 
    imports: [BrowserModule,VGAngularModule.forRoot(),FormsModule,HttpClientModule,AppRoutingModule], 
    providers: [{ provide: 'env', useValue: environment }], 
    bootstrap: [AppComponent]
 }) 

export class AppModule { }
OAuthModule.forRoot({
            resourceServer: {
                allowedUrls: ['http://vgidentityserver.novalys.local'],
                sendAccessToken: true
            }
})

Examples of APIs

import { VGRuntimeService, VGAuthenticationMode } from 'vgangular';
constructor(private vgSecurityRuntime: VGRuntimeService) { }

Login() to VisualGuard

this.vgSecurityRuntime.AuthenticateLogin(username, password,  VGAuthenticationMode.VisualGuard);

SignOut() from VisualGuard

this.vgRuntimeService.SignOut();

Method: HasPermission(permission)

let hasPermission = this.vgRuntimeService.HasPermission("CanEditContract");

Method: HasPermissions(permissionsString)

let hasPermissions = this.vgRuntimeService.HasPermissions("CanDeleteContract,CanEditContract,CanAddContract,CanViewContract");

Method: IsInRole(role)

let isinRole = this.vgRuntimeService.IsInRole("ServiceManager");

Method: IsInRoles(rolesString)

let isInRoles = this.vgRuntimeService.IsInRoles("Admin,ServiceManager");

Access user’s ProfileValues

let profileFirstname = this.vgRuntimeService.GetProfileValue("Firstname")
let profileLastname = this.vgRuntimeService.GetProfileValue("Lastname");
let employeeAvtarImageBase64String = this.vgRuntimeService.GetProfileValue("Avtar");

// get profile image example
let profileImageData = this.vgRuntimeService.GetProfile("PhotoImage");
if (profileImageData && profileImageData.isImage) {
    // set image.src = stringurl example
    let imageContent:string = profileImageData.GetDataAsImageDataString();
}

Note Note
This image string can directly bound to image.src to display image

Permission Directive (vgPermission)

  1. vgPermission (required)
  2. vgHasPermissions (optional)
  3. vgIsInRoles (optional)

  1. vgPermission: (same name as that of the directive)In given parameter you can set attributes to control html element display (‘none’, ‘inline’, ‘block’) and disabled (‘disabled’, ‘enabled’)
    when vgHasPermissions() or vgIsInRoles() are existing and returns false:
    1. ‘none’ : will hide html element
    2. ‘inline’: will show html element inline
    3. ‘block’: will show html element as block (its default)
    4. ‘disabled’: will disable the html element (user cannot click it)
    5. ‘enabled’: will enable the html element (its default)

    Example:

    • [vgPermission]=”‘none,disabled'”This means when either vgHasPermission or vgIsInRoles returns false, it will hide and disable element
    • [vgPermission]=”inline,disabled'”This means when either vgHasPermission or vgIsInRoles returns false, it will show as inline but will disable element
    • [vgPermission]=”block,disabled'”This means when either vgHasPermission or vgIsInRoles returns false, it will show as block but will disable element
    Note Note
    when vgHasPermissions (optional) or vgIsInRoles(optional) are provided and are true (all combined) then it will always show the element
    and it will be enabled. However, when it is false (any of vgHasPermissions or vgIsInRoles returns false) then it will use vgPermission
    attribute and will show/hide/enable/disable html element as the parameter values set from any of the 5 above.

    When vgHasPermssions is not present that means it is by default true, so if for example, vgHasPermissions is not present and only
    vgIsInRoles present then it will consider return value of vgIsInRoles only.

    If none of the vgHasPermissions or vgIsInRoles are present, then it will consider both as true and so will show as block
    with element enabled.

  2. vgPermission (required)Example:
    • vgHasPermissions=”CanDeleteContract, CanEditContract, CanAddContract”
    • vgHasPermissions=”CanDeleteContract”
  3. vgIsInRoles:A string with comma separated roles can be set to check if current user has these role(s)

    Example:

    • vgIsInRoles=”Default,ServiceManager,Admin”
    • vgIsInRoles=”ServiceManager”
  4. vgIsInRoles (optional)

Examples of using vgPermission attribute with html elements

  1. <button type=”button” [vgPermission=””]=”‘inline, disabled'” vgHasPermissions=”CanEditContract, AccessComponent”
    vgIsInRoles=”Default, ServiceManager”>Button</button>
    Note Note
    Here if current user does not have all permissions specified in vgHasPermissions and all roles specified in vgIsInRoles
    then it will be shown inline but will be disabled.
  2. <a [vgPermission]=”‘disabled'” vgIsInRoles=”Default,ServiceManager”>Link</a>
    Note Note
    Here vgHasPermissions is missing so only vgIsInRoles will be considered and if its false then the element will be disabled.
  3. <p [vgPermission]=”‘disabled,none'” vgHasPermissions=”CanEditContract,AccessComponent”>Paragraph</p>
    Note Note
    If current user does not have any of the permissions specified in vgHasPermissions then element will be hidden and disabled.
  4. <label [vgPermission]=”‘disabled,block'” vgHasPermissions=”AccessComponent” vgIsInRoles=”Default”>label</label>
    Note Note
    Here if current user does not have all permissions specified in vgHasPermissions and all roles specified in vgIsInRoles
    then it will be shown as block but will be disabled.