<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luy Lucas on Medium]]></title>
        <description><![CDATA[Stories by Luy Lucas on Medium]]></description>
        <link>https://medium.com/@luylucas10?source=rss-b23911439ec7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*8idHncKJJ2EGVTTGoKD_uA.png</url>
            <title>Stories by Luy Lucas on Medium</title>
            <link>https://medium.com/@luylucas10?source=rss-b23911439ec7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:57:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luylucas10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rancher for Devs — Part 2]]></title>
            <link>https://medium.com/@luylucas10/rancher-for-devs-part-2-0f9fe4596eaa?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f9fe4596eaa</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[harbor]]></category>
            <category><![CDATA[rancher]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 00:49:36 GMT</pubDate>
            <atom:updated>2024-11-15T03:44:35.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1tMfomTM1cpZV9XU8HveQ.png" /><figcaption>Rancher Logo</figcaption></figure><h3><a href="https://medium.com/@luylucas10/rancher-for-devs-83854a6f08e7?source=your_stories_page-------------------------------------">Localhost CI/CD with Rancher — PT </a>2</h3><p><a href="https://github.com/luylucas10/rancher-localhost">GitHub - luylucas10/rancher-localhost</a></p><p>Update 15/11/2024: like the first topic, I did some updates here.</p><p>After setting up our Kubernetes cluster, it’s time to install some essential tools to make our environment fully operational.</p><h3>Longhorn</h3><p><a href="https://longhorn.io/">Longhorn</a> is a storage management tool that will handle persistent storage for us. To install it:</p><ol><li>Log in to the Rancher admin console.</li><li>Navigate to <strong>Cluster &gt; Tools &gt; </strong>select<strong> Longhorn</strong>.</li></ol><p>During the installation wizard, configure the following settings:</p><p><strong>Longhorn Default Settings:</strong></p><ul><li>Orphaned Data Cleanup: <strong>Enabled</strong></li><li>Deletion Confirmation: <strong>Enabled</strong></li></ul><p><strong>Longhorn Storage Class Settings:</strong></p><ul><li>Storage Class Retain Policy: <strong>Delete</strong></li><li>Default Storage Class Replica Count: <strong>1</strong></li><li>Default Storage Class Data Locality: <strong>Best-Effort</strong></li></ul><p><strong>Service and Load Balancing:</strong></p><ul><li>Expose: <strong>Enabled</strong></li><li>Hostname: longhorn.yourdomain.com</li></ul><p>After configuring these settings, click <strong>Install</strong> and wait it finishes.</p><h3>Monitoring</h3><p>Next, we will install Rancher’s built-in monitoring tools. You can follow the instructions from <a href="https://ranchermanager.docs.rancher.com/integrations-in-rancher/monitoring-and-alerting">Rancher’s Monitoring and Alerting documentation</a>. This installation doesn’t require additional configuration — just follow the steps.</p><h3>Logging</h3><p>You can install Logging like Monitoring, to future use.</p><h3>Harbor</h3><p><a href="https://goharbor.io/">Harbor</a> is a container registry that supports proxying Docker, GitHub, Quay, and private registries such as AWS and Azure. To install it:</p><p>Add the Harbor Helm repository and fetch the chart:</p><pre># create a namespace for harbor, I&#39;m using -system to follow the pattern of rancher<br>kubectl create namespace harbor-system<br><br># with cert-manager installed, we can create the tls certificate for harbor<br>echo &quot;apiVersion: cert-manager.io/v1<br>kind: Certificate<br>metadata:<br>  name: harbor-tls<br>  namespace: harbor-system<br>spec:<br>  secretName: harbor-tls<br>  issuerRef:<br>    name: digitalocean-issuer<br>    kind: ClusterIssuer<br>  commonName: hub.yourdomain.com<br>  dnsNames:<br>    - hub.hub.yourdomain.com<br>  &quot; | kubectl apply -f -<br><br><br>helm repo add harbor https://helm.goharbor.io <br><br>helm upgrade --install --namespace harbor-system harbor harbor/harbor \<br>    --set expose.tls.enabled=true \<br>    --set expose.tls.certSource=secret \<br>    --set expose.tls.secretName=harbor-tls \<br>    --set expose.ingress.hosts.core=hub.yourdomain.com \<br>    --set externalURL=https://hub.yourdomain.com \<br>    --set harborAdminPassword=&lt;your-password&gt; \<br>    # with metrics enabled, we can monitor harbor with prometheus<br>    --set metrics.enabled=true \ <br>    # with serviceMonitor enabled, we can monitor harbor with prometheus<br>    --set metrics.serviceMonitor.enabled=true <br><br># if you need to remove<br># helm uninstall --namespace harbor-system harbor</pre><p>After a few minutes, Harbor will be accessible at https://hub.yourdomain.com. Log in using the admin username and the password you configured.</p><h3>GitLab</h3><p>Since public GitLab or GitHub instances cannot directly access our private cluster, we will set up a local instance of GitLab.</p><p>Add the GitLab Helm repository and fetch the chart:</p><pre>helm repo add gitlab https://charts.gitlab.io/ # add the gitlab helm repository<br><br># install gitlab on cluster<br>helm upgrade --install gitlab gitlab/gitlab \<br>  --namespace gitlab-system --create-namespace \<br>  --set global.edition=ce \<br>  --set global.hosts.domain=yourdomain.com \<br>  --set global.ingress.configureCertmanager=false \<br>  --set gitlab.webservice.ingress.annotations.&quot;cert-manager\.io/cluster-issuer&quot;=&quot;digitalocean-issuer&quot; \<br>  --set global.ingress.class=nginx \<br>  --set global.ingress.tls.enabled=true \<br>  --set global.ingress.tls.secretName=gitlab-tls \<br>  --set global.monitoring.enabled=true \<br>  --set global.gitaly.enabled=true \<br>  --set global.praefect.enabled=false \<br>  --set global.minio.enabled=true \<br>  --set global.kas.enabled=false \<br>  --set global.registry.enabled=false \<br>  --set certmanager.install=false \<br>  --set nginx-ingress.enabled=false \<br>  --set prometheus.install=false \<br>  --set gitlab-runner.install=false<br><br># get the root password<br>kubectl get secret --namespace gitlab-system gitlab-gitlab-initial-root-password -ojsonpath=&#39;{.data.password}&#39; | base64 --decode ; echo<br><br># to uninstall<br># helm uninstall --namespace gitlab-system gitlab</pre><p>Access <a href="http://gitlab.yourdomain.com/">http://gitlab.yourdomain.com</a> using the root user and the password.</p><h3>ArgoCD</h3><p>ArgoCD is a popular tool for continuous delivery (CD) in Kubernetes. Install the ArgoCD CLI:</p><pre>curl -sSL -o argocd-linux-amd64 https://github.com/argoproj/argo-cd/releases/latest/download/argocd-linux-amd64<br>install -m 555 argocd-linux-amd64 /usr/local/bin/argocd<br>rm argocd-linux-amd64</pre><p>Install ArgoCD in the cluster using :</p><pre># add the helm repo<br>helm repo add argo https://argoproj.github.io/argo-helm<br><br># install argocd<br>helm upgrade --install argocd argo/argo-cd \<br>  --namespace argocd --create-namespace \<br>  --set global.domain=&#39;cd.yourdomain.com&#39; \<br>  --set configs.cm.url=&#39;https://cd.yourdomain.com&#39; \<br>  --set configs.cm.users.anonymous.enabled=false \<br>  --set configs.cm.resource.exclusions[0].apiGroups[0]=&quot;*&quot; \<br>  --set configs.cm.resource.exclusions[0].kinds[0]=&quot;PipelineRun&quot; \<br>  --set configs.cm.resource.exclusions[0].kinds[1]=&quot;TaskRun&quot; \<br>  --set configs.cm.resource.exclusions[0].clusters[0]=&quot;*&quot;\<br>  --set configs.params.application.namespaces=&quot;*&quot; \<br>  --set server.metrics.enabled=true \<br>  --set server.metrics.serviceMonitor.enabled=true \<br>  --set server.ingress.enabled=true \<br>  --set server.ingress.ingressClassName=nginx \<br>  --set server.ingress.tls=true \<br>  --set server.ingress.annotations.&quot;nginx\.ingress\.kubernetes\.io/force-ssl-redirect&quot;=true \<br>  --set server.ingress.annotations.&quot;nginx\.ingress\.kubernetes\.io/ssl-passthrough&quot;=true \<br>  --set server.ingress.annotations.&quot;nginx\.ingress\.kubernetes\.io/backend-protocol&quot;=&quot;HTTPS&quot; \<br>  --set server.ingress.annotations.&quot;cert-manager\.io/cluster-issuer&quot;=&quot;digitalocean-issuer&quot;</pre><p>Retrieve the admin password:</p><pre>argocd admin initial-password -n argocd</pre><p>Add the hostnames to your /etc/hosts file and login in ArgoCD:</p><pre>argocd login cd.yourdomain.com --username admin</pre><p>Set up the example guestbook application:</p><pre>argocd app create guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path guestbook --dest-server https://kubernetes.default.svc --dest-namespace default</pre><p>Check the app status and sync it:</p><pre>argocd app get guestbook<br>argocd app sync guestbook</pre><h3>Tekton CI</h3><p>To complete the CI/CD pipeline, we will install Tekton. Install the Tekton operator:</p><pre>curl -LO https://github.com/tektoncd/cli/releases/download/v0.38.1/tektoncd-cli-0.38.1_Linux-64bit.deb<br>dpkg -i ./tektoncd-cli-0.38.1_Linux-64bit.deb<br><br># install the tekton operator<br>kubectl apply -f https://storage.googleapis.com/tekton-releases/operator/latest/release.yaml<br><br># apply config to install all resources<br>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: operator.tekton.dev/v1alpha1<br>kind: TektonConfig<br>metadata:<br>  name: config<br>spec:<br>  targetNamespace: tekton-pipelines<br>  profile: all<br>  chain:<br>    disabled: false<br>  pipeline:<br>    set-security-context: true<br>  pruner:<br>    disabled: false<br>    schedule: &quot;* 1 * * *&quot;<br>    resources:<br>      - taskrun<br>      - pipelinerun<br>    keep: 5<br>  dashboard:<br>    readonly: false<br>EOF<br><br># add ingress to the dashboard<br>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: tekton-dashboard<br>  namespace: tekton-pipelines<br>  annotations:<br>    cert-manager.io/cluster-issuer: digitalocean-issuer<br>spec:<br>  rules:<br>  - host: ci.yourdomain.com<br>    http:<br>      paths:<br>      - pathType: ImplementationSpecific<br>        backend:<br>          service:<br>            name: tekton-dashboard<br>            port:<br>              number: 9097<br>  tls:<br>  - hosts:<br>    - ci.yourdomain.com<br>    secretName: tekton-dashboard-tls<br>EOF<br><br></pre><p>Now, all the essential tools are installed. In the next part, we’ll configure the communication between these tools to complete our CI/CD setup.</p><p>See you in the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f9fe4596eaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET MVC + Keycloak Authz]]></title>
            <link>https://medium.com/@luylucas10/asp-net-mvc-keycloak-authz-41cd4f358084?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/41cd4f358084</guid>
            <category><![CDATA[aspnetcoremvc]]></category>
            <category><![CDATA[authz]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[auth]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 23:28:40 GMT</pubDate>
            <atom:updated>2024-07-29T14:46:43.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*cMsxJyYL3kRXZ0n78qYcXg.png" /></figure><h4>Today, we are going to use Keycloak authorization services inside an ASP.NET MVC app.</h4><p>Previously, we built the integration between <a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8">ASP.NET and Keycloak</a>. Recently, I needed to use authorization to secure routes and functions in my personal project. I knew Keycloak has authorization control, so I started to search about it. Now, I’m going to show this solution to you.</p><p>For this example, we may change some configurations because we are going to use a new version of Keycloak.AuthServices. This library is very good and does the necessary job (I recommend reading its documentation).</p><p>First things first, our client needs to be confidential in the configuration, and we need the Authorization tab active:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*MjfzXvKXArm5NFVzZcPtcg.png" /><figcaption>Screenshot from keycloak app</figcaption></figure><h3>How it works:</h3><ul><li><strong>Resources</strong> are like parts of our app, such as “manage-people”, “manage-employees”, “create-something”, and can be a group of functions or a single function.</li><li><strong>Scopes</strong> are like actions that we can do, such as “list-things”, “create-thing”, “view-thing”. We can also combine them for better identification, like “list-on-manage-people” or “create-thing-on-create-something”. You can use generic or specific scopes.</li><li><strong>Policies</strong> are like rules, and you have many options to create them. I guess group, role, and user are the most used options. For example, to “manage-people”, you might need the group “hr” or the role “admin”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*u-JwwgZhVjxhbFaby1p-VQ.png" /></figure><ul><li>Lastly, we have <strong>Permissions</strong>, and as the name implies, they permit. Trying to explain in words: “the user that has this role or is in this group has permission to manage-something”. This tab will merge all the things we previously created: resources, scopes, and policies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Ywqpt14dWxqFol6CYQmcGw.png" /></figure><p>We can have resources, so we either permit all resource access or just a scope (which we are going to use).</p><p>Selecting scope-based, we have this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnF7EyXL6zCe8GSI0o_D4A.png" /></figure><p>Put a name that makes it easy to identify the permission. Select the resource that you want to permit, what scopes it will allow, and what policies are related to it. If the user needs to meet just one of all rules, your “Decision Strategy” is Affirmative. If the user needs to meet all rules, choose Unanimous. If the user needs to have more policies that allow than deny access to those scopes, choose Consensus. Easy, right? Yes, I agree that it isn’t, but after spending some hours on it, you start to learn. Lastly, you can test the permission in the Evaluate tab. Now, let’s go to the app.</p><p>We have to install two packages in our MVC app:</p><pre>Keycloak.AuthServices.Authentication<br>Keycloak.AuthServices.Authorization</pre><p>The program.cs will look like this:</p><pre>...<br>builder<br>    .Services<br>    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)<br>    .AddKeycloakWebApp(<br>        builder.Configuration.GetSection(KeycloakAuthenticationOptions.Section),<br>        configureOpenIdConnectOptions: opt =&gt;<br>        {<br>            opt.SaveTokens = true;<br>            opt.ResponseType = OpenIdConnectResponseType.Code;<br>            opt.GetClaimsFromUserInfoEndpoint = true;<br>            opt.MapInboundClaims = false;<br>            opt.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;<br>            opt.TokenValidationParameters.RoleClaimType = ClaimTypes.Role;<br>            opt.Events = new OpenIdConnectEvents<br>            {<br>                OnSignedOutCallbackRedirect = context =&gt;<br>                {<br>                    context.Response.Redirect(&quot;/&quot;);<br>                    context.HandleResponse();<br>                    return Task.CompletedTask;<br>                },<br>                OnTokenResponseReceived = context =&gt;<br>                {<br>                    var identity = context?.Principal?.Identity as ClaimsIdentity;<br>                    identity?.AddClaims(new[]<br>                    {<br>                        //there is the &quot;cat jump&quot; or as we say in Brazil &quot;o pulo do gato&quot;<br>                        new Claim(&quot;access_token&quot;, context.TokenEndpointResponse.AccessToken),<br>                        new Claim(&quot;id_token&quot;, context.TokenEndpointResponse.IdToken)<br>                    });<br>                    context.Properties.IsPersistent = true;<br>                    context.Properties.ExpiresUtc =<br>                        new JwtSecurityToken(context.TokenEndpointResponse.AccessToken).ValidTo;<br>                    return Task.CompletedTask;<br>                }<br>            };<br>        },<br>        configureCookieAuthenticationOptions: opt =&gt;<br>        {<br>            opt.LogoutPath = &quot;/acesso/sair&quot;;<br>            opt.AccessDeniedPath = &quot;/acesso/negado&quot;;<br>        });<br><br>builder<br>    .Services<br>    .AddKeycloakAuthorization(builder.Configuration)<br>    .AddAuthorizationServer(builder.Configuration)<br>    .ConfigureHttpClient(async (provider, client) =&gt;<br>    {<br>        // another &quot;cat jump&quot; here<br>        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;,<br>            await provider?.GetService&lt;IHttpContextAccessor&gt;()?.HttpContext?.GetTokenAsync(&quot;access_token&quot;)!);<br>    });<br><br>builder.Services.AddControllersWithViews(op =&gt; op.AddProtectedResources())<br>...</pre><p>The “cat jump” here is about Keycloak authorization services implementation. With Web API, as we have the header token in the context, the library catches this token to send within the request to the Keycloak API. But in MVC, we don’t have this token, so in the login process with OpenIdConnect, we take the access_token and put it as a claim in the cookie, using it in the authorization configuration. Saying it like that, it seems easy, but I worked two days on that (<a href="https://github.com/NikiforovAll/keycloak-authorization-services-dotnet/issues/104">https://github.com/NikiforovAll/keycloak-authorization-services-dotnet/issues/104</a>).</p><p>Another thing is in the Keycloak section at appsettings, we need two more options:</p><pre>&quot;DisableHeaderPropagation&quot;: true,<br>&quot;ScopesValidationMode&quot;: 1</pre><p>Do you remember the Affirmative and Unanimous in the permissions? ScopesValidationMode is about that. The library will validate if the user has all scopes allowed or any of them.</p><p>DisableHeaderPropagation makes the library not inject the existing token from the user request to the client request. It will just try to send a request, even without header auth. This is why we need to configure the client in the program.cs, catching the token from claims.</p><p>Yes, we configure everything, but how do we use all of that?</p><p>Now is the simplest part. Do you know the AuthorizeAttribute? Yes, the library has the ProtectedResourceAttribute that we can use in our actions (it’s the same for Web API).</p><p>In our MVC actions, we just put this annotation:</p><pre>[ProtectedResource(&quot;resource-name&quot;, &quot;list,of,scopes&quot;)]<br>public ViewResult Index() =&gt; View();</pre><p>“But I want to control the HTML access too,” you say. Yes, young grasshopper, we can do this. The library has the IAuthorizationServerClient, and we can use the method VerifyAccessToResource like this:</p><pre>if (!await _keycloakAuthClient<br>    .VerifyAccessToResource(&quot;resource&quot;, &quot;scope&quot;, ScopesValidationMode.AnyOf,<br>    CancellationToken.None))</pre><p>But filling our HTML with a lot of ifs and elses is not ideal, so take this tag helper:</p><pre>[HtmlTargetElement(Attributes = &quot;resouce&quot;)]<br>[HtmlTargetElement(Attributes = &quot;scopes&quot;)]<br>public class AuthTagHelper : TagHelper<br>{<br>    private readonly IAuthorizationServerClient _keycloakAuthClient;<br><br>    public AuthTagHelper(IAuthorizationServerClient keycloakAuthClient)<br>    {<br>        _keycloakAuthClient = keycloakAuthClient;<br>    }<br><br>    [HtmlAttributeName(&quot;resource&quot;)] public string Resource { get; set; }<br><br>    [HtmlAttributeName(&quot;scopes&quot;)] public string Scopes { get; set; }<br><br>    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)<br>    {<br>        if (Scopes is null || Resource is null) output.SuppressOutput();<br><br>        if (!await _keycloakAuthClient.VerifyAccessToResource(Resource, Scopes, ScopesValidationMode.AnyOf,<br>                CancellationToken.None))<br>            output.SuppressOutput();<br>        await base.ProcessAsync(context, output);<br>    }<br>}</pre><p>And use it like this (works only with ending tags with &lt;tag&gt;&lt;/tag&gt;, but you can create another tag helper that works with &lt;tag/&gt;):</p><pre>&lt;div class=&quot;card-header clearfix&quot;<br>     scopes=&quot;list,of,scopes&quot;<br>     resource=&quot;resource&quot;&gt;<br>    &lt;a class=&quot;btn btn-primary float-end&quot;<br>       href=&quot;@Url.Action(&quot;Create&quot;)&quot;&gt;<br>       Create<br>    &lt;/a&gt;<br>&lt;/div&gt;</pre><p>Now, my friend, your job will be to create a lot of permissions, hahahaha.</p><p>Thanks for reading, I hope this helped you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41cd4f358084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Localhost CI/CD with Rancher — PT 1]]></title>
            <link>https://medium.com/@luylucas10/rancher-for-devs-83854a6f08e7?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83854a6f08e7</guid>
            <category><![CDATA[localhost]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[rancher]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 20:04:32 GMT</pubDate>
            <atom:updated>2024-11-15T03:38:19.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1tMfomTM1cpZV9XU8HveQ.png" /><figcaption>Rancher logo</figcaption></figure><p><a href="https://github.com/luylucas10/rancher-localhost">GitHub - luylucas10/rancher-localhost</a></p><p>Update: 13/10/2024 — I’m refactoring all articles in this series, I recommend to read again from this beginning…</p><p>Update 15/11/2024 — More updates.</p><p>Kubernetes has evolved into what is (perhaps) the mainstream method for deploying applications. Recently, I decided to create a local environment to work with Kubernetes. Why? Well, we know that CI/CD pipelines are essential for deploying applications today, and like most developers, we learn by doing. So, I’ll show you how to create a small Kubernetes cluster for your local development. Let’s start by setting up the environment.</p><p>For this setup, I used Ubuntu Server VMs with VirtualBox. I created (no just three, but) five VMs, one with 5vCPUs and 8GB of RAM and the other 4 VMs each with 4 vCPUs, 8GB of RAM, all have 150GB of disk space, using a bridged network. I also fixed the IP addresses of these VMs on my router to resolve names in /etc/hostsand now in DigitalOcean DNS.</p><p>My machine has good specs, but you can try with fewer resources—perhaps 4 VMs with 4 vCPUs and 4GB of RAM (time to make your CPU work!). You&#39;ll need at least 70GB of disk space per node to accommodate the persistent volumes that will be created, but I recommend 100GB.</p><p>In my setup, I used one Control Plane + etcd (the bigger one) and four Worker nodes. These roles are defined by Kubernetes and RKE2. If you add a fifth machine, keep one Control Plane and make the others Worker nodes. Why? According to the docs:</p><blockquote><em>“An etcd cluster must consist of an odd number of server nodes to maintain quorum. For a cluster with </em><em>n servers, quorum is </em><em>(n/2) + 1. While adding a node to an odd-sized cluster increases the number of nodes, it reduces fault tolerance. The same number of node failures is allowed without losing quorum, but with more nodes, there are more potential points of failure.&quot; </em><a href="https://docs.rke2.io/install/ha"><em>Source</em></a></blockquote><h3>Let’s Begin:</h3><ol><li>Create all VMs, format them, and update them:</li></ol><pre>sudo -i<br>systemctl stop ufw # stop the software firewall<br>systemctl disable ufw # disable the software firewall<br>apt update # get updates<br>apt upgrade -y # do updates<br>apt install nfs-common -y # install nfs for longhorn system<br>apt autoremove -y # clean up</pre><p>We’ll use Rancher over RKE2. If you want more information, check out the <a href="https://docs.rke2.io/">RKE2 documentation</a> or <a href="https://ranchermanager.docs.rancher.com/">Rancher documentation</a>. I used this <a href="https://ranchergovernment.com/blog/article-simple-rke2-longhorn-and-rancher-install">blog post</a> as a reference to build this.</p><p>Choose one VM to be the master Control Plane of the cluster. This VM will generate the token that allows the other machines to connect. Install RKE2:</p><pre>curl -sfL https://get.rke2.io | sh -  # Install RKE2</pre><p>RKE2 uses /etc/rancher/rke2/ for config files, so create that directory:</p><pre>mkdir -p /etc/rancher/rke2/  # Create the base config directory<br>touch /etc/rancher/rke2/config.yaml  # Create the config file</pre><p>Add the following configurations:</p><pre>echo &quot;write-kubeconfig-mode: 0644&quot; &gt;&gt; /etc/rancher/rke2/config.yaml # write kubeconfig mode<br>echo &quot;cni: cilium&quot; &gt;&gt; /etc/rancher/rke2/config.yaml # use cilium as cni<br># Self-signed certificates configuration for the Rancher server<br>echo &quot;tls-san:<br>  - rancher.&lt;yourdomain.com&gt;&quot; &gt;&gt; /etc/rancher/rke2/config.yaml</pre><p>One cool thing about RKE2 is its Helm chart integration. You can modify the behavior of components just by placing the right manifests in the appropriate directories. For example, here’s how to add the NGINX ingress controller with SSL passthrough, which is necessary for ArgoCD:</p><pre>mkdir -p /var/lib/rancher/rke2/server/manifests<br>touch /var/lib/rancher/rke2/server/manifests/rke2-ingress-nginx-config.yaml<br><br>echo &quot;apiVersion: helm.cattle.io/v1<br>kind: HelmChartConfig<br>metadata:<br>  name: rke2-ingress-nginx<br>  namespace: kube-system<br>spec:<br>  valuesContent: |-<br>    controller:<br>      config:<br>        use-forwarded-headers: true<br>      extraArgs:<br>        enable-ssl-passthrough: true&quot; &gt; /var/lib/rancher/rke2/server/manifests/rke2-ingress-nginx-config.yaml</pre><p>Now, enable and start the RKE2 server:</p><pre>systemctl enable rke2-server.service  # Enable RKE2 server on boot<br>systemctl start rke2-server.service  # Start RKE2 server</pre><p>Create a symlink for kubectl:</p><pre>ln -s $(find /var/lib/rancher/rke2/data/ -name kubectl) /usr/local/bin/kubectl</pre><p>Set the Kubeconfig environment variable:</p><pre>export KUBECONFIG=/etc/rancher/rke2/rke2.yaml  # For current session<br>echo &quot;KUBECONFIG=&#39;/etc/rancher/rke2/rke2.yaml&#39;&quot; &gt;&gt; ~/.bashrc  # For future sessions<br>source ~/.bashrc</pre><p>Install Helm CLI:</p><pre># install helm<br>curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash</pre><p>Retrieve the token for other servers and agents (workers):</p><pre>cat /var/lib/rancher/rke2/server/node-token</pre><p>To add additional control plane servers, follow the instructions in this <a href="https://github.com/luylucas10/rancher-localhost/blob/main/02.1-create-other-server.sh">GitHub repository</a>.</p><p>For agent nodes, the configuration is simpler:</p><pre>mkdir -p /etc/rancher/rke2/ # create directory<br>touch /etc/rancher/rke2/config.yaml # create config file<br>echo &quot;write-kubeconfig-mode: 0644&quot; &gt;&gt; /etc/rancher/rke2/config.yaml # write kubeconfig mode<br>echo &quot;server: https://&lt;ip-of-your-first-control-plane&gt;:9345&quot; &gt;&gt; /etc/rancher/rke2/config.yaml # main server ip <br>echo &quot;token: &lt;server-token&gt;&quot; &gt;&gt; /etc/rancher/rke2/config.yaml # main server token</pre><p>Then, install the RKE2 agent:</p><pre>curl -sfL https://get.rke2.io | INSTALL_RKE2_TYPE=&quot;agent&quot; sh -  # Install RKE2 agent<br>systemctl enable rke2-agent.service  # Enable RKE2 agent on boot<br>systemctl start rke2-agent.service  # Start RKE2 agent</pre><p>Great! Now you can run commands with kubectl from the first server:</p><pre>watch kubectl get nodes  # Watch the nodes in the cluster<br><br>NAME               STATUS   ROLES                       AGE     VERSION<br>rancher-agent-01   Ready    &lt;none&gt;                      6h20m   v1.30.5+rke2r1<br>rancher-agent-02   Ready    &lt;none&gt;                      6h12m   v1.30.5+rke2r1<br>rancher-server     Ready    control-plane,etcd,master   6h43m   v1.30.5+rke2r1</pre><p>To install Rancher Server and other apps, you’ll need Helm:</p><pre># Install Helm<br>curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash</pre><p>After installing Helm, install cert-manager and create a issuer for it to use Digital Ocean:</p><pre><br>helm repo add jetstack https://charts.jetstack.io<br><br>helm install cert-manager jetstack/cert-manager \<br>    --namespace cert-manager \<br>    --create-namespace \<br>    --set crds.enabled=true<br><br>echo &quot;apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: digitalocean-api-token<br>  namespace: cert-manager<br>type: Opaque<br>data:<br>  access-token: &lt;base64-digital-token&gt;&quot; | kubectl apply -f -<br><br>echo &quot;apiVersion: cert-manager.io/v1<br>kind: ClusterIssuer<br>metadata:<br>  name: digitalocean-issuer<br>  namespace: cert-manager<br>spec:<br>  acme:<br>    server: https://acme-staging-v02.api.letsencrypt.org/directory<br>    email: &lt;your-email&gt;<br>    privateKeySecretRef:<br>      name: digitalocean-tls-key<br>    solvers:<br>    - dns01:<br>        digitalocean:<br>          tokenSecretRef:<br>            name: digitalocean-api-token<br>            key: access-token&quot; | kubectl apply -f -<br></pre><p>Install Rancher and set annotation to user Digital Ocean Cluster Issuer. Don’t forget to add all domain names at DNS.</p><pre>helm repo add rancher-latest https://releases.rancher.com/server-charts/latest<br><br>helm upgrade --install rancher rancher-latest/rancher \<br>  --namespace cattle-system \<br>  --create-namespace \<br>  --set hostname=rancher.&lt;your-domain&gt; \<br>  --set bootstrapPassword=admin \<br>  --set ingress.tls.source=letsEncrypt \<br>  --set letsEncrypt.email=your@email.com \<br>  --set letsEncrypt.ingress.class=nginx \<br>  --set letsEncrypt.environment=staging<br><br>kubectl -n cattle-system rollout status deploy/rancher<br><br># patch the rancher ingress to use cert-manager digitalocean-issuer as the cluster issuer and the tls secret<br>kubectl -n cattle-system patch ingress rancher -p &#39;{&quot;metadata&quot;:{&quot;annotations&quot;:{&quot;cert-manager.io/cluster-issuer&quot;:&quot;digitalocean-issuer&quot;}}}&#39;</pre><p>Wait for Rancher to be ready:</p><pre>kubectl -n cattle-system rollout status deploy/rancher</pre><p>After a few minutes, Rancher should be accessible at rancher.yourdomain.com. Use the password admin to log in, and save your new password. If you need to reset it later, you can run this command:</p><pre>kubectl -n cattle-system exec $(kubectl -n cattle-system get pods -l app=rancher --no-headers | head -1 | awk &#39;{ print $1 }&#39;) -c rancher -- reset-password</pre><p>(or you can continue use hosts file) On your host machine (the one running VirtualBox), add the following entries to your hosts file:</p><pre>&lt;rancher-server-vm-ip&gt;  rancher.yourdomain.com<br>&lt;rancher-server-vm-ip&gt;  cd.yourdomain.com<br>&lt;rancher-server-vm-ip&gt;  ci.yourdomain.com<br>&lt;rancher-server-vm-ip&gt;  gitlab.yourdomain.com<br>&lt;rancher-server-vm-ip&gt;  storage.yourdomain.com</pre><p>We’ll configure these DNS entries in the cluster later. For now, your Kubernetes cluster is up and running, ready for you to explore.</p><p>Next, we’ll start setting up the tools you’ll need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83854a6f08e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 5]]></title>
            <link>https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-5-3da06ac4801e?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da06ac4801e</guid>
            <category><![CDATA[openid]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 17:22:48 GMT</pubDate>
            <atom:updated>2024-01-28T17:22:48.376Z</atom:updated>
            <content:encoded><![CDATA[<h3>ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 5</h3><p>This part is about loading roles in the jwt token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*836xzJ6_S5G36I2Ta_5sfw.png" /></figure><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-1-74f5eb779dc2">Part 1;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8">Part 2;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-3-83e330962f0d">Part 3;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-4-0f32ade3f751">Part 4;</a></p><p>Now that we have all clients configured, there is a bonus.</p><p>Since we used a public client in Keycloak, it’s not possible to use authorization services to have fine-grained authorization.</p><p>As a result, we only have groups and roles to use (RBAC).</p><p>To do this, we open the admin UI, select the client that was created, and in the ‘Client Scope’ tab, we select the ‘&lt;clientid&gt;-dedicated’ scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXKH-450M_tOWNHVsWmwog.png" /></figure><p>Click in Add Mapper &gt; By Configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*NpESTNp4zWW8MGqNccNIWQ.png" /></figure><p>Select the ‘User Client Role’ option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*pIZiWLlDFxYK1bdky5YAMA.png" /></figure><p>Set its configuration like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnexTMo-J5dkcizdcTQ0xQ.png" /></figure><p>Now, every created token will contain the role attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*xKn17hLf0WTtZp--75irgg.png" /><figcaption>Click on Evalute tab, on side of Setup tab, bellow the Client Scopes tab</figcaption></figure><p>The API app just has the role name configured so we don’t need to set it.</p><p>In the MVC app, we have to input this in the OpenIdConnect options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*sUZC_5sdbdAK8Obic1T7Sw.png" /></figure><p>And in Blazor too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*oaRvs0r8i-uH7ZOhQ8l6wA.png" /></figure><p>That’s it. Now, all roles of an authenticated user will be loaded and you can use in Authorize attribute to check user permissions.</p><p>All this code is in my <a href="https://github.com/luylucas10/aspnetcore-keycloak-examples">example repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da06ac4801e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 4]]></title>
            <link>https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-4-0f32ade3f751?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f32ade3f751</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[blazor-webassembly]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[sso]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 17:00:33 GMT</pubDate>
            <atom:updated>2024-01-28T17:23:41.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 4</h3><p>In this part, we’ll configure a Blazor app to use Keycloak as SSO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*836xzJ6_S5G36I2Ta_5sfw.png" /></figure><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-1-74f5eb779dc2">Part 1;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8">Part 2;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-3-83e330962f0d">Part 3;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-5-3da06ac4801e">Bonus;</a></p><p>In the same solution we created before, create a Blazor WASM project and select ‘Individual Accounts’. Just as we did before, copy the Keycloak appsettings section to the new appsettings. In the ‘Program.cs’ file, write these configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTsH7MxWlkuzMJ27V3JGNw.png" /></figure><p>Copy the ‘applicationUrl’ from ‘launchSettings’ and register it as a valid redirect URI in the Keycloak client. It’s ready. Annotate the ‘Weather.razor’ page with the ‘[Authorize]’ attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*0BhjHMKeQdR5CoUcj0aRIw.png" /></figure><p>Run the app.</p><p>When you click on the ‘Weather’ link, it’ll redirect you to the Keycloak login page, <em>voilá</em>.</p><p>As a bonus, we can use a http client to consume the API. For this, we have to create an ‘AuthorizationMessageHandler’ to set the Bearer Token in the http messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*SDyh6cb0L5gZC26AL_SMjw.png" /></figure><p>Register it as transient and as message handler for http client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*CfqJ-c1SfGBYSOQw-hTpqg.png" /></figure><p>In the ‘Weather.razor’ page, inject the ‘IHttpClientFactory’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*nfPa8XskF_UFsBHLKSsWvw.png" /></figure><p>And in the code section, call the API to get values from your API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*8BemxIlW8uM0_ggd_QFR9g.png" /></figure><p>As the Weather model is the same in the API and Blazor, we don’t have to change it. Now run the API and Blazor, test the weather page, if you check the Network section in you development tools on browser, you can see the Bearer Token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f32ade3f751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 3]]></title>
            <link>https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-3-83e330962f0d?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e330962f0d</guid>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[openid]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[aspnetcoremvc]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 17:00:28 GMT</pubDate>
            <atom:updated>2024-01-28T17:24:29.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*836xzJ6_S5G36I2Ta_5sfw.png" /></figure><p>In this part, we’ll integrate a MVC app with Keycloak</p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-1-74f5eb779dc2">Part 1;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8">Part 2;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-4-0f32ade3f751">Part 4;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-5-3da06ac4801e">Bonus;</a></p><p>For the MVC app, we do almost the same thing like on API before.</p><p>We have to install this package:</p><blockquote>Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect</blockquote><p>Copy the keycloak section from the API appsettings, we can use the same client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*QJNEroXgTsAYQ0KLb6o9aQ.png" /></figure><p>Copy the applicationUrl from launchSettings and input as Valid Redirect URI in the Keycloak client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*D6h6sWZVbTu4xD9Z3HGJgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*1JKvKRkJixtdzJYc4RIlMA.png" /><figcaption>I used the same client for all examples in this series</figcaption></figure><p>In the program.cs file we write these configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*GAHktaewu84rh2Y2yxHRyw.png" /></figure><p>Don’t forget to activate the Auth and Authz middlewares.</p><p>In the HomeController.cs We can use the [Authorize] attribute in the Privacy action.</p><p>Run this and click on the privacy link, You’ll be redirected to Keycloak login page, use the usertest1 credentials. Create a breakpoint in the Index or Privacy action and see the User:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*tX15JKtP_TFBifRWTWqepA.png" /></figure><p>Well that’s all for now!</p><p>Next, I’ll share Blazor WASM solution to this.</p><p>Cya.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e330962f0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core (API, Blazor and MVC) + Keycloak — Part 2]]></title>
            <link>https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e487c6a5e8</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 15:47:31 GMT</pubDate>
            <atom:updated>2024-01-28T17:24:16.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*836xzJ6_S5G36I2Ta_5sfw.png" /></figure><h3>ASP.NET Core (API, Blazor and MVC) + Keycloak — Part 2</h3><p>In this part 2, We’ll connect an API with one client</p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-1-74f5eb779dc2">Part 1;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-3-83e330962f0d">Part 3;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-4-0f32ade3f751">Part 4;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-5-3da06ac4801e">Bonus;</a></p><p>With Visual Studio 2022, Visual Studio Code, Jetbrains Rider, or your favorite IDE, create a solution and add an ASP.NET API app with no authentication and add these packages:</p><blockquote>Install-Package Keycloak.AuthServices.Authentication</blockquote><blockquote>Install-Package Keycloak.AuthServices.Authorization</blockquote><p>These two packages from <a href="https://github.com/NikiforovAll/keycloak-authorization-services-dotnet/tree/main">GitHub</a> have all the configurations needed to connect the API to Keycloak. In the Keycloak Administration Panel, select the ASP.NET realm, go to ‘clients’ and copy the client settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*ib-cT92K4UvXxE6ev0bHIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*-PJ7IaoVderqP4eX3-zJ8g.png" /></figure><p>In the ‘appsettings.development’, create a new section called ‘Keycloak’ and paste this JSON:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*0Ai7w8rAZmP9QATXBId7xw.png" /></figure><p>SSL is not used because this is just a development example. You will need to configure this for your production scenario. Now, in the ‘Program.cs’ file, we’ll register the authentication and authorization services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*SWLm1QVe8xSN4FzrAUetdQ.png" /></figure><p>We can use Keycloak with Swagger too. Just paste this configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcotWx0Jvmh6AqKvrCSx7g.png" /></figure><p>Don’t forget to register the middlewares. I’ve disabled CORS for this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*sHwUCCvY9E39x3-oIgEC7w.png" /></figure><p>Before run this, We need to register the URI as valid in Keycloak client. We can copy the registred valid redirect URI from Keycloak client to API launch settings or copy the url from launch settings and input as valid URI on the keycloak client. We just need to have the app URI on keycloak client.</p><p>For this example, I have changed API launchsettings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*MLbB0dnLSxqBLj8PE3EPqg.png" /></figure><p>That’s all we need. Run this, and on Swagger, click ‘Authorize’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*bFJBu1lQ-nHXYkAcxAxS8A.png" /></figure><p>Search for ‘implicit’ and enter the client ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*rUhUgki6636-9E2ba_4png.png" /></figure><p>Click on ‘Authorize’. This will redirect you to the Keycloak login page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*hAFn1u8kq8frba3vk9dceA.png" /></figure><p>Use the usertest1 credentials and <em>voilá</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*MZEr0MrIsuIaON351wD8CA.png" /></figure><p>Now, you can generate tokens from the Keycloak API and use them directly as bearer tokens for the API.</p><p>This source is in my <a href="https://github.com/luylucas10/aspnetcore-keycloak-examples">GitHub</a> and I used <a href="https://github.com/NikiforovAll/keycloak-authorization-services-dotnet/tree/main">this repo</a> from <a href="https://nikiforovall.github.io/aspnetcore/dotnet/2022/08/24/dotnet-keycloak-auth.html">this article</a> to build this.</p><p>Next, we’ll do this with ASP.NET Core MVC.</p><p>Cya.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e487c6a5e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core (API, Blazor and MVC) + Keycloak — Part 1]]></title>
            <link>https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-1-74f5eb779dc2?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f5eb779dc2</guid>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 14:27:56 GMT</pubDate>
            <atom:updated>2024-01-28T17:24:02.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>ASP.NET Core (API, Blazor and MVC) + Keycloak — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*836xzJ6_S5G36I2Ta_5sfw.png" /></figure><p>This series delves into the integration of ASP.NET Core apps with Keycloak SSO (running in Docker), explaining how to authenticate and authorize an user.</p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-and-mvc-keycloak-part-2-69e487c6a5e8">Part 2</a>;</p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-3-83e330962f0d">Part 3;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-4-0f32ade3f751">Part 4;</a></p><p><a href="https://medium.com/@luylucas10/asp-net-core-api-blazor-mvc-keycloak-part-5-3da06ac4801e">Bonus;</a></p><p>We’ll start configuring the Keycloak instance on Docker running this command on powershell:</p><blockquote>docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:latest start-dev</blockquote><p>This will start an instance on develop mode. Open the admin UI http://localhost:8080, option “Administration Console”, login with admin/admin credentials:</p><figure><img alt="A print of the administration console option after open the localhost url" src="https://cdn-images-1.medium.com/max/591/1*Yqt6eEtU4tohS6TKEJmGGw.png" /></figure><p>Lets create a new realm, name it aspnet (or any name do you want):</p><figure><img alt="A print of realm options in the sidebar menu of keycloak UI" src="https://cdn-images-1.medium.com/max/299/1*noffT2uSnbvc2wAMlBXvew.png" /></figure><p>The realm needs just the name:</p><figure><img alt="A print of the realm register page" src="https://cdn-images-1.medium.com/max/558/1*iSNX8A1rQwqu5EqK5ln3Iw.png" /></figure><p>After create a realm, create a client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*dVIFS6xkxVRagUj4BYyMZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*8LUYShnQ5XlHRDvhkaIHHg.png" /></figure><p>Client type: OpenId;</p><p>ClientId: You can use a plain text or a uuid;</p><p>Give a name and description to the client;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax0tIz48sNww5fTh0CPS1A.png" /></figure><p>Client Authentication: off;</p><p>Enable Implicit Flow (It’ll used by Swagger);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nk3UMnoZmXJKuAnGWNbqvQ.png" /></figure><p>Root URL: API Url;</p><p>Valid Redirects URIs: are URIs that Keycloak can redirect after login;</p><p>Web Origins: are URIs that Keycloak can accept requests, set it ‘+’ to accept requests from Valid Redirect URIs;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*nW7G_1KHXCRSd3MYSjgrKg.png" /></figure><p>Save. Now, create an user in the realm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnzpPxVNQPraq5UGuQJrRQ.png" /></figure><p>In the credentials tab, create a password (make it simple, like 123456):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*1ZqZLgndPKJsktBfMfb2Dg.png" /></figure><p>For now, We have a Keycloak instance configured to use. In the next part, We’ll configure an API to use this client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f5eb779dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core MVC, Webpack and Vue.js — Update]]></title>
            <link>https://medium.com/js-dojo/asp-net-core-mvc-webpack-and-vue-js-update-f10fcc76238c?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f10fcc76238c</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Mon, 01 May 2023 23:04:37 GMT</pubDate>
            <atom:updated>2023-05-01T23:04:37.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>ASP.NET Core MVC, Webpack and Vue.js — Update</h3><p>Hi everyone, after a lot of time, I’m bringing an update on my first model to work with these great tools. I recommend you read <a href="https://medium.com/js-dojo/net-mvc-webpack-and-vue-js-part-1-tools-9227b57d4690">first version</a> because I’ll use equivalent tools configurations to transpile javascript, build sass, and some additionals and updates. Here we’ll use VS2022, Node 18 (I recommend you to use <a href="https://github.com/coreybutler/nvm-windows">nvm on windows</a>)</p><p><a href="https://github.com/luylucas10/mvc-core-webpack">Here</a> you’ll find the repo of this example, let’s work.</p><p>But first: Why? Why not a SPA with an API? Well, some scenarios we want switch techs to produce the same result with less time impact to develop a solution. As a dotnet developer, I really like C# as my primary language, but We know that javascript was made for browsers, but pure javascript is hard and verbose, jquery is old and for simple things, angular and react, far as I know, is just for SPA and I think that has much complexity if We want to build simple apps (I’m not here to say what is better), so why don’t merge the best of ASP.NET (security, performance, productivity) and best of Vue (reactivity)? Well, I hope that you enjoy this solution.</p><p>First of all, we need a project, I’ll use the default ASP.NET Core MVC App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbS9dgHPrEBcMS-SHnQSBA.png" /></figure><p>I’ll use version 7.0 of .NET Framework, but what we’ll do here can be applied in any version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKehHJteWZG3vyBEb_MYxA.png" /></figure><p>Now, we run <em>npm init -y</em> script, with a VS PMC <strong>in root</strong> of the web project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ6BCd60-XXk99somWje-A.png" /></figure><p>This creates a <em>package.json</em> file in project, allowing to us to use NPM packages. Now install the dev dependencies packages:</p><p><em>npm install — save-dev @babel/core @babel/preset-env babel-loader copy-webpack-plugin css-loader glob mini-css-extract-plugin postcss postcss-loader resolve-url-loader sass sass-loader style-loader terser-webpack-plugin vue-loader vue-style-loader vue-template-compiler webpack webpack-assets-manifest webpack-cli webpack-merge</em></p><p>Our project dependencies, just install:</p><p><em>npm install — save bootstrap vue</em></p><p>Now, we’ll configure webpack development and production configs. First we’ll create a common webpack config file (webpack.common.js) in web project root directory:</p><pre>const glob = require(&quot;glob&quot;);<br>const path = require(&quot;path&quot;);<br>const webpack = require(&quot;webpack&quot;);<br>const miniCssExtractPlugin = require(&quot;mini-css-extract-plugin&quot;);<br>const { VueLoaderPlugin } = require(&quot;vue-loader&quot;);<br>const CopyWebpackPlugin = require(&#39;copy-webpack-plugin&#39;);<br><br>const scripts = {<br> // initial point, We use to load layout and base libraries<br> index: &quot;./wwwroot/src/js/index.js&quot;,<br>};<br><br>module.exports = {<br> // load all .js files presents in the directory merging with index<br> entry: glob<br>  .sync(&quot;./wwwroot/src/js/**/*.js&quot;)<br>  .reduce(function (obj, el) {<br>   obj[path.parse(el).name] = `./${el}`;<br>   return obj;<br>  }, scripts),<br> // set output directory, I like to clean every build<br> output: {<br>  path: path.resolve(__dirname, &quot;./wwwroot/dist&quot;),<br>  publicPath: &quot;/dist/&quot;,<br>  clean: true<br> },<br> // set output of webpack build stats<br> stats: {<br>  preset: &quot;none&quot;,<br>  assets: true,<br>  errors: true,<br> },<br> plugins: [<br>  new VueLoaderPlugin(),<br>  // copy all images to output dir<br>  new CopyWebpackPlugin({<br>   patterns: [<br>    {<br>     from: path.resolve(__dirname, &quot;./wwwroot/src/img&quot;),<br>     to: path.resolve(__dirname, &quot;./wwwroot/dist/img&quot;)<br>    },<br>   ],<br>  }<br>  ),<br> ],<br><br> module: {<br>  rules: [<br>   {<br>    // this will load and build all scss, making a css file<br>    test: /\.((sa|sc|c)ss)$/i,<br>    use: [<br>     miniCssExtractPlugin.loader,<br>     &quot;css-loader&quot;,<br>     &quot;resolve-url-loader&quot;,<br>     {<br>      loader: &quot;postcss-loader&quot;,<br>      options: {<br>       postcssOptions: {<br>        plugins: function () {<br>         return [<br>          require(&quot;autoprefixer&quot;)<br>         ];<br>        }<br>       }<br>      }<br>     },<br>     {<br>      loader: &quot;sass-loader&quot;,<br>      options: {<br>       implementation: require(&quot;sass&quot;)<br>      }<br>     }<br>    ]<br>   },<br>   {<br>    // this will load all js files, transpile to es5<br>    test: /\.js$/,<br>    include: path.resolve(__dirname, &#39;./wwwroot/src/js&#39;),<br>    use: {<br>     loader: &quot;babel-loader&quot;,<br>     options: {<br>      presets: [&quot;@babel/preset-env&quot;]<br>     }<br>    }<br>   },<br>   {<br>    //case when sass files have images references, webpack will copy<br>    test: /\.(jpe?g|png|gif|svg)$/,<br>    include: path.resolve(__dirname, &#39;./wwwroot/src/img&#39;),<br>    type: &quot;asset/resource&quot;,<br>    generator: {<br>     filename: &quot;img/[name].[ext]&quot;<br>    }<br>   },<br>   {<br>    test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,<br>    type: &quot;asset/resource&quot;,<br>    generator: {<br>     filename: &quot;fonts/[name].[ext]&quot;<br>    }<br>   },<br>   {<br>    test: /\.vue$/,<br>    loader: &quot;vue-loader&quot;<br>   }<br>  ]<br> },<br><br> resolve: {<br>  alias: {<br>   // use es module vue version<br>   vue: &quot;vue/dist/vue.esm-bundler.js&quot;<br>  }<br> },<br>};</pre><p>Now, let’s create a dev config (webpack.dev.js):</p><pre>const MiniCssExtractPlugin = require(&quot;mini-css-extract-plugin&quot;);<br>const { merge } = require(&quot;webpack-merge&quot;);<br>const common = require(&quot;./webpack.common.js&quot;);<br>const webpack = require(&quot;webpack&quot;);<br>module.exports = merge(common, {<br> mode: &quot;development&quot;,<br> output: {<br>  filename: &quot;js/[name].js&quot;,<br>  pathinfo: false,<br> },<br><br> plugins: [<br>  new MiniCssExtractPlugin({ filename: &quot;css/[name].css&quot; }),<br>  new webpack.DefinePlugin({<br>   __VUE_OPTIONS_API__: true, // If you are using the options api.<br>   __VUE_PROD_DEVTOOLS__: true // If you don&#39;t want people sneaking around your components in production.<br>  }),<br> ],<br><br> devtool: &quot;inline-source-map&quot;,<br><br> optimization: {<br>  removeAvailableModules: false,<br>  removeEmptyChunks: false,<br>  splitChunks: false,<br> },<br>});</pre><p>Now, let’s create a production config (webpack.prd.js):</p><pre>const { merge } = require(&quot;webpack-merge&quot;);<br>const common = require(&quot;./webpack.common.js&quot;);<br>const MiniCssExtractPlugin = require(&quot;mini-css-extract-plugin&quot;);<br>const WebpackAssetsManifest = require(&quot;webpack-assets-manifest&quot;);<br>const webpack = require(&quot;webpack&quot;);<br><br>module.exports = merge(common, {<br> mode: &quot;production&quot;,<br> output: {<br>  filename: &quot;js/[name].[chunkhash].js&quot;,<br>  clean: true<br> },<br> devtool: false,<br> plugins: [<br>  new MiniCssExtractPlugin({ filename: &quot;css/[name].[chunkhash].css&quot; }),<br>  // this plugin generates integrity of files and put in stats file<br>  new WebpackAssetsManifest({<br>   integrity: true,<br>   integrityHashes: [&quot;sha256&quot;]<br>  }),<br>  new webpack.SourceMapDevToolPlugin({<br>   test: /\.((sa|sc|c)ss)$/i,<br>  }),<br>  new webpack.DefinePlugin({<br>   __VUE_OPTIONS_API__: true, // If you are using the options api.<br>   __VUE_PROD_DEVTOOLS__: false // If you don&#39;t want people sneaking around your components in production.<br>  }),<br> ],<br> optimization: {<br>  runtimeChunk: &quot;single&quot;,<br>  splitChunks: {<br>   cacheGroups: {<br>    vendor: {<br>     test: /[\\/]node_modules[\\/]/,<br>     name: &#39;vendors&#39;,<br>     chunks: &#39;all&#39;,<br>    },<br>   },<br>  },<br> },<br>});</pre><p>At this point we have webpack ready to build, now put the scripts builds in <em>package.json</em>. Here we have <em>— json=stats.json</em>, this will generate a <em>stats.json </em>file to us (feel free to change this name). This file will be used to load all builds in our <em>.cshtml</em>:</p><pre>&quot;scripts&quot;: {<br>    &quot;debug&quot;: &quot;webpack --config webpack.dev.js&quot;,<br>    &quot;dev&quot;: &quot;webpack --config webpack.dev.js --json=stats.json --watch --progress&quot;,<br>    &quot;prd&quot;: &quot;webpack --config webpack.prd.js --json=stats.json&quot;<br>  },</pre><p>Let’s make some changes in our app. At <em>wwwroot</em>, delete all directories, create a src directory. Inside src, create a directory for scss files, js files and vue files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*eV7Jntmka7vZJM8c73Ti3g.png" /></figure><p>Executing npm debug script, the dist directory will be create, with just js subdirectory and a empty js file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEjKW0StVHrUzCTFceFarw.png" /></figure><p>Now we’ll create a config for our app loads files. First install:</p><pre>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation&quot; Version=&quot;7.0.5&quot; /&gt;<br>&lt;PackageReference Include=&quot;Newtonsoft.Json&quot; Version=&quot;13.0.3&quot; /&gt;</pre><p>Create a file called something like LoadWebpack.cs in Models Directory. Put the following code in:</p><pre>using Newtonsoft.Json;<br>using Newtonsoft.Json.Linq;<br><br>namespace Webpack.Models;<br><br>public static class LoadWebpack<br>{<br> private static Dictionary&lt;string, Tuple&lt;string, string&gt;&gt; Css { get; } = new();<br> private static Dictionary&lt;string, Tuple&lt;string, string&gt;&gt; Js { get; } = new();<br><br> public static void Load()<br> {<br>  //open stats.json file to read, creating a dictionary of css and js files to read<br>  // in Our .cshtml files;<br>  using var status = File.OpenRead(&quot;stats.json&quot;);<br>  using var streamReader = new StreamReader(status);<br>  using var textReader = new JsonTextReader(streamReader);<br>  var jsonObjects = JObject.Load(textReader);<br><br>  var assetsChunks = jsonObjects[&quot;assetsByChunkName&quot;];<br>  var assets = jsonObjects[&quot;assets&quot;];<br><br>  var item = assets<br>   ?.Select(x =&gt;<br>    new<br>    {<br>     name = x[&quot;name&quot;]?.ToString(),<br>     integrity = x[&quot;info&quot;]?[&quot;integrity&quot;]?.ToString()<br>    })<br>   ?.ToList();<br><br>  foreach (var asset in assetsChunks)<br>  {<br>   var property = (JProperty)asset;<br>   foreach (var value in property.Value.ToObject&lt;string[]&gt;())<br>    if ((value?.StartsWith(&quot;css&quot;) ?? false) &amp;&amp; !Css.ContainsKey(property.Name))<br>     Css.Add(property.Name, new Tuple&lt;string, string&gt;(value, item?.FirstOrDefault(a =&gt; a.name == value)?.integrity!));<br>    else if ((value?.StartsWith(&quot;js&quot;) ?? false) &amp;&amp; !Js.ContainsKey(property.Name))<br>     Js.Add(property.Name, new Tuple&lt;string, string&gt;(value, item?.FirstOrDefault(a =&gt; a.name == value)?.integrity!));<br>  }<br> }<br><br> public static Tuple&lt;string, string&gt; LoadCss(string name)<br> {<br>  if (Css.TryGetValue(name, out var styleFile))<br>  {<br>   Load();<br>   Css.TryGetValue(name, out styleFile);<br>  }<br><br>  return styleFile!;<br> }<br><br> public static Tuple&lt;string, string&gt; LoadJs(string name)<br> {<br>  if (Js.TryGetValue(name, out var scriptFile))<br>  {<br>   Load();<br>   Js.TryGetValue(name, out scriptFile);<br>  }<br><br>  return scriptFile!;<br> }<br>}</pre><p>This class will read <em>stats.json</em> file (flag setted on <em>package.json</em> scripts) to make file paths available.</p><p>In <em>Program.cs </em>we call <em>Load </em>method and call .AddRazorRuntimeCompilation() to reload pages without restart app:</p><pre>using Webpack.Models;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>LoadWebpack.Load();<br><br>// Add services to the container.<br>builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (!app.Environment.IsDevelopment())<br>{<br> app.UseExceptionHandler(&quot;/Home/Error&quot;);<br> // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.<br> app.UseHsts();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br><br>app.UseRouting();<br><br>app.UseAuthorization();<br><br>app.MapControllerRoute(<br>  name: &quot;default&quot;,<br>  pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br><br>app.Run();</pre><p>We’ll create two partial views, one to load css file and one to load js files. First, partial for css (<em>_Styles.cshtml</em>):</p><pre>@model string<br>@if (Model is not null)<br>{<br> var css = LoadWebpack.LoadCss(Model);<br> if (css?.Item2 is not null)<br> {<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;~/dist/@css.Item1&quot; integrity=&quot;@css.Item2&quot; crossorigin=&quot;anonymous&quot;&gt;<br> }<br> else if (css?.Item1 is not null)<br> {<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;~/dist/@css.Item1&quot;&gt;<br> }<br>}</pre><p>And <em>_Scripts.cshtml</em>:</p><pre>@model string<br>@if (Model is not null)<br>{<br> var js = LoadWebpack.LoadJs(Model);<br> if (js?.Item2 is not null)<br> {<br>  &lt;script src=&quot;~/dist/@js.Item1&quot; crossorigin=&quot;anonymous&quot; integrity=&quot;@js.Item2&quot;&gt;&lt;/script&gt;<br> }<br> else if(js?.Item1 is not null)<br> {<br>  &lt;script src=&quot;~/dist/@js.Item1&quot;&gt;&lt;/script&gt;<br> }<br>}</pre><p>Use it in <em>_Layout.cshtml</em> (I already apply this <a href="https://getbootstrap.com/docs/5.3/examples/cover/">bootstrap example</a>):</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot; class=&quot;h-100&quot; data-bs-theme=&quot;auto&quot;&gt;<br>&lt;head&gt;<br> &lt;meta charset=&quot;utf-8&quot;&gt;<br> &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br> &lt;title&gt;@ViewData[&quot;Title&quot;] - Webpack&lt;/title&gt;<br> @await Html.PartialAsync(&quot;_Styles&quot;, &quot;index&quot;)<br> @await RenderSectionAsync(&quot;Styles&quot;, required: false)<br>&lt;/head&gt;<br>&lt;body class=&quot;d-flex h-100 text-center text-bg-dark&quot;&gt;<br> &lt;div class=&quot;cover-container d-flex w-100 h-100 p-3 mx-auto flex-column&quot;&gt;<br>  &lt;header class=&quot;mb-auto&quot;&gt;<br>   &lt;div&gt;<br>    &lt;h3 class=&quot;float-md-start mb-0&quot;&gt;Cover&lt;/h3&gt;<br>    &lt;nav class=&quot;nav nav-masthead justify-content-center float-md-end&quot;&gt;<br>     &lt;a class=&quot;nav-link fw-bold py-1 px-0 active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Home&lt;/a&gt;<br>     &lt;a class=&quot;nav-link fw-bold py-1 px-0&quot; href=&quot;#&quot;&gt;Features&lt;/a&gt;<br>     &lt;a class=&quot;nav-link fw-bold py-1 px-0&quot; href=&quot;#&quot;&gt;Contact&lt;/a&gt;<br>    &lt;/nav&gt;<br>   &lt;/div&gt;<br>  &lt;/header&gt;<br><br>  @RenderBody()<br><br>  &lt;footer class=&quot;mt-auto text-white-50&quot;&gt;<br>   &lt;p&gt;<br>    Cover template for &lt;a href=&quot;https://getbootstrap.com/&quot; class=&quot;text-white&quot;&gt;Bootstrap&lt;/a&gt;, by &lt;a href=&quot;https://twitter.com/mdo&quot; class=&quot;text-white&quot;&gt;@@mdo&lt;/a&gt;.<br>   &lt;/p&gt;<br>  &lt;/footer&gt;<br> &lt;/div&gt;<br><br> @await Html.PartialAsync(&quot;_Scripts&quot;, &quot;index&quot;)<br> @await RenderSectionAsync(&quot;Scripts&quot;, required: false)<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Our home page:</p><pre>@{<br>    ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>&lt;main class=&quot;px-3&quot;&gt;<br> &lt;h1&gt;Cover your page.&lt;/h1&gt;<br> &lt;p class=&quot;lead&quot;&gt;<br>  Cover is a one-page template for building simple and beautiful home pages. Download, edit the<br>  text, and add your own fullscreen background photo to make it your own.<br> &lt;/p&gt;<br> &lt;p class=&quot;lead&quot;&gt;<br>  &lt;a href=&quot;#&quot; class=&quot;btn btn-lg btn-light fw-bold border-white bg-white&quot;&gt;Learn more&lt;/a&gt;<br> &lt;/p&gt;<br>&lt;/main&gt;</pre><p>This BS example brings some css, so, let’s put in our code. In our <em>wwwroot/src/scss/index.scss</em>:</p><pre>@import &quot;bootstrap/scss/bootstrap&quot;;<br><br>.bd-placeholder-img {<br> font-size: 1.125rem;<br> text-anchor: middle;<br> -webkit-user-select: none;<br> -moz-user-select: none;<br> user-select: none;<br>}<br><br>@media (min-width: 768px) {<br> .bd-placeholder-img-lg {<br>  font-size: 3.5rem;<br> }<br>}<br><br>.b-example-divider {<br> width: 100%;<br> height: 3rem;<br> background-color: rgba(0, 0, 0, .1);<br> border: solid rgba(0, 0, 0, .15);<br> border-width: 1px 0;<br> box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);<br>}<br><br>.b-example-vr {<br> flex-shrink: 0;<br> width: 1.5rem;<br> height: 100vh;<br>}<br><br>.bi {<br> vertical-align: -.125em;<br> fill: currentColor;<br>}<br><br>.nav-scroller {<br> position: relative;<br> z-index: 2;<br> height: 2.75rem;<br> overflow-y: hidden;<br>}<br><br>.nav-scroller .nav {<br> display: flex;<br> flex-wrap: nowrap;<br> padding-bottom: 1rem;<br> margin-top: -1px;<br> overflow-x: auto;<br> text-align: center;<br> white-space: nowrap;<br> -webkit-overflow-scrolling: touch;<br>}<br><br>.btn-bd-primary {<br> --bd-violet-bg: #712cf9;<br> --bd-violet-rgb: 112.520718, 44.062154, 249.437846;<br> --bs-btn-font-weight: 600;<br> --bs-btn-color: var(--bs-white);<br> --bs-btn-bg: var(--bd-violet-bg);<br> --bs-btn-border-color: var(--bd-violet-bg);<br> --bs-btn-hover-color: var(--bs-white);<br> --bs-btn-hover-bg: #6528e0;<br> --bs-btn-hover-border-color: #6528e0;<br> --bs-btn-focus-shadow-rgb: var(--bd-violet-rgb);<br> --bs-btn-active-color: var(--bs-btn-hover-color);<br> --bs-btn-active-bg: #5a23c8;<br> --bs-btn-active-border-color: #5a23c8;<br>}<br><br>.bd-mode-toggle {<br> z-index: 1500;<br>}<br><br>/*<br> * Globals<br> */<br><br><br>/* Custom default button */<br>.btn-light,<br>.btn-light:hover,<br>.btn-light:focus {<br> color: #333;<br> text-shadow: none; /* Prevent inheritance from `body` */<br>}<br><br><br>/*<br> * Base structure<br> */<br><br>body {<br> text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);<br> box-shadow: inset 0 0 5rem rgba(0, 0, 0, .5);<br>}<br><br>.cover-container {<br> max-width: 42em;<br>}<br><br><br>/*<br> * Header<br> */<br><br>.nav-masthead .nav-link {<br> color: rgba(255, 255, 255, .5);<br> border-bottom: .25rem solid transparent;<br>}<br><br>.nav-masthead .nav-link:hover,<br>.nav-masthead .nav-link:focus {<br> border-bottom-color: rgba(255, 255, 255, .25);<br>}<br><br>.nav-masthead .nav-link + .nav-link {<br> margin-left: 1rem;<br>}<br><br>.nav-masthead .active {<br> color: #fff;<br> border-bottom-color: #fff;<br>}</pre><p>Import this file in <em>wwwroot/src/js/index.js</em>:</p><pre>import &quot;../scss/index.scss&quot;;<br><br>console.log(&quot;Hello Webpack World&quot;);</pre><p>Run npm debug script and <em>Voilá</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*HD3U_wBTcYgStmo9fQc89Q.png" /></figure><p>If we run our app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT02jS88IhC1h1NY1zv1EQ.png" /></figure><p>WHAAT?! Oks, It was proposital, we run debug scripts, it just builds our files and show, or not, console errors, it doesn’t generate our <em>stats.json</em> file. Remove the <em>— watch</em> flag from <em>dev script</em> in <em>package.json</em> and run it <em>npm run dev</em> again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*433Hlype2_x663vIjb7-SQ.png" /></figure><p>Until now we have:</p><ul><li>Webpack building development SCSS and Javascript version;</li><li>MVC Loading CSS and Javascript file;</li></ul><p>Let’s create some vue SFCs. I’ll create a simple example, but after that, We have Vue full power in our app, being able to use Vue Router, Vuex/Pinia (with localstorage) and (maybe) any Vue Template.</p><p>One more thing before: this example works with ASP.NET resolving routes and auth, not Vue, but, you can configure vue router to resolve the components. Here We work with multipaging and ASP.NET redirects, my goal here is just replace pure javascript e jquery to Vue. Be free to modify for your case.</p><p>In <em>wwwroot/src/vue</em>, create a <em>HomePage.vue</em> component, I put this code in:</p><pre>&lt;template&gt;<br><br> &lt;main class=&quot;px-3&quot;&gt;<br>  &lt;h1&gt;{{message}}&lt;/h1&gt;<br>  &lt;p class=&quot;lead&quot;&gt;<br>   Cover is a one-page template for building simple and beautiful home pages. Download, edit the<br>   text, and add your own fullscreen background photo to make it your own.<br>  &lt;/p&gt;<br>  &lt;p class=&quot;lead&quot;&gt;<br>   &lt;a href=&quot;#&quot; class=&quot;btn btn-lg btn-light fw-bold border-white bg-white&quot;&gt;Learn more&lt;/a&gt;<br>  &lt;/p&gt;<br> &lt;/main&gt;<br><br> <br>&lt;/template&gt;<br>&lt;script&gt;<br><br> export default {<br>  name: &quot;HomePage&quot;,<br>  data() {<br>   return {<br>    message: &quot;Hello Vue&quot;<br>   }<br>  }<br> }<br>&lt;/script&gt;</pre><p>In <em>Views/Home/Index.cshtml</em>, replace the code for this:</p><pre>@{<br> ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>@section Styles{@await Html.PartialAsync(&quot;_Styles&quot;, &quot;home&quot;)}<br>@section Scripts{@await Html.PartialAsync(&quot;_Scripts&quot;, &quot;home&quot;)}<br><br>&lt;div id=&quot;home-app&quot;&gt;&lt;/div&gt;</pre><p>Creates a <em>wwwroot/src/js/home/home.js</em> and put the code in:</p><pre>import { createApp } from &quot;vue&quot;;<br>import HomePage from &quot;../../vue/HomePage.vue&quot;;<br><br>createApp(HomePage).mount(&quot;div#home-app&quot;);</pre><p><em>npm run dev</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i7YqjVpwdydyDMRnRNzNA.png" /></figure><p>So far, so good. Pay attention: we <strong>always need</strong> a javascript file to execute SFC, because we have to set what DOM element the componente will be mounted.</p><p>I want to see production builds. We have a little error in production script, because we didn’t put any images in <em>wwwroot/src/img</em>, Webpack doesn’t build prodution outputs, so put any png, jpeg image in the directory and run <em>npm run prd.</em></p><p>We’ll have two more javascript files: runtime and vendors. Runtime is some webpack scripts to load our modules and vendors is grouping of libs scripts (I recommend you to read this <a href="https://webpack.js.org/guides/">Webpack Guide</a> to understand and maybe tunning this primal configuration).</p><p>In <em>_Layout.cshtml</em>, put two more scripts partials on order:</p><pre> @await Html.PartialAsync(&quot;_Scripts&quot;, &quot;runtime&quot;)<br> @await Html.PartialAsync(&quot;_Scripts&quot;, &quot;vendors&quot;)<br> @await Html.PartialAsync(&quot;_Scripts&quot;, &quot;index&quot;)<br> @await RenderSectionAsync(&quot;Scripts&quot;, required: false)</pre><p>Running the app now, visually nothing changes, but if we inspect the generated html, we can see different files references:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*iR-qMsL7cWsz70871-TQ7g.png" /></figure><p>We didn’t change nothing in the .cshtml files and, in automatic way, we can use hashed css and javascript files in browsers. This helps to change broswer cached files when a new app version is published.</p><p>That’s it, you can explore another world. Maybe in a next story, I’ll bring Pinia with Localstorage and Vue Router. Feel free to make PR in <a href="https://github.com/luylucas10/mvc-core-webpack">this repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f10fcc76238c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/asp-net-core-mvc-webpack-and-vue-js-update-f10fcc76238c">ASP.NET Core MVC, Webpack and Vue.js — Update</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET MVC, Webpack and Vue.js — Final — Vuex.js]]></title>
            <link>https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-final-vuex-js-ece0b377a2b8?source=rss-b23911439ec7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece0b377a2b8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Luy Lucas]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 01:52:25 GMT</pubDate>
            <atom:updated>2019-04-28T01:52:25.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>.NET MVC, Webpack and Vue.js — Final — Vuex.js</h3><h4>In this last story about the subject, I show how to keep the vue state between page reloads</h4><ul><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-part-1-tools-9227b57d4690">Part 1 — Tools;</a></li><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-part-2-project-structure-fa7de8963ede">Part 2 — Project structure;</a></li><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-part-3-npm-packages-4d4af0d6110e">Part 3 — NPM Packages;</a></li><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-part-4-webpack-configuration-843f87c9608c">Part 4 — Webpack Configuration;</a></li><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-part-5-vue-js-7731a3b31e91">Part 5 — Vue.js;</a></li><li><a href="https://medium.com/@luylucas10/net-mvc-webpack-and-vue-js-final-vuex-js-ece0b377a2b8"><strong>Part 6 — Vuex;</strong></a></li></ul><p>Now that we have our application already running with Vue.js, we’ll set a configuration to keep state between pages reloading.</p><p>First, we have to install this npm package</p><blockquote>npm install vuex-persist</blockquote><p>This package will use browser database to store the Vuex state data.</p><p>After install, create a <em>store.js</em> file at root of the <em>~/public/src/js</em>, and put the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*yeOEDz9tS8EcleEcNLPe1w.png" /><figcaption>The store.js code</figcaption></figure><p>Now, we have to import the store in the <em>~/public/src/js/home/index.js</em>, adding the store to the Vue instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Q7yPBV8Gn7HjlDpz4cZRkw.png" /><figcaption>importing of the vuex object to the home vue instance</figcaption></figure><p>Execute <em>npm run build</em> and run debug and see what you built.</p><p>Now, in the <em>store.js</em>, create a new state and a mutation for this state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*WhFE354REffHi39WzYxvgA.png" /></figure><p>In the <em>~/public/src/js/home/index.js</em>, import the mapState from vuex, it’ll map the anotherMessage state in the computed object and we have to create a method that commit the mutations from the store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*wuEIok8jqCYGTSsLk7SFeA.png" /><figcaption>Mapping things from store.js</figcaption></figure><p>Add a button in the Home/Index.cshtml and bind the changeMessage method to the button with v-on:click=“” directive, add a &lt;p&gt; tag that show the anotherMessage state with double mustache sintax and add a link to about page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*n4C1sTBjFcDZRaNiHqxbGw.png" /><figcaption>The Home/Index.cshtml file</figcaption></figure><p>Create a <strong>about </strong>directory in <em>~/public/src/js</em> directory, create a index.js file, import the Vue, the mapState from Vuex and the store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*oDd7X2AXu6s4ajSHZ555BQ.png" /><figcaption>the ~/public/src/about/index.js file</figcaption></figure><p>In the About.cshtml, create a div with the app-about id, and bind the anotherMessage to a &lt;p&gt; tag.</p><blockquote>npm run build</blockquote><p>Run debug, go to home, click on the button and go to about, see what’s happened.</p><p>Now, write your application with your needs. You can create any modules in the ~/public/src/js/&lt;view-name&gt;/&lt;module&gt;.js and import then in the index.js file. Vuex can be modular too, you can read about <a href="https://vuex.vuejs.org/guide/modules.html">here</a>.</p><p>My resources:</p><ul><li><a href="https://www.udemy.com/course/curso-web/">Web Complete Course at Udemy</a> (in portuguese, where I got my major knowledge about javascript and webpack);</li><li><a href="https://www.slightedgecoder.com/2017/05/22/setting-es6-environment-asp-net-mvc-5/">Setting up ES6 Modules for MVC 5</a>;</li><li><a href="https://medium.com/corebuild-software/vue-js-and-net-mvc-b5cede228626">Vue.js and ASP.NET MVC</a>;</li><li><a href="https://alligator.io/vuejs/vuex-persist-state/">Vuex-Persist</a> (I found the references at StackOverflow but I didn’t save the url);</li><li><a href="https://webpack.js.org/">Webpack</a>;</li></ul><p>I want to thank all people which contributes with Vue, Webpack and all js frameworks and libraries. You’re doing a great work. I want to do that someday!</p><p>I appreciate your reading. Share this if it can be useful for you or someone that you know.</p><p>See ya in my next posts!</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece0b377a2b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>