Enforcing Web Security

Learn how to integrate Keycloak’s identity service into the web endpoint for access control in the microservice developed 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’s security adapter to enable security settings so that when there is an access request, user authentication is required on a centralized Keycloak basis.

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 indicated procedures.

  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 it, we will have a new Endpoint called “/private” that already has 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 URLs /private, /login, and /logout.

To view from 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 as the ClientID in the Audience field as shown in the example below and make sure
that EnableOIDC is set to “true”.

Procedure for Adding Security Configuration by OIDC:

a) Open from 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. Go to the private link and you will be directed to authentication
    Welcome Keycloak

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

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

Next Steps:

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

Last modified April 11, 2024 (cc33f7e6)