Applying Web Security

Learn how to integrate the Keycloak identity service on the web endpoint for access control in the microservice built using the Devprime platform. Keycloak supports OpenID Connect / OAuth 2.0 / JWT in the protection of web pages and API’s.

During this scenario we will use the Devprime stack security adapter to enable the security settings so that when there is an access request the user is required to authenticate in a centralized Keycloak database.

To move forward in this scenario, it is essential to have an instance of Keycloak and follow the steps as instructed below:

  1. Create an instance of Keycloak following the steps indicated.

  2. Install the Devprime CLI.

  3. Creating a microservice for use in the “ms-sec-order” demo
    dp new ms-order --state mongodb --stream rabbitmq --marketplace order --init

  4. After completion, you can run the microservice. Then finish.
    .\run.ps1 or ./run.sh (Linux, macOS)

  5. Adding Web template for use in the demo. This will create some web pages
    to use in the demonstration.
    dp add web login

After running we will have a new Endpoint called “/private” that already brings the “Authorize” attribute necessary to indicate that that url requires authentication. The excerpt from the file below “code src/App/appsettings.json” demonstrates this scenario
with the /private, /login, and /logout urls.

To view by Visual Studio Code:
code src/App/appsettings.json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    public override void Endpoints(WebApplication app)
    {
        app.MapGet("/private", [Authorize]
        (ClaimsPrincipal user) =>
        {
            StringBuilder sb = new StringBuilder();
            foreach (var claim in user.Claims)
            {
                sb.Append($"{claim.Type}={claim.Value}{System.Environment.NewLine}");
            }
            return sb.ToString();
        });
        app.MapGet("/login", async (HttpContext http, string returnUrl) =>
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
                returnUrl = "/";
            await http.ChallengeAsync(SecurityConfig.Identity.AuthenticationScheme, new AuthenticationProperties()
            {RedirectUri = returnUrl});
        });
        app.MapGet("/logout", [Authorize]
        async (HttpContext http) =>
        {
            await http.SignOutAsync(SecurityConfig.Identity.AuthenticationScheme, new AuthenticationProperties{RedirectUri = "/"});
            await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        });
    }
  1. Open the settings file and include in the security adapter the Keycloak parameters obtained in item 1 of this step-by-step by changing the items “ClientID / ClientSecret / LogoutUri / Audience”

IMPORTANTE:
Put the same value of the ClientID in the Audience field as shown in the example below and make sure
that EnableOIDC is set to “true”.

Procedure to include OIDC security configuration:

a) Open through Visual Studio Code
code src/App/appsettings.json

b) Copy the code below and put it in the appsettings.json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
  "Devprime_Security": {
    "Enable": "true",
    "Identity": {
      "Enable": "true",
      "Type": "keycloak",
      "Domain": "http://localhost:8080/realms/devprime",
      "ClientId": "myapp",
      "ClientSecret": "your-clien-secret",
      "EnableOIDC": "true",
      "AuthenticationScheme": "OpenIdConnect",
      "Audience":"myapp",
      "LogoutUri": "http://localhost:8080/auth/realms/devprime/protocol/openid-connect/logout?redirect_uri=https%3A%2F%2Flocalhost%3A5001",
      "Scopes": "openid;email"
    }
  },
  1. Run the application and open https://localhost:5001 to view the new links added.

  2. Access the private link and you will be directed to authentication
    Welcome Keycloak

  3. Log in or register on Keycloak under “Register”.
    Welcome Keycloak

  4. In case of success, the private web page will be released.
    Welcome Keycloak

Next steps:

You have secured a web application using Keycloak and a microservice using the Devprime platform. Congratulations🚀🚀🚀

Last modified August 20, 2024 (2f9802da)