npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@elderbyte/ngx-auth

v18.0.0

Published

[![CI Status](https://travis-ci.org/ElderByte-/ngx-auth.svg?branch=master)](https://travis-ci.org/ElderByte-/ngx-auth) [![npm version](https://badge.fury.io/js/%40elderbyte%2Fngx-auth.svg)](https://badge.fury.io/js/%40elderbyte%2Fngx-auth)

Downloads

57

Readme

CI Status npm version

ngx-auth

Angular authentication library based on the OpenId Connect standard (OAuth & Signed JWTs).

The major version designates the supported Angular version. For example, 15.x.x means it supports Angular 15.

The angular-oauth2-oidc library is used for authentication. For integration with Azure AD see Azure AD Integration Doc

Scope

Current

  • OIDC compatible
  • Supports OIDC discovery and auto configuration
  • Remote login supporting OAuth2 login (code flow)
  • Saving JWT in local storage
  • In-memory Principal created by JWT parsing
  • Parsing user tokens from URL like /?access_token=myNiceJwt.token
  • Mock support for easy development handling
  • Supports HttpClient request interceptors for automated JWT bearer token injection
  • Refreshtoken support
  • Supports Angular 15

Future

Usage

Install via npm

npm i @elderbyte/ngx-auth --save

Import via JS/TS import statement

import {} from "@elderbyte/ngx-auth";

OIDC Sample Configuration

@NgModule({
    declarations: [
        imports:
[
    HttpClientModule,
    ElderAuthModule.forRoot(
        {
            issuerUrl: 'http://localhost:8099/auth/realms/demo',
            clientId: 'demo-client',
            scope: 'openid profile email',
            accessDeniedRoute: 'app/accessdenied'
        }
    )
]
})

export class AppModule {
}

Azure AD B2C: don't forget to add an api scope to your client and add it in your authConfig like so: scope: 'openid profile email api://yourClientId/api'

Beware, this module depends on these three libraries:

Display DOM elements (by Role)

In case you need to hide certain elements when users do not belong to a specific role, use hasRole:


<div *hasRole="['ADMIN']">
    <!-- my incredible content -->
</div>

Guarding URLs (simplified)

Besides obtaining a token from the server, of course you may want to protect routes by restricting access to authenticated users only. This is pretty straight forward:

const appRoutes: Routes = [
    {
        path: 'login',   // Unprotected url
        component: LoginComponent,
    },
    {
        path: 'orders',
        canActivate: [SimpleAuthGuard],   // Only accessible for logged in users
        component: OrderBrowserComponent,
    }
];
  • For more fine gradient role based rules, see belows HasRoleGuard.

Guarding URLs HasRoleGuard

To prevent users from accessing parts of your application if they lack certain roles, you can use a role based router guard:

Assume you have the following route definition:

  {
    path: 'app/customers',
        component
:
    CustomerBrowserComponent,
}

Just add the HasRoleGuard incanActivate and specify the allowed roles under the data.roles key:

  {
    path: 'app/customers',
        component
:
    CustomerBrowserComponent,
        canActivate
:
    [HasRoleGuard],
        data
:
    {
        roles: ['USER']
    }
}

Configuration of AuthService (customized)

export class AuthConfig {

    /**
     * OIDC issuer url
     *
     * If this property is specified OpenId Connect is enabled.
     * Using this url, the basic configuration is auto discovered.
     */
    issuerUrl?: string;

    /**
     * Specify the OAuth client id. (Required for OAuth / OIDC login)
     */
    clientId?: string;

    /**
     * The requested scopes
     */
    scope?: string;

    /**
     * Specify resource parameter
     * AAD: To get an access token for itself, pass the client_id
     */
    resource?: string;

    /**
     * Role hierarchy to consider when
     * making decisions about granting access.
     */
    roleHierarchy?: string;

    bearer?: {

        /**
         * If true, disable bearer token injection.
         */
        disabled?: boolean

        /**
         * Specify authorization header value prefix.
         * Defaults to 'Bearer'
         */
        prefix?: string;
    };

    /**
     * An Angular route which is invoked on access denied.
     * Defaults to '/accessdenied'
     */
    accessDeniedRoute?: string;

    /**
     * The Angular route where the successful OAuth login redirect should be sent.
     *
     * Note: Since the user is automatically redirected where he wanted to go before the login intercepted him
     * (remembered url), this route is usually only important in very specific edge cases.
     * Defaults to '/'
     */
    loginCallbackRoute?: string;


    validation?: {

        /**
         * The level of https enforcement.
         * By default, all non localhost connections must use HTTPS.
         */
        httpsRequired?: HttpsValidationType;

        /**
         * Check that the obtained issuer-url at discovery time
         * equals the initial provided issuer url.
         *
         * Disabled by default for higher compatibility.
         */
        originalIssuerCheck?: boolean;

        /**
         * Checks that all urls in the obtained
         * discovery document are located under the same issuer-url.
         *
         * Disabled by default for higher compatibility.
         */
        discoveryDocumentUrlCheck?: boolean;

    };
}

Keycloak Setup & Configuration

You might want to test your application with an Identity provider instead of mocking. You can do so by using a local IAM like Keycloak.

There are a couple steps to configure a client in keycloak with code flow + PKCE.

Basic Setup

If you haven't installed keycloak yet, here's the official guide to install and set it up on docker: https://www.keycloak.org/getting-started/getting-started-docker

Using the linked guide is recommended as it's being kept updated. Here are the basic steps:

  1. Run keycloak in docker
docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:21.0.1 start-dev
  1. create a master realm (only for management)
  2. create a realm (for applications)
  3. create a client in realm
  4. create a user in realm
  5. create role in realm and assign it to the user

Client configuration for code-flow + PKCE

  1. navigate to your client (client details)
  2. in Settings tab, configure the following:

| setting | | |-----------------------------------|-----------------------------------------------------| | Client authentication | OFF | | Authentication flow | Standard flow | | Valid redirect URIs | set you application URIhttp://localhost:4300/* | | Valid post logout redirect URIs | + | | Web origins | set you application originhttp://localhost:4300 |

  1. save
  2. in Advanced tab, configure the following:

| setting | | |-----------------------------------------------------|------| | Proof Key for Code Exchange Code Challenge Method | S256 |

  1. save

Your client should now be configured to use code flow + PKCE


Development

After you have added and tested a new feature, publish a new version on npm:

  1. Increment the version in package.json and dist/package.json - they must have the same version
  2. Build the library into the /dist directory by running npm run build from the project root directory.
  3. Commit the compiled /dist changes
  4. Run npm publish dist --access=public from the project root directory or npm publish --access=public from within the dist directory.

Note --access=public is only neccessary if you publish the package the first time. If you omit this parameter the first time, you'll get a error message that you need a paid account.


License

MIT © ElderByte AG