<?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 Michael M. on Medium]]></title>
        <description><![CDATA[Stories by Michael M. on Medium]]></description>
        <link>https://medium.com/@gin_mitch?source=rss-4f1f572735b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KuRKZvQvvDA5L0aThhWQ0Q.jpeg</url>
            <title>Stories by Michael M. on Medium</title>
            <link>https://medium.com/@gin_mitch?source=rss-4f1f572735b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:42:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gin_mitch/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[Access Control and Zero-Knowledge]]></title>
            <link>https://medium.com/@gin_mitch/access-control-and-zero-knowledge-f4f97137d237?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f97137d237</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 08:00:17 GMT</pubDate>
            <atom:updated>2025-03-02T08:00:17.917Z</atom:updated>
            <content:encoded><![CDATA[<p>Previous articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/building-secure-systems-for-modern-applications-9e5a9f59e876">Building Secure Systems for Modern Applications</a><br>• <a href="https://medium.com/@gin_mitch/database-setup-jwt-implementation-api-a0519ceca560">Database Setup, JWT Implementation &amp; API</a><br>• <a href="https://medium.com/@gin_mitch/openapi-and-frontend-058e0e81cb1d">OpenAPI and Frontend</a></p><h3>Recap</h3><p>In the previous parts of the series, we implemented a backend capable of securely authenticating users and a functional frontend application.</p><p>In this part, we will protect our app’s (and users’) data by introducing an access control mechanism and further securing users’ authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxNcmfCH6IYBbOrwlg9OZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sortino">Joshua Sortino</a> on <a href="https://unsplash.com/photos/worms-eye-view-photography-of-ceiling-LqKhnDzSF-8">Unsplash</a></figcaption></figure><h3>Role-Based Access Control</h3><p>If you remember, previously, we intentionally skipped any route validations within the frontend application, so if you open the “/account” page without signing in, two endpoints will be queried:</p><ul><li>The /api/account/check/public will return a successful response</li><li>The /api/account will return an error caused by the &quot;user_not_found&quot; exception</li></ul><p>While this seems correct at first, the issue here is the exception’s origin — that service shouldn’t have been invoked in the first place. What if the data queried by that endpoint didn’t require the user’s ID? This could expose unnecessary information or services.</p><p>Let’s protect that endpoint so that an unauthorized request never reaches it. Remember how we added the user’s role to the token withClaim(claimUserType, userType) and then, in the JwtFilter, put it into the Security Context new SimpleGrantedAuthority(tokenData.getUserType())? This would help us filter requests using Spring&#39;s annotation:</p><pre>@PreAuthorize(&quot;hasAnyAuthority(&#39;admin&#39;, &#39;user&#39;)&quot;)<br>public ResponseEntity&lt;UserInfo&gt; getUser() { ... }<br><br>...</pre><p><em>[AccountController.java]</em></p><p>Here, we marked this endpoint with the @PreAuthorize annotation, asking Spring to check if the user making the request has any of the listed roles. If the criteria don’t match, Spring will entirely prevent the request from reaching this endpoint.</p><p>Since we don’t display any greeting on the account page if the request fails, let’s add one more endpoint for the demonstration:</p><pre>...<br><br>@GetMapping(value = &quot;/check/protected&quot;, produces = MediaType.TEXT_PLAIN_VALUE)<br>@PreAuthorize(&quot;hasAnyAuthority(&#39;admin&#39;, &#39;user&#39;)&quot;)<br>public ResponseEntity&lt;String&gt; getProtected() {<br>    return ResponseEntity.status(HttpStatus.OK)<br>            .body(&quot;This data is available only when signed in.&quot;);<br>}</pre><p><em>[AccountController.java]</em></p><p>Once again, launch the backend and execute npm run api-gen to update our frontend services. As a final touch, query this endpoint along with the public one:</p><pre>public ngOnInit(): void {<br>    this.loadData(this.accountService.getPublic(), this.responsePublic$);<br>    this.loadData(this.accountService.getProtected(), this.responseProtected$);<br>    ...<br>}</pre><p><em>[account.component.ts]</em></p><p>And display the result:</p><pre>&lt;div class=&quot;c-split&quot;&gt;<br>    &lt;span class=&quot;text-split&quot;&gt;Protected endpoint:&lt;/span&gt;<br>    @if (responseProtected$ | async; as response) {<br>    &lt;span class=&quot;text-split&quot;&gt;{{ response }}&lt;/span&gt;<br>    }<br>&lt;/div&gt;</pre><p><em>[account.component.ts]</em></p><p>Now, launch the frontend as well and navigate to the account page manually without signing in. All three endpoints would be queried simultaneously, but only one would return with a successful response (you will see the HTTP status of the protected endpoint, though). But after you sign in, all of them will return something useful.</p><p>In a SaaS platform, for example, protecting sensitive endpoints with access control is essential to ensuring users only access what they’re authorized for, preventing data leaks or misconfiguration vulnerabilities.</p><blockquote><strong><em>Practice</em></strong><em>: Now that you’ve set up access control, try experimenting with additional roles or creating different endpoint restrictions. How would you allow specific users to access something, and what are the potential pitfalls?</em></blockquote><h3>Zero-Knowledge</h3><p>With all the basics set up, I may now introduce you to the zero-knowledge password storage. The idea behind this is very simple: I, as the owner of the web service, take full responsibility for the user’s personal information, if applicable, but I don’t want to have even the slightest chance to know their passwords and be responsible for credentials in case of a leakage.</p><p>Okay, but how do we achieve this? We need to store some kind of credentials anyway to let users in, and the answer would be double hashing.</p><p>Hashing passwords with modern algorithms already prevents storing raw passwords in the database. Even if attackers gain access to the hashes, reversing them would be computationally, and financially, expensive. Double hashing adds an extra layer by ensuring that even if someone knows the hashed format, they still won’t have access to the raw data unless they’re willing to spend even more resources on brute-forcing. Let’s see the implementation.</p><p>First, we will add a dependency to the frontend app npm i hash.js, and since this package is a CommonJS one, we let Angular know that we&#39;re OK with that:</p><pre>...<br>&quot;options&quot;: {<br>    ...<br>    &quot;allowedCommonJsDependencies&quot;: [&quot;hash.js&quot;]<br>}</pre><p><em>[project.json]</em></p><p>Now, all we have to do is slightly change the login (and signup) form submission logic:</p><pre>const formValue = this.form.getRawValue();<br>const hashedValue = sha256()<br>    .update(formValue.password || &#39;&#39;)<br>    .digest(&#39;hex&#39;);<br><br>this.authService<br>    .login({ body: { username: formValue.username, password: hashedValue } })</pre><p><em>[login.component.ts]</em></p><p>This will invalidate all existing password hashes stored in the database, so if you would like to introduce this to an existing production application, you would need to implement a smooth migration strategy.</p><p>Finally, let’s make sure that network errors or brute-force attacks won’t mess with our database performance by adding an extra validation to the “password” field:</p><pre>...<br><br>@Size(min = 64, max = 64, message = &quot;Incorrect password format&quot;)<br>@Pattern(regexp = &quot;^[\\da-f]+$&quot;, message = &quot;Incorrect password format&quot;)<br>private String password;</pre><p><em>[LoginRequest.java]</em></p><p>Now, the only time our application knows the real user’s password is the moment between the form input and page navigation. The backend does not know the original value at any point, and you may see it for yourself using the Network tab of Dev Tools.</p><h3>Conclusion</h3><p>In this part, we’ve added more security measures to the application, namely access control and zero-knowledge password storage.</p><p>As usual, all the code fragments in this article are in the <a href="https://github.com/GinMitch/knox-auth/tree/4-knox-rbac">companion repository</a>, which you can clone or browse online. If you feel any area needs further clarification in the article itself, feel free to point in the comments, and I’ll do my best.</p><p>Up next is the multi-factor authentication and the seemingly complex (not really) WebAuthn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f97137d237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAPI and Frontend]]></title>
            <link>https://medium.com/@gin_mitch/openapi-and-frontend-058e0e81cb1d?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/058e0e81cb1d</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 12:29:08 GMT</pubDate>
            <atom:updated>2025-03-02T08:05:15.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Previous articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/building-secure-systems-for-modern-applications-9e5a9f59e876">Building Secure Systems for Modern Applications</a><br>• <a href="https://medium.com/@gin_mitch/database-setup-jwt-implementation-api-a0519ceca560">Database Setup, JWT Implementation &amp; API</a></p><h3>Recap</h3><p>In the previous part of the series, we configured the PostgreSQL database, created the User entity, implemented JSON Web Tokens, and secured our API.</p><p>In this part, we will add two more methods in the backend for convenience and demonstration and then build the frontend application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0BPNzg8ky5dxu2Ort-ZHw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@karengrigorean">Karen Grigorean</a> on <a href="https://unsplash.com/photos/a-person-pointing-at-a-large-display-of-pictures-9D6UlCW38Ss">Unsplash</a></figcaption></figure><h3>Logout &amp; User Information</h3><p>Before jumping to the frontend part, we should take one step ahead and think about how we will test everything without using the browser’s Dev Tools. We authenticate users with cookies, and of course, we have to be able to remove them when they sign out, so we introduce the “logout” endpoint:</p><pre>...<br><br>@PostMapping(value = &quot;/logout&quot;)<br>public ResponseEntity&lt;String&gt; logout(<br>        HttpServletResponse res<br>) {<br>    CookiesResult result = this.authService.logout();<br><br>    res.addCookie(result.getResult()[0]);<br>    res.addCookie(result.getResult()[1]);<br>    return ResponseEntity.status(HttpStatus.OK).build();<br>}</pre><p><em>[AuthController.java]</em></p><p>The AuthService’s method just passes the request down to the JwtService, where the logic, yet again, is quite simple. By returning cookies with the same parameters, i.e., name and path, but zeroed expiration time, we’re essentially revoking them in the browser the moment it processes the response.</p><pre>...<br><br>public @NonNull Cookie[] revokeCookies() {<br>    return new Cookie[]{<br>            this.createAuth(&quot;&quot;, 0),<br>            this.createMarker(&quot;&quot;, 0)<br>    };<br>}</pre><p><em>[JwtServiceImpl.java]</em></p><p>As I said in the previous article, you should implement a revocation mechanism that blacklists tokens until they expire. But, since this is a demo application, we will only revoke cookies for anyone, even if they’re not yet authenticated.</p><p>Next, to test that we have signed in successfully and everything is good and well, let’s create an endpoint that returns the current user’s information.</p><pre>...<br><br>@GetMapping(value = &quot;/&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public ResponseEntity&lt;UserInfo&gt; getUser() {<br>    UserInfo user = this.accountService.getUser();<br>    return ResponseEntity.status(HttpStatus.OK)<br>            .body(user);<br>}</pre><p><em>[AccountController.java]</em></p><p>And the corresponding service:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class AccountServiceImpl implements AccountService {<br><br>    private final UserRepo userRepo;<br><br>    public UserInfo getUser() {<br>        String principal = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();<br>        Optional&lt;User&gt; userOptional = this.userRepo.findFirstById(UUID.fromString(principal));<br>        if (userOptional.isEmpty()) {<br>            throw new RuntimeException(&quot;user_not_found&quot;);<br>        }<br><br>        User user = userOptional.get();<br>        return new UserInfo(user.getUsername());<br>    }<br>}</pre><p><em>[AccountServiceImpl.java]</em></p><p>Note how we retrieve the principal (or, in JWT terms, the subject). When the HTTP request hits the application, it’s passed through several mechanisms within Spring, as well as our JwtFilter we implemented earlier. It populates the context so we can retrieve this information across the app.</p><h3>OpenAPI</h3><p>Since we’re done creating endpoints for all operations we need right now, let’s add <a href="https://www.openapis.org/what-is-openapi">OpenAPI</a> to our application. Doing so allows our clients or other teams to discover the endpoints quickly and potentially generate their code, just like we would do in a moment. In larger projects, this drastically reduces errors and time spent debugging integrations.</p><p>We will start by adding a dependency that does pretty much everything for us:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>    &lt;artifactId&gt;springdoc-openapi-starter-webmvc-api&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><em>[pom.xml]</em></p><p>And set it up with just a few lines of configuration properties. We will enable the generation and make it human-readable by enabling “pretty print,” but since we won’t need the Swagger UI, let’s turn it off.</p><pre>springdoc:<br>  api-docs:<br>    enabled: true<br>  swagger-ui:<br>    enabled: false<br>  writer-with-default-pretty-printer: true</pre><p><em>[application.yaml]</em></p><p>One last thing would be adding tags to our controllers:</p><pre>@Tag(name = &quot;auth&quot;)<br>public class AuthController {<br>    ...<br>}</pre><p><em>[AuthController.java]</em></p><p>We’re all set, you may now start the app and open <em>http://localhost:25100/api/v3/api-docs</em> in the browser.</p><h3>Frontend Models</h3><p>Creating services and models manually sounds easy enough, but not when you have a huge application with over a hundred endpoints and their contracts change from time to time. Of course, there are tools to automate the models’ generation, and for Angular, we will even create services in just a few lines of code.</p><p>First, we’ll need a dependency <em>npm i -D @public-js/ng-openapi-gen</em> with a few lines of configuration:</p><pre>{<br>  ...<br>  &quot;input&quot;: &quot;http://localhost:25100/api/v3/api-docs&quot;,<br>  &quot;output&quot;: &quot;src/api/generated&quot;<br>}</pre><p><em>[openapi.json]</em></p><p>And a handy npm script to run it:</p><pre>...<br>&quot;scripts&quot;: {<br>  ...<br>  &quot;api-gen&quot;: &quot;ng-openapi-gen --config ./openapi.json&quot;<br>}</pre><p><em>[package.json]</em></p><p>Now, all we need to do is successfully start the backend and, while it’s running, execute <em>npm run api-gen</em> to get ourselves all models and services in TypeScript that are ready to use.</p><p>With the services in place, we need to plug them into the application. Let’s start by creating a proxy configuration to trick the browser into thinking that our backend is served at the exact same domain and port and avoid CORS issues:</p><pre>{<br>  &quot;/api/**&quot;: {<br>    &quot;target&quot;: &quot;http://127.0.0.1:25100/api&quot;,<br>    &quot;secure&quot;: false,<br>    &quot;changeOrigin&quot;: true,<br>    &quot;pathRewrite&quot;: {<br>      &quot;^/api&quot;: &quot;&quot;<br>    }<br>  }<br>}</pre><p><em>[proxy-local.json]</em></p><p>We should also make sure that running the <em>npm run start</em> command uses this file every time:</p><pre>...<br><br>&quot;configurations&quot;: {<br>  ...<br>  &quot;development&quot;: {<br>    ...<br>    &quot;proxyConfig&quot;: &quot;./proxy-local.json&quot;<br>  }<br>}</pre><p><em>[project.json]</em></p><p>Now that we’re able to communicate with the backend during development, we will set up the actual application to work with the generated code. You may either hard-code this path or leverage the power of Angular’s file replacement technique, which I highly recommend using.</p><pre>export const environment = { apiRootUrl: &#39;/api&#39; };</pre><p><em>[environment.ts]</em></p><p>Finally, provide the app with the generated API module. To do so, we need to start utilizing Angular’s HttpClient, pass our root URL to the <a href="https://angular.dev/guide/di/dependency-injection-providers#value-providers-usevalue">Dependency Injection Token</a>, and provide our app with the generated services coupled by a module.</p><pre>providers: [<br>    ...<br>    provideHttpClient(),<br>    { provide: API_ROOT_URL_TOKEN, useValue: environment.apiRootUrl },<br>    importProvidersFrom(ApiModule),<br>]</pre><p><em>[app.config.ts]</em></p><h3>User Interface</h3><p>Let’s get to the most creative part of this series — the user interface, aka frontend.</p><p>We will start by outlining our navigation routes. Note that we don’t add any router filters, so we can easily navigate between these pages during development.</p><pre>export const appRoutes: Route[] = [<br>    { path: &#39;account&#39;, component: AccountComponent },<br>    { path: &#39;login&#39;, component: LoginComponent },<br>    { path: &#39;signup&#39;, component: SignupComponent },<br>    { path: &#39;&#39;, pathMatch: &#39;full&#39;, redirectTo: &#39;login&#39; },<br>];</pre><p><em>[app.routes.ts]</em></p><p>Moving on to the signup page, start by creating an Angular reactive form. It has the same validation rules for the username field as the backend, so we can catch errors faster. Also, we won’t even bother validating the “repeat_password” control, because we will check if it matches the password anyway.</p><pre>public readonly form = this.fb.nonNullable.group({<br>    username: this.fb.nonNullable.control&lt;string&gt;(&#39;&#39;, [Validators.required, Validators.pattern(&#39;[\\da-zA-Z_-]+&#39;)]),<br>    password: this.fb.nonNullable.control&lt;string&gt;(&#39;&#39;, [Validators.required, Validators.minLength(6)]),<br>    repeat_password: this.fb.nonNullable.control&lt;string&gt;(&#39;&#39;, [Validators.required]),<br>});</pre><p><em>[signup.component.ts]</em></p><p>Next, we add some HTML to render this form. Not only will our forms be visually pleasing, but they will also be accessible. For the user’s convenience, we will explicitly disable the spellcheck and automatic capitalization, even though we look users up in a case-insensitive manner.</p><p>Also, since the CSS code is provided in the repo, I will not mention it here at all. You’re welcome to either re-use it or write your own from scratch.</p><pre>&lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;submit()&quot; class=&quot;c-form&quot;&gt;<br>    &lt;div class=&quot;w-input&quot;&gt;<br>        &lt;label for=&quot;username&quot; class=&quot;f-label&quot;&gt;Username&lt;/label&gt;<br>        &lt;input<br>            formControlName=&quot;username&quot;<br>            id=&quot;username&quot;<br>            type=&quot;text&quot;<br>            autocomplete=&quot;username&quot;<br>            autocapitalize=&quot;off&quot;<br>            autocorrect=&quot;off&quot;<br>            spellcheck=&quot;false&quot;<br>            class=&quot;f-input&quot;<br>        /&gt;<br>    &lt;/div&gt;<br><br>    ...<br>&lt;/form&gt;</pre><p><em>[signup.component.ts]</em></p><p>Then, because we need some logic to be done before the data is sent, we will add a method to mark the form “dirty” if the validation fails and add an error message. It will then send the request and handle its response.</p><pre>...<br><br>public submit(): void {<br>    if (!this.form.valid) {<br>        this.form.markAsDirty();<br>        this.errors$.next(&#39;The form is invalid&#39;);<br>        this.form.valueChanges.pipe(first()).subscribe(() =&gt; this.errors$.next(&#39;&#39;));<br>        return;<br>    }<br><br>    if (this.form.value.password !== this.form.value.repeat_password) {<br>        this.errors$.next(&quot;Passwords don&#39;t match&quot;);<br>        this.form.valueChanges.pipe(first()).subscribe(() =&gt; this.errors$.next(&#39;&#39;));<br>        return;<br>    }<br><br>    const formValue = this.form.getRawValue();<br><br>    this.authService<br>        .signup({ body: { username: formValue.username, password: formValue.password } })<br>        .pipe(catchError(this.handleHttpError))<br>        .subscribe({<br>            next: () =&gt; this.router.navigate([&#39;account&#39;]),<br>            error: (code: string) =&gt; this.errors$.next(signupErrors[code] ?? signupErrors[&#39;_&#39;]),<br>        });<br>}</pre><p><em>[signup.component.ts]</em></p><p>For a seamless experience, let’s add the navigation link that adds the username to the router state.</p><pre>&lt;div class=&quot;c-split&quot;&gt;<br>    &lt;span class=&quot;text-split&quot;&gt;Already have an account?&lt;/span&gt;<br>    &lt;a routerLink=&quot;/login&quot; [state]=&quot;{ username: form.value.username }&quot; class=&quot;link-split&quot;&gt;Sign in&lt;/a&gt;<br>&lt;/div&gt;</pre><p><em>[signup.component.ts]</em></p><p>The login page looks very alike, so I’ll skip ahead and add a method that pulls the username from the router state and applies it to the form:</p><pre>...<br><br>public ngOnInit(): void {<br>    const navUsername = this.router.lastSuccessfulNavigation?.extras?.state?.[&#39;username&#39;];<br>    if (navUsername) {<br>        this.form.patchValue({ username: navUsername });<br>    }<br>}</pre><p><em>[login.component.ts]</em></p><p>How is it convenient? Easy: imagine yourself as a user who tried to sign up on a website and got a message that this user already exists. You will likely remember that some time ago you already signed up here, and when you click the “sign in” link, the login form will greet you with that username already in place. Same applies in the other direction.</p><p>So, what about those two endpoind we added at the beginning of this part? We will use them for the account page. Let’s (try to) load some data when this page is opened:</p><pre>...<br><br>public ngOnInit(): void {<br>    this.loadData(this.accountService.getPublic(), this.responsePublic$);<br><br>    this.accountService.getUser().subscribe({<br>        next: (user) =&gt; this.userInfo$.next(user),<br>    });<br>}</pre><p><em>[account.component.ts]</em></p><p>And greet the user by their username, if they’re signed in (remember, we don’t have router filters):</p><pre>@if (userInfo$ | async; as userInfo) {<br>&lt;div class=&quot;c-title&quot;&gt;<br>    &lt;h2 class=&quot;text-title&quot;&gt;Hello, {{ userInfo.username }}&lt;/h2&gt;<br>&lt;/div&gt;<br>}</pre><p><em>[account.component.ts]</em></p><p>That’s it, you may now spin up everything and see how it works for yourself!</p><blockquote><strong>TODO</strong>: Add the drumroll sound.</blockquote><h3>Conclusion</h3><p>In this part we’ve implemented a fully-functional accessible frontend based on auto-generated API models from the OpenAPI document.</p><p>As a reminder, all the code fragments in this article are in the <a href="https://github.com/GinMitch/knox-auth/tree/3-openapi-fe">companion repository</a>, which you can clone or browse online. If you feel any area needs further clarification in the article itself, feel free to point in the comments, and I’ll do my best.</p><p>We can now proceed to more complex and even more exciting functionality like access control, multi-factor authentication, and WebAuthn.</p><p>Next articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/access-control-and-zero-knowledge-f4f97137d237">Access Control and Zero-Knowledge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=058e0e81cb1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Setup, JWT Implementation & API]]></title>
            <link>https://medium.com/@gin_mitch/database-setup-jwt-implementation-api-a0519ceca560?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0519ceca560</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 05:36:21 GMT</pubDate>
            <atom:updated>2025-03-02T08:04:16.095Z</atom:updated>
            <content:encoded><![CDATA[<p>Previous articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/building-secure-systems-for-modern-applications-9e5a9f59e876">Building Secure Systems for Modern Applications</a></p><h3>Foundation</h3><p>For this series, our launchpad will be two separate applications: the Spring Boot-based backend and the Angular-based frontend. I am deliberately omitting their initialization because this code is just boilerplate, already in the companion repository, and you will likely find a better guide covering all the basics.</p><p>I am also deliberately omitting a lot of code here to focus on explaining key concepts, leaving repetitive or obvious parts outside of the article. You will find a complete working implementation in the repo, where everything is broken down into separate commits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIMydD49tv7OOL8G0Qjr4A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico">Kaleidico</a> on <a href="https://unsplash.com/photos/two-people-drawing-on-whiteboard-26MJGnCM0Wc">Unsplash</a></figcaption></figure><p>Before we create any application logic, we’ll need a database to store user information. While Spring provides out-of-the-box support for an H2 in-memory database, which self-destructs when the application is shut down, for this project, let’s focus on a more real-world implementation using PostgreSQL. The setup is as simple as possible:</p><pre>image: postgres:16-alpine<br>environment:<br>  POSTGRES_DB: knox_dev_db<br>  POSTGRES_USER: knox_dev_user<br>  POSTGRES_PASSWORD: knox_dev_pass<br>  ...<br>volumes:<br>  - ./dbdev:/var/lib/postgresql/data<br>ports:<br>  - &#39;25101:5432&#39;</pre><p><em>[docker-compose.dev.yml]</em></p><p>This configuration pulls the lightweight Alpine-based image of PostgreSQL and sets up essential environment variables like the database name, username, and password. We also specify a custom port and tell Docker to persist container data right beside the file.</p><p>Don’t forget to add the “volume” directory to the “gitignore” file because PostgreSQL spawns a lot of files that we don’t want to be committed to the repository:</p><pre>dbdev/*</pre><p><em>[.gitignore]</em></p><p>Yes, committing credentials to shared storage and even storing them in plaintext is risky, but since this file is used solely to spin up a <strong>local</strong> database, it’s acceptable as long as you never use these credentials in production.</p><p>Now, let’s tell our backend how to connect to the database:</p><pre>datasource:<br>  driver-class-name: org.postgresql.Driver<br>  url: jdbc:postgresql://localhost:25101/knox_dev_db<br>  username: knox_dev_user<br>  password: knox_dev_pass<br>jpa:<br>  generate-ddl: true<br>  hibernate:<br>    ddl-auto: update<br>  ...</pre><p><em>[application.yml]</em></p><p>This configuration uses a JDBC connection string to connect to the database, which is pretty standard and allows us to pass only one variable during deployment instead of three. We also enable DDL generation to let Spring automatically update the database schema as we go.</p><p>At this point, you may already start the application with the database connected to it, but nothing much will happen yet. Let’s now create an entity that will represent users in our app; it will serve as the foundation for managing users, their credentials, and other relevant information.</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br><br>    @NonNull<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.UUID)<br>    @Column(name = &quot;id&quot;, nullable = false, updatable = false)<br>    private UUID id;<br><br>    @Setter<br>    @NonNull<br>    @Column(name = &quot;username&quot;, nullable = false, unique = true, length = 64)<br>    @JdbcTypeCode(SqlTypes.VARCHAR)<br>    private String username;<br><br>    ...<br>}</pre><p><em>[User.java]</em></p><p>Here, we use UUIDs for the user ID to prevent guessing and to allow potential future scaling of the application into a large distributed system without major refactoring. The username field is unique and capped at 64 characters to balance out flexibility and performance; the password field is capped at the same length because of bcrypt limitations.</p><blockquote><strong><em>Pro Tip</em></strong><em>: Always use UUIDs for primary keys in distributed systems to avoid ID collisions and enhance security by preventing sequential patterns.</em></blockquote><p>Now, let’s create a repository for this entity, which, thanks to Spring Data’s Derived Query Methods, we can declare as an interface without writing custom implementations:</p><pre>public interface UserRepo extends JpaRepository&lt;User, UUID&gt; {<br><br>    Optional&lt;User&gt; findFirstById(@NonNull UUID id);<br><br>    Optional&lt;User&gt; findFirstByUsernameLikeIgnoreCase(@NonNull String username);<br>}</pre><p><em>[UserRepo.java]</em></p><p>Finally, leverage the power of Spring Data so it will wire this entity and repository automatically:</p><pre>@EntityScan({&quot;gin.knox.jpa&quot;})<br>@EnableJpaRepositories({&quot;gin.knox.jpa&quot;})<br>public class KnoxApplication {<br>    ...<br>}</pre><p><em>[KnoxApplication.java]</em></p><h3>JWT Implementation</h3><p>Now, let’s move on to implementing <a href="https://jwt.io/introduction">JSON Web Tokens</a>.</p><p>First, we need to add a few dependencies that handle many things behind the scenes:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.auth0&lt;/groupId&gt;<br>    &lt;artifactId&gt;java-jwt&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><em>[pom.xml]</em></p><p>Next, create a class to interchange the token information within our app. As a reminder, these tokens have only a few mandatory claims and are very extensible, but in our case, we’ll focus on the subject, which is the user’s ID, and the role:</p><pre>public class TokenData implements Serializable {<br><br>    @NonNull<br>    private String userId;<br><br>    @Nullable<br>    private String userType;<br>}</pre><p><em>[TokenData.java]</em></p><p>The core of the JWT implementation is the private key used for signing the token. If you’ve worked with production environments before, you probably know that providing secure non-text data to the application is painful. Tools like HashiCorp Vault are used in big tech to securely store various credentials, so we’ll generate our keys as single-line text strings.</p><pre>openssl genrsa -out ${pathPem} 2048;<br>keyPkcs8=$(openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in ${pathPem} | tr -d &#39;\n&#39;);<br>...<br>keyX509=$(openssl rsa -pubout -in ${pathPem} | tr -d &#39;\n&#39;);<br>...</pre><p><em>[jwk-gen.sh]</em></p><p>Add the resulting keys to application.yaml (again, that&#39;s okay if these keys are used solely in your local environment). Technically, you may set your key ID to be anything you like; this random value would be useful when you need to rotate your keys, but that&#39;s a topic for a different article.</p><pre>jwt:<br>  issuer: knoxdev<br>  key:<br>    id: ...<br>    pkcs8: ...<br>    x509: ...</pre><p><em>[application.yml]</em></p><p>Next, we’ll create an interface for the JwtDataProvider based on the RSAKeyProvider and provide methods to retrieve the issuer and keys for JWT handling:</p><pre>public interface JwtDataProvider extends RSAKeyProvider {<br><br>    @NonNull<br>    String getIssuer();<br>}</pre><p><em>[JwtDataProvider.java]</em></p><p>And then implement it using the @Value annotation to inject variables from the configuration and the postConstruct method, where our base64-encoded keys are decoded into the respective formats:</p><pre>@Service<br>public class JwtDataProviderImpl implements JwtDataProvider {<br>    ...<br><br>    @Value(&quot;${jwt.key.x509}&quot;)<br>    private String keyX509;<br><br>    @PostConstruct<br>    private void postConstruct() throws Exception {<br>        KeyFactory keyFactory = KeyFactory.getInstance(&quot;RSA&quot;);<br><br>        this.publicKey =<br>                (RSAPublicKey)<br>                        keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(this.keyX509)));<br>        ...<br>    }<br>}</pre><p><em>[JwtDataProviderImpl.java]</em></p><p>Now that we have our key set up, let’s implement the JwtService itself:</p><pre>@RequiredArgsConstructor<br>public class JwtServiceImpl implements JwtService {<br>    ...<br>}</pre><p><em>[JwtServiceImpl.java]</em></p><p>At the core of this service will be an issuing method that sets the token’s validity time, and consequentially the session length, the user ID and their role, our key ID, and the issuer name.</p><pre>...<br><br>private @Nullable String issueToken(@NonNull String userId, @NonNull String userType) {<br>    try {<br>        return JWT.create()<br>                .withKeyId(this.dataProvider.getPrivateKeyId())<br>                .withIssuer(this.dataProvider.getIssuer())<br>                .withExpiresAt(Instant.now().plusSeconds(sessionTtl))<br>                .withSubject(userId)<br>                .withClaim(claimUserType, userType)<br>                .sign(this.algorithm);<br>    } catch (Exception ex) {<br>        return null;<br>    }<br>}</pre><p><em>[JwtServiceImpl.java]</em></p><blockquote><strong><em>Best Practice</em></strong><em>: Set reasonable expiration times for JWTs; in production, consider implementing a token blacklist or revocation mechanism to prevent compromised tokens from being reused.</em></blockquote><p>This method would be called by another one that places the resulting token in a cookie. In fact, we will create two cookies — one with the token itself, which would be inaccessible for JavaScript, and one allowing the frontend to know whether the user is signed in or not.</p><pre>public @Nullable Cookie[] issueCookies(@NonNull String userId, @NonNull String userType) {<br>    String token = issueToken(userId, userType);<br>    return token == null ? null : new Cookie[]{<br>            this.createAuth(token, sessionTtl),<br>            this.createMarker(&quot;1&quot;, sessionTtl - 10)<br>    };<br>}<br><br>private @NonNull Cookie createAuth(@Nullable String value, int maxAge) {<br>    Cookie cookie = new Cookie(authCookieName, value);<br>    cookie.setPath(&quot;/&quot;);<br>    cookie.setHttpOnly(true); // &quot;false&quot; for the marker<br>    cookie.setMaxAge(maxAge);<br>    return cookie;<br>}<br><br>...</pre><p><em>[JwtServiceImpl.java]</em></p><p>Parsing the token is a multi-step process as well: we extract the cookie, verify the token’s signature, and only then retrieve its claims. We will check that the token contains the user type as well.</p><pre>...<br><br>public @Nullable TokenData parseCookies(Cookie[] cookies) {<br>    Optional&lt;Cookie&gt; cookieMaybe =<br>            cookies == null<br>                    ? Optional.empty()<br>                    : Arrays.stream(cookies)<br>                    .filter(cookie -&gt; cookie.getName().equals(authCookieName))<br>                    .findFirst();<br><br>    TokenData tokenData = cookieMaybe.isEmpty() || cookieMaybe.get().getValue().isBlank()<br>            ? null<br>            : this.parseToken(cookieMaybe.get().getValue());<br><br>    return tokenData == null || tokenData.getUserType() == null ? null : tokenData;<br>}<br><br>private @Nullable TokenData parseToken(@NonNull String token) {<br>    try {<br>        DecodedJWT jwt = this.verifier.verify(token);<br>        return new TokenData(jwt.getSubject(), jwt.getClaim(claimUserType).asString());<br>    } catch (Exception ex) {<br>        return null;<br>    }<br>}</pre><p><em>[JwtServiceImpl.java]</em></p><p>Create a RequestFilter that will authenticate our users upon each request:</p><pre>@Component<br>@RequiredArgsConstructor<br>public class JwtFilter extends OncePerRequestFilter {<br><br>    @Override<br>    protected void doFilterInternal(...) {<br>        TokenData tokenData = this.jwtService.parseCookies(request.getCookies());<br><br>        SecurityContextHolder.getContext()<br>                .setAuthentication(<br>                        tokenData == null<br>                                ? new UsernamePasswordAuthenticationToken(&quot;&quot;, null, null)<br>                                : new UsernamePasswordAuthenticationToken(<br>                                tokenData.getUserId(),<br>                                null,<br>                                Collections.singleton(new SimpleGrantedAuthority(tokenData.getUserType()))));<br><br>        filterChain.doFilter(request, response);<br>        SecurityContextHolder.getContext().setAuthentication(null);<br>    }<br>}</pre><p><em>[JwtFilter.java]</em></p><p>Note that in this implementation, every request is considered authenticated, you may tailor this filter to your own specifics.</p><p>Finally, let’s enable WebSecurity and set up the SecurityFilterChain:</p><pre>@Configuration<br>@EnableWebSecurity<br>@EnableMethodSecurity<br>@RequiredArgsConstructor<br>public class SecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain filterChain(@NonNull HttpSecurity http) throws Exception {<br>        http.addFilterBefore(this.jwtFilter, UsernamePasswordAuthenticationFilter.class);<br><br>        http.authorizeHttpRequests(customizer -&gt; customizer.anyRequest().authenticated());<br><br>        http.sessionManagement(customizer -&gt; customizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br><br>        http.csrf(AbstractHttpConfigurer::disable);<br>        http.cors(Customizer.withDefaults());<br><br>        return http.build();<br>    }<br><br>    ...<br>}</pre><p><em>[SecurityConfig.java]</em></p><p>While we’ve disabled CSRF for simplicity, keep in mind that this is an <a href="https://portswigger.net/web-security/csrf">important security measure</a> to protect against certain types of attacks.</p><h3>API</h3><p>Now that we have implemented JWTs for issuing and validating tokens, the next logical step is to expose this functionality through a REST API so we can at least try the code above using Postman.</p><p>First off, let’s circle back to the security configuration and set up the password encoder that we will use later in the process. We don’t want to store passwords in plain text.</p><pre>...<br><br>@Bean<br>public PasswordEncoder passwordEncoder() {<br>    return new BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion.$2B, 10);<br>}</pre><p><em>[SecurityConfig.java]</em></p><p>I like using simple yet handy generic classes like this one for internal stuff:</p><pre>@Getter<br>@AllArgsConstructor<br>public abstract class AnyResult&lt;T&gt; {<br><br>    private String error;<br><br>    private T result;<br>}</pre><p><em>[AnyResult.java]</em></p><p>It allows us to create classes like this, for example:</p><pre>public class CookiesResult extends AnyResult&lt;Cookie[]&gt; {<br><br>    public CookiesResult(String error, Cookie[] result) {<br>        super(error, result);<br>    }<br><br>    public static CookiesResult error(String error) {<br>        return new CookiesResult(error, null);<br>    }<br><br>    public static CookiesResult success(Cookie[] result) {<br>        return new CookiesResult(null, result);<br>    }<br>}</pre><p><em>[CookiesResult.java]</em></p><p>We will also need some public-facing data transfer objects (aka DTOs):</p><pre>public class SignupRequest {<br><br>    @NotEmpty<br>    @Size(min = 6, max = 64, message = &quot;Incorrect username format&quot;)<br>    @Pattern(regexp = &quot;^[\\da-zA-Z_-]+$&quot;, message = &quot;Incorrect username format&quot;)<br>    private String username;<br><br>    @ToString.Exclude<br>    @NotEmpty<br>    @Size(min = 6, max = 64, message = &quot;Incorrect password format&quot;)<br>    private String password;<br><br>    private boolean admin;<br>}</pre><p><em>[SignupRequest.java]</em></p><p>Here, we provide the same length limits for the username and password, add minimal requirements and some validation for usernames.</p><blockquote><strong><em>TODO</em></strong><em>: Should I mention that adding the “admin” flag for something other than a demonstration is a bad idea?</em></blockquote><p>Let’s tie everything together with a service to process login and signup. The “login” method is quite simple: it checks the user’s credentials and issues JWT cookies if the credentials are valid.</p><pre>@Service<br>@RequiredArgsConstructor<br>public class AuthServiceImpl implements AuthService {<br><br>    ...<br><br>    public CookiesResult login(@NonNull LoginRequest request) {<br>        Optional&lt;User&gt; userOptional = this.userRepo.findFirstByUsernameLikeIgnoreCase(request.getUsername());<br>        if (userOptional.isEmpty()) {<br>            return CookiesResult.error(&quot;user_not_found&quot;);<br>        }<br><br>        User user = userOptional.get();<br>        if (!this.passwordEncoder.matches(request.getPassword(), user.getPassword())) {<br>            return CookiesResult.error(&quot;password_mismatch&quot;);<br>        }<br><br>        return CookiesResult.success(<br>                this.jwtService.issueCookies(<br>                        user.getId().toString(),<br>                        user.getType().toString()<br>                ));<br>    }<br><br>    ...<br>}</pre><p><em>[AuthServiceImpl.java]</em></p><p>And finally, a REST controller. You may implement the service logic right in the controller, but I prefer to keep them as simple as possible, so we’ll pass the request to the service and handle the output.</p><pre>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>@RequiredArgsConstructor<br>public class AuthController {<br><br>    @PostMapping(value = &quot;/login&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;String&gt; login(<br>            @RequestBody @Valid @NotNull LoginRequest request,<br>            HttpServletResponse res<br>    ) {<br>        CookiesResult result = this.authService.login(request);<br>        if (result.getError() != null) {<br>            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result.getError());<br>        }<br><br>        res.addCookie(result.getResult()[0]);<br>        res.addCookie(result.getResult()[1]);<br>        return ResponseEntity.status(HttpStatus.OK).build();<br>    }<br><br>    ...<br>}</pre><p><em>[AuthController.java]</em></p><h3>Conclusion</h3><p>We’ve taken a hands-on approach to building a robust authentication system. From configuring PostgreSQL, to creating the User entity, to implementing JWTs and securing REST API, each component plays its role.</p><p>At this point, our application can:</p><ul><li>Store users in the database with the hashed passwords</li><li>Handle their signup and login</li><li>Validate usernames and passwords</li><li>Issue JWTs and authenticate requests</li></ul><p>Again, all the code fragments in this article are in the <a href="https://github.com/GinMitch/knox-auth/tree/2-db-api">companion repository</a>, which you can clone or browse online. If you feel any area needs further clarification in the article itself, feel free to point in the comments, and I’ll do my best.</p><p>In the next articles, we will move on to the frontend part and then dive into more complex stuff to secure our users’ data as much as possible.</p><p>Next articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/openapi-and-frontend-058e0e81cb1d">OpenAPI and Frontend</a><br>• <a href="https://medium.com/@gin_mitch/access-control-and-zero-knowledge-f4f97137d237">Access Control and Zero-Knowledge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0519ceca560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Secure Systems for Modern Applications]]></title>
            <link>https://medium.com/@gin_mitch/building-secure-systems-for-modern-applications-9e5a9f59e876?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5a9f59e876</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 04:04:08 GMT</pubDate>
            <atom:updated>2025-03-02T08:03:10.796Z</atom:updated>
            <content:encoded><![CDATA[<p>The importance of secure authentication in modern applications has grown exponentially in the last decade and continues to rise. The security of your personal information, private messages, photos, contacts, bank transactions, and much more is at stake whenever you use any online service. While some corporations build their income on top of security, the vast majority of companies, regardless of size, are susceptible to cyber threats, as demonstrated by the recent increase in data breaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucttJ8pxNotoLV0Avo8tXg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kaip">Kai Pilger</a> on <a href="https://unsplash.com/photos/closeup-photo-of-street-go-and-stop-signage-displaying-stop-1k3vsv7iIIc">Unsplash</a></figcaption></figure><p>In this series of articles, I will cover various approaches to storing users’ credentials and create a small, yet secure, application to demonstrate them. Rather than targeting a general audience, these articles are aimed at architects and developers, for whom they will be exceptionally useful.</p><p>The technology stack I’ve chosen is fairly standard — PostgreSQL, Java with Spring, and Angular. While these technologies are popular, the concepts and approaches discussed in the series can apply to any modern stack.</p><p>Before we move on, let’s refresh some key knowledge:</p><p><strong>Authentication</strong> is the process of verifying the identity of a user or system. For example, when a user signs in, the system checks if the credentials are correct.</p><p><strong>Authorization</strong>, on the other hand, is the process of determining the user’s or system’s permissions. For example, a signed-in user might be able to view and edit their own data if they’re a “regular” user, or edit anyone’s data if they have “elevated” permissions.</p><p>While these processes are often discussed together, they’re distinct and entirely different, although interconnected. To use an analogy, if this were a concert, <strong>authentication</strong> would be the validation of your ticket, and <strong>authorization</strong> would be moving to your assigned seating zone.</p><p>Setting aside intentional data leaks, where someone with access to user data “dumps” or exports it, the majority of breaches occur due to poor authentication or authorization practices, whether it’s weak password policies, outdated cryptographic algorithms, or what’s commonly called <a href="https://owasp.org/Top10/A01_2021-Broken_Access_Control/">“Broken Access Control”</a>.</p><p>To mitigate some of these vulnerabilities, weak passwords can be addressed by implementing Multi-Factor Authentication (MFA), also known as the “six-digit code from an email or app,” which can be easily integrated into systems of any size.</p><p>Commonly used authorization models include:</p><ul><li><strong>Role-Based Access Control (RBAC)</strong>: Pre-defined user roles and their access scope.</li><li><strong>Attribute-Based Access Control (ABAC)</strong>: Access is granted based on various attributes such as device type, user group, or file type.</li><li><strong>Discretionary Access Control (DAC)</strong>: Provides granular permissions with flexibility in exchange for increased complexity.</li></ul><p>One of today’s techniques to secure authentication and minimize data leakages is using advanced hashing algorithms like bcrypt and Argon2 for secure password storage and to prevent brute force attacks. These algorithms are computationally intensive, requiring a substantial amount of power to encrypt passwords, but also making brute force attacks against the resulting hashes extremely difficult — potentially taking <a href="https://www.hivesystems.com/blog/are-your-passwords-in-the-green">days or even years</a> to decrypt a single password with cutting-edge technologies.</p><p>As mentioned earlier, MFA mitigates the risks of weak cryptography by requiring users to provide a “second factor” for signing in. The first factor is something the user knows — their password. The second factor is something they possess, such as a trusted device, a smartphone with an app, or a secure token. But we’ll get to that later in the series.</p><p>Server-side password hashing is good enough to protect user accounts in case the database gets leaked, but we can enhance security tenfold by implementing the zero-knowledge approach. This improvement is why our app will be called “Knox.”</p><p>In the following articles, I will describe in detail and implement:</p><ul><li><strong>Database design</strong> to store and manage user accounts</li><li><strong>Classic approach</strong> to password storage</li><li><strong>Frontend application</strong> (because an API alone won’t cut it)</li><li><strong>RBAC</strong> with Spring</li><li><strong>Improved approach</strong> to password storage</li></ul><p>After we’ve laid the groundwork, we’ll dive into more advanced topics like:</p><ul><li><strong>MFA</strong>, with proper time-based implementation</li><li><strong>WebAuthn</strong>, for a cutting-edge authentication flow</li><li><strong>OAuth2</strong>, to implicitly sign users up</li></ul><p>By following the series, you’ll not only gain a fully functional backend with a GitHub repository included but also priceless knowledge. As a bonus, you’ll have a neatly designed frontend with a wonderful user experience, crafted especially for this series by a friend of mine <a href="https://www.linkedin.com/in/andriiryzhankov/">Andrii</a>.</p><p>Next articles of the Knox series:<br>• <a href="https://medium.com/@gin_mitch/database-setup-jwt-implementation-api-a0519ceca560">Database Setup, JWT Implementation &amp; API</a><br>• <a href="https://medium.com/@gin_mitch/openapi-and-frontend-058e0e81cb1d">OpenAPI and Frontend</a><br>• <a href="https://medium.com/@gin_mitch/access-control-and-zero-knowledge-f4f97137d237">Access Control and Zero-Knowledge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5a9f59e876" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Alternatives: Are There Better Options Than JSON?]]></title>
            <link>https://medium.com/@gin_mitch/exploring-alternatives-are-there-better-options-than-json-acd4905ac980?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd4905ac980</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[messagepack]]></category>
            <category><![CDATA[protobuf]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 16:43:20 GMT</pubDate>
            <atom:updated>2024-02-29T17:29:52.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*gLTaafXpt-CDKFFiMTfefg.jpeg" /></figure><p>A while back, I stumbled upon a captivating article titled “<a href="https://medium.com/data-science-community-srm/json-is-incredibly-slow-heres-what-s-faster-ca35d5aaf9e8">JSON is incredibly slow: Here’s What’s Faster!</a>” It almost immediately caught my attention because, let’s face it, who doesn’t like shiny trinkets that make their apps run faster? But as I dug deeper, something felt off. So, I decided to not only take another look at these alternatives but also put them to the test.</p><p>Here are the key points I’d like to focus on and discuss: JSON has serialization overhead, offers a limited set of data types, and is bloated and too verbose, so there are at least four supposedly faster alternative exchange formats to use.</p><p>Let’s kick things off with the basics. No format can eliminate serialization overhead, given the internet’s reliance on various transfer protocols for serialized data. We can try to optimize whatever we want, but unless there’s an alternative to HTTP itself, we’ll be serializing data back and forth.</p><p>Now, onto the alternatives mentioned in the article: Protocol Buffers (protobuf), MessagePack (msgpack), BSON, and Apache Avro. I would exclude BSON and Avro from this experiment as they cater to more niche use cases, so applying them to a typical client-server exchange might prove challenging even for a simple playground app.</p><p>One thing mentioned is JSON’s lack of binary data and functions support. Here’s where all the alternatives shine, as they are binary. However, none of the suggested formats still offer functions. Don’t get me wrong, but why overcomplicate things and pass functions? Doing so will not only disperse the business logic of an application but also introduce unnecessary complexity because the receiving end, whether it’s a client-side part running on JavaScript or another service created in a different language, might be unable to execute such functions either way, the sender will be responsible for creating a function in a language foreign to itself.</p><p>Next up is verbosity. With most applications split into backend and frontend components, each can and has its own bugs. Consider what an experienced QA engineer familiar with the project enough and aware of some technical details does when they find a problem and need to file a Jira issue: they open DevTools, look through the data received from the backend, and assign the corresponding label. Swapping out JSON, or XML for that matter, for a binary format will make it harder for both QA engineers and developers to trace issues. So developers will have to use breakpoints to investigate even the tiniest issue, which wouldn’t take much time, but you know how problems sometimes pile up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*-2F7lt13yI5ogfktIZvQpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*jKVqMg5McZYG17EhJPuYrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ouQ7G374YAOoAIzMfZFVyg.png" /><figcaption>A side-by-side comparison of JSON, msgpack, and protobuf responses</figcaption></figure><p>Let’s imagine that we weighed all the risks and prepared automated tests of all sorts, but the question remains: do we truly need an alternative to JSON, or is it doing just fine? I take software benchmarks with a grain of salt, often seeing them as a part of marketing, just like the battery life in fancy smartphone presentations. That’s why if I can’t get some good reviews, I roll up my sleeves, set up playgrounds, and try to replicate real-life conditions. Who cares how fast a protocol can serialize data if the roundtrip time is still the same?</p><p>Here are the results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f32732a1751003899c18fb09a52236/href">https://medium.com/media/f8f32732a1751003899c18fb09a52236/href</a></iframe><p>Evidently, protobuf is a winner regarding medium-sized requests, at least in transfer size, which is crucial for clients with poor internet connection. But if you’ve noticed the gaps in the table, you got to the juiciest part — missing measurements. But why so?</p><p>Countless times, I’ve encountered a nice piece of software that either had no examples whatsoever or the ones provided were so unhelpful that I spent hours trying to make things work. The same goes for protobuf and msgpack — both lack solid working examples. Sure, Spring supports protobuf <a href="https://spring.io/blog/2015/03/22/using-google-protocol-buffers-with-spring-mvc-based-rest-services">out of the box</a>, and there are indeed <a href="https://github.com/thomasdarimont/spring-boot-protobuf-example/blob/master/src/main/java/demo/CustomerRestController.java">good examples</a> and <a href="https://www.baeldung.com/spring-rest-api-with-protocol-buffers">even guides</a> on how to start using <a href="https://github.com/making/spring-mvc-msgpack-sample/blob/master/src/main/java/com/example/App.java">either of them</a>, but a closer look at the table reveals a significant issue — the absence of POST requests. It’s not that Spring can’t handle them; it’s just incredibly tedious to implement. Even though Java is not my primary skill, I’ve spent about 20 hours trying to crack that nut.</p><p>Yet I’m grateful for the open-source software we already have and that there are potential alternatives to JSON, but if you’re putting something out there and expecting others to use it, please at least provide some basic and, most importantly, working examples.</p><p>How do companies like Okta and LinkedIn make it all tick? One might assume they’ve got deep pockets to throw at such challenges, but unfortunately, not all of us can afford that luxury. That’s why I invite you to take part in building a one-stop collection of working examples, making these technologies more accessible to those with fewer resources. If you can contribute, you’re more than welcome to the repo: <a href="https://github.com/GinMitch/better-than-json">https://github.com/GinMitch/better-than-json</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd4905ac980" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic translations in Angular made possible]]></title>
            <link>https://medium.com/angular-in-depth/dynamic-translations-in-angular-made-possible-5eeed8466696?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eeed8466696</guid>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 17:57:37 GMT</pubDate>
            <atom:updated>2024-02-29T17:27:51.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj8gqt3-P8GVXnrKEaBepw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@splashabout">Nareeta Martin</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h4>A practical guide to implement lazy-loaded translations</h4><p>If you have ever dealt with internationalization (or “i18n” for short) in Angular or is about to implement it, you may stick with the <a href="https://angular.io/guide/i18n-overview">official guide</a> which is awesome, use third-party packages that might be hard to debug or choose an alternative path which I will describe below.</p><p>One of the common pitfalls when using i18n are large translation files size and inability to split them in order to hide parts of your application from prying eyes. Some solutions like Angular built-in implementation are really powerful and SEO compatible but require a lot of preparation and do not support switching languages on the fly in development mode (which was <a href="https://stackoverflow.com/q/60683954/3909488">causing troubles</a> at least in version 9); other solutions like <a href="https://github.com/ngx-translate/core">ngx-translate</a> require you to install several packages and still don’t support splitting up a single language (update: in fact, ngx-translate supports this).</p><p>While there is no “magic wand” out there for this complex feature that supports everything and fits everyone, here is another way of implementing translations that might fit your needs.<br>Enough with the introduction, I promised this would be a practical guide, so let’s jump straight into it.</p><h3>Preparing the basics</h3><p>The first step is to create a type for languages that will be used across the app:</p><pre>export type LanguageCode = &#39;en&#39; | &#39;de&#39;;</pre><p>One of the loved Angular features is Dependency Injection that does a lot for us — let’s utilize it for our needs. I would also like to spice things up a little by using NgRx for this guide but if you don’t use it in your project, feel free to replace it with a simple BehaviorSubject.</p><p>As an optional step that will make further development with NgRx easier, create a type for DI factories:</p><pre>export type Ti18nFactory&lt;Part&gt; = (store: Store) =&gt; Observable&lt;Part&gt;;</pre><h3>Creating translation files</h3><h4>General strings</h4><p>Suppose we have some basic strings that we’d like to use across the app. Some simple yet common things that are never related to a specific module, feature or library, like “OK” or “Back” buttons.<br>We will place these strings in “core” module and start doing so with a simple interface that will help us not to forget any single string in out translations:</p><pre>export interface I18nCore {<br>  errorDefault: string;<br>  language: string;<br>}</pre><blockquote>Just to be clear, this interface does not guarantee that all the strings will be actually translated but the TypeScript compiler (and your IDE) will raise an error “TS2741” if you forget to include any string in your “lang” files.</blockquote><p>Moving on to the implementation for the interface and for this snippet it’s vitally important that I provide an example file path which in this case would be libs/core/src/lib/i18n/lang-en.lang.ts:</p><pre>export const lang: I18nCore = {<br>  errorDefault: &#39;An error has occurred&#39;,<br>  language: &#39;Language&#39;,<br>};</pre><p>To reduce code duplication and get the most out of the development process, we’ll also create a DI factory. Here’s a working example utilizing NgRx (again, this is completely optional, you may use BehaviorSubject for this):</p><pre>export const I18N_CORE =<br>  new InjectionToken&lt;Observable&lt;I18nCore&gt;&gt;(&#39;I18N_CORE&#39;);<br><br>export const i18nCoreFactory: Ti18nFactory&lt;I18nCore&gt; =<br>  (store: Store): Observable&lt;I18nCore&gt; =&gt; <br>    (store as Store&lt;LocalePartialState&gt;).pipe(<br>      select(getLocaleLanguageCode),<br>      distinctUntilChanged(),<br>      switchMap((code: LanguageCode) =&gt;<br>        import(`./lang-${code}.lang`)<br>          .then((l: { lang: I18nCore }) =&gt; l.lang)<br>      ),<br>    );<br><br>export const i18nCoreProvider: FactoryProvider = {<br>  provide: I18N_CORE,<br>  useFactory: i18nCoreFactory,<br>  deps: [Store],<br>};</pre><p>Obviously, the getLocaleLanguageCode selector will pick the language code from Store.</p><p>Don’t forget to include translation files into your compilation as they are not being referenced directly thus will not be automatically included. For that, locate the relevant “tsconfig” (the one that lists “main.ts”) and add the following to the “include” array:</p><pre>&quot;../../libs/core/src/lib/i18n/*.lang.ts&quot;</pre><p>Note that the file path here includes a wildcard so that all your translations will be included at once. Also, as a matter of taste, I like to prefix similar files which pretty much explains why the example name ([prefix]-[langCode]<strong>.lang.ts</strong>) looks so weird.</p><h4>Module-specific strings</h4><p>Let’s do the same for any module, so we can see how translations will be loaded separately in the browser. To keep it simple, this module would be named “tab1”.</p><p>Again, start with the interface:</p><pre>export interface I18nTab1 {<br>  country: string;<br>}</pre><p>Implement this interface:</p><pre>export const lang: I18nTab1 = {<br>  country: &#39;Country&#39;,<br>};</pre><p>Include your translations into compilation:</p><pre>&quot;../../libs/tab1/src/lib/i18n/*.lang.ts&quot;</pre><p>And optionally create a DI factory which would look literally the same as previous but with another interface.</p><h3>Providing translations</h3><p>I prefer to reduce the amount of providers so “core” translations will be listed in AppModule only:</p><pre>providers: [i18nCoreProvider],</pre><p>Any other translation should be provided in the relevant modules only — either in lazy-loaded feature modules or, if you follow the SCAM pattern, in component modules:</p><pre>@NgModule({<br>  declarations: [TabComponent],<br>  imports: [CommonModule, ReactiveFormsModule],<br>  providers: [i18nTab1Provider],<br>})<br>export class TabModule {}</pre><p>Also note the elegance of utilizing pre-made FactoryProviders instead of adding objects here.</p><p>Inject the tokens in a component.ts:</p><pre>constructor(<br>  @Inject(I18N_CORE)<br>  public readonly i18nCore$: Observable&lt;I18nCore&gt;,<br>  @Inject(I18N_TAB1)<br>  public readonly i18nTab1$: Observable&lt;I18nTab1&gt;,<br>) {}</pre><p>And finally, wrap component.html with ng-container and a simple ngIf statement:</p><pre>&lt;ng-container *ngIf=&quot;{<br>    core: i18nCore$ | async,<br>    tab1: i18nTab1$ | async<br>  } as i18n&quot;&gt;<br>    &lt;p&gt;{{ i18n.core?.language }}&lt;/p&gt;<br>    &lt;p&gt;{{ i18n.tab1?.country }}: n/a&lt;/p&gt;<br>&lt;/ng-container&gt;</pre><h3>Checking out the result</h3><p>Let’s run this and see if this actually works and more importantly how exactly would these translations be loaded. I created a simple demo app consisting of two lazy-loaded Angular modules, so you may clone and experiment with it. But for now, here are the actual screenshots of DevTools:</p><figure><img alt="Screenshot of the Network tab in Chrome DevTools" src="https://cdn-images-1.medium.com/max/1024/1*3I-9050lAqo2hbfhFc9B9Q.png" /><figcaption>This is the initial page load in development mode; note the two `.js` files at the very end — we created these in a previous section.</figcaption></figure><figure><img alt="Screenshot of the Network tab in Chrome DevTools" src="https://cdn-images-1.medium.com/max/1024/1*l-C12GQ6_i_Y3M0y5hQEUA.png" /><figcaption>This is what it looks like when language is being switched. The Network tab has been reset for demonstration purposes.</figcaption></figure><figure><img alt="Screenshot of the Network tab in Chrome DevTools" src="https://cdn-images-1.medium.com/max/1024/1*vqvEVTwHSM2u5hN-3BlRJg.png" /><figcaption>And this is the result of switching to the second lazy tab.</figcaption></figure><h4>Benefits</h4><ul><li>With this solution you would be able but not obliged to split your translations into several files in any way that you need;</li><li>It’s reactive, which means that being implemented correctly it provides your users with a seamless experience;</li><li>It does not require you to install anything that doesn’t ship with Angular out of the box;</li><li>It’s easily debuggable and fully customizable as it would be implemented directly in your project;</li><li>It supports complex locale resolutions like relating on browser language, picking up regional settings from user account upon authorization and overriding with a user-defined language — and all this without a single page reload;</li><li>It also supports code completion in modern IDEs.</li></ul><h4>Drawbacks</h4><ul><li>As these translation files will not be included in assets, they should actually be transpiled which will slightly increase the build time;</li><li>It requires you to create a custom utility or use a third-party solution to exchange your translations with a localization platform;</li><li>It might not work really well with search engines without proper server-side rendering.</li></ul><h4>GitHub</h4><p>Feel free to experiment with the fully working example that is available in <a href="https://github.com/GinMitch/ng-lazy-i18n">this repository</a>.<br>Stay positive and create great apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eeed8466696" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/dynamic-translations-in-angular-made-possible-5eeed8466696">Dynamic translations in Angular made possible</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Farewell, Moment.js!]]></title>
            <link>https://medium.com/@gin_mitch/farewell-moment-js-b3bfd99a6422?source=rss-4f1f572735b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3bfd99a6422</guid>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[date]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael M.]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 15:14:06 GMT</pubDate>
            <atom:updated>2024-02-29T17:26:51.404Z</atom:updated>
            <content:encoded><![CDATA[<p>On September 15, 2020 Moment.js maintainers’ team <a href="https://github.com/moment/momentjs.com/commits/master/docs/moment/-project-status/00-intro.md">stated</a> that one of the world’s most popular JavaScript date library has come to an end.</p><p>It doesn’t need any introduction: according to <a href="https://www.npmjs.com/package/moment">NPM</a>, as of September 2020, it has over <strong>14 million </strong>downloads weekly and more than 46000 dependent open source packages. Moment.js has been around since 2011, but its developers have their own reasons to shut down its active support, which also includes immutability and support for “tree shaking”.</p><p>There’s no need to whine about it but a good reason to take a look at its successors. Obviously, I must tell you that you don’t have to immediately scoop through all of your projects and replace Moment.js; if there are not many places where you use it, go ahead and upgrade but <strong>since now anything you start working on should probably not use it</strong> anymore.</p><p>Here is an overview comparison of several date libraries which are recommended as a feasible replacement. We’ll stick to TypeScript as an increasingly popular language used by a lot of projects (I mean, there are really a lot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*sSPSdbdeeSAF60otRF9rOw.png" /></figure><p>To begin with, let’s create a pretty basic React app, so we can jump start this journey and see the results immediately:<br>yarn create react-app play-date — template typescript</p><h3>Moment.js</h3><p>Let’s take a look at <a href="https://momentjs.com/">Moment.js</a> and see how simple it is to start using it (or should I now say “was”?).</p><p>First thing we need before using Moment.js in any project is to install it:<br>npm i moment or yarn add moment</p><p>Then import it in a component and you’re good to go:<br>import moment from &#39;moment&#39;;</p><p><strong>Date as object</strong><br>const test1 = new Date(&#39;2018–01–16&#39;); // Date</p><p>First, we need to convert it:<br>const obj1 = moment(test1); // Moment<br>That’s it — nice and simple! Moment.js takes a Date object “as is” and turns it into its own object, so we could operate on it.</p><p>And if we need to know what year is inside, then we could easily get it:<br>obj1.year(); // number</p><p>Or count how many days have passed since then:<br>moment().diff(obj1, &#39;days&#39;); // number</p><p><strong>Date as string</strong><br>const test2 = &#39;2016–07–20&#39;; // string</p><p>Convert it:<br>moment(test2); // Moment<br>Moment.js also takes a string “as is” so you should only care about its format.<br>Though Moment doesn’t restrict you with some special format, it may not recognize some real junk.</p><h3>Day.js</h3><p>Then we move on to the Moment’s nearest successor — <a href="https://day.js.org/">Day.js</a>. If you ever used Moment.js, it should be really easy to replace it with Day.js, it’s not exactly the same but still worth a try.</p><p>Start using Day.js by adding it to your project:<br>npm i dayjs or yarn add dayjs</p><p>Then import it:<br>import dayjs from &#39;dayjs&#39;;</p><p>Even to those of you who have never heard of Moment before the two previous lines should ring a bell as if you’ve seen this before. And you’d be right to say that it looks exactly like Moment’s installation and import.</p><p><strong>Date as object</strong><br>const test1 = new Date(&#39;2018–01–16&#39;); // Date</p><p>Day.js might not be a drop-in replacement for Moment.js but it gives you pretty similar API and uses the same concept of turning everything into its own object.</p><p>Convert it:<br>const obj1 = dayjs(test1); // Dayjs</p><p>And if we need to know what year is inside, then we just get it:<br>obj1.year(); // number</p><p>Or simply count how many days have passed since then:<br>dayjs().diff(obj1, &#39;day&#39;); // number</p><blockquote>The thing about using Moment.js is that you could count <em>days</em> or <em>years</em> as well as <em>day</em> or <em>year</em> — that doesn’t matter at all. We couldn’t say the same about Day.js, but on the other hand that’s the price you pay for having a really lightweight library.</blockquote><p><strong>Date as string</strong><br>const test2 = &#39;2016–07–20&#39;; // string</p><p>And again we need to convert it. Day.js as well as Moment.js will parse any string given its ISO 8601. But if you want to parse anything different from that, you must provide it with the desired format:<br>dayjs(test2, &#39;YYYY-MM-DD&#39;); // Dayjs</p><h3>Luxon</h3><p>Our next contestant gives us a subtle hint that its core maintainers is nearly the same as Moment’s.</p><p>Take the usual step and add <a href="https://moment.github.io/luxon/">Luxon</a> to your project:<br>npm i luxon or yarn add luxon</p><p>Back off a little bit. Remember we decided to go on with TypeScript? Well, Luxon in contrast to the other libraries doesn’t ship with its own type definitions, so your modern IDE should scream about when you try to import it. Here’s the way to add TypeScript support:<br>npm i @types/luxon or yarn add @types/luxon</p><p>Then you may proceed to another usual step:<br>import { DateTime } from &#39;luxon&#39;;</p><p><strong>Date as object</strong><br>const test1 = new Date(&#39;2018–01–16&#39;); // Date</p><p>If you think we should wrap (or convert) the date to use it then you’re right:<br>const obj1 = DateTime.fromJSDate(test1); // DateTime<br>Rather than Moment.js, Luxon will not provide you with a single “entry point” to do it. Refer to its guide or use code completion to parse your date.</p><p>Get the year value back:<br>obj1.toFormat(&#39;yyyy&#39;); // string</p><blockquote><em>Here we get result as string because </em>toFormat()<em> could give us nearly anything with the token parameter.</em></blockquote><p>Count how many days have passed since then:<br>DateTime.fromJSDate(new Date()).diff(obj1, &#39;days&#39;).as(&#39;days&#39;); // number<br>The syntax is trying really hard to look similar to Moment.js, but it’s a way longer than I personally like and it gives you an awfully precise result.</p><p><strong>Date as string</strong><br>const test2 = &#39;2016–07–20&#39;; // string</p><p>And again we need to convert it using the corresponding method. Though, we could’ve used <em>fromFormat()</em> if this string was not ISO 8601 but let’s stick with <em>fromISO()</em> for now:<br>DateTime.fromISO(test2); // DateTime</p><h3>date-fns</h3><p>To move on to the next library, we need to add <a href="https://date-fns.org/">date-fns</a> just as usual:<br>npm i date-fns or yarn add date-fns</p><p>And here comes its first pitfall — you could not import it like Moment.js or Luxon, each of date-fns’ functions should be added to the import statement separately thus you can not use the benefits of code completion.<br>It requires you to know which function you need or refer to its guide to find the right one:<br>import { differenceInDays, getYear } from &#39;date-fns&#39;;</p><p><strong>Date as object</strong><br>const test1 = new Date(&#39;2018–01–16&#39;); // Date</p><p>This library is based on so-called “helper functions” which rely on native Date object manipulations, which is really great. Therefore, we need no conversion to use it right away!</p><p>Let’s get a year from it again:<br>getYear(test1); // number</p><p>And count how many days have passed since then:<br>differenceInDays(new Date(), test1); // number</p><p><strong>Date as string</strong><br>const test2 = &#39;2016–07–20&#39;; // string</p><p>Unfortunately, date-fns could not recognize the string format for us so to parse it we must explicitly provide the string format which is not the point if your project is well-documented and consistent:<br>parse(test2, &#39;yyyy-MM-dd&#39;, new Date()); // Date</p><p>All code samples here <a href="https://github.com/GinMitch/farewell-moment-js">available on GitHub</a> within the React app.</p><p>I must say that this quick overview of Moment’s possible replacements doesn’t make a claim to be a full guide to these libraries or a full list of “What should I use instead of Moment.js?”.<br>If you know better tools — please let everyone know by mentioning them in the comments.</p><p>Originally posted on <a href="https://dev.to/mullinsmikey/farewell-moment-js-bd3">dev.to</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3bfd99a6422" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>