Tuesday, December 1, 2026

Spring Authorization Server: from zero to a working OIDC provider

Part 2 of the OIDC series. This is the piece everything else hangs off: standing up a real authorization server with Spring Authorization Server (SAS), and learning where the framework ends and your responsibility begins.

What SAS gives you for free

Drop spring-boot-starter-oauth2-authorization-server on the classpath, register a client, and you immediately get the full protocol surface:

  • /.well-known/openid-configuration — discovery, generated correctly
  • /oauth2/authorize, /oauth2/token, /oauth2/jwks, /oauth2/introspect, /oauth2/revoke, /userinfo
  • Authorization Code + PKCE, Refresh Token, Client Credentials grants
  • A consent screen when a client asks for scopes the user hasn't approved

The honest surprise: the protocol endpoints are the easy 20%. SAS is deliberately a protocol engine, not a product — everything around the endpoints is yours to build.

The four repositories that make it real

SAS's default wiring is in-memory — restart and every client, token, and consent evaporates. Persistence means backing four contracts with real storage (JDBC implementations ship with SAS; Flyway migrates the schema):

  • RegisteredClientRepository → oauth2_registered_client — who may ask for tokens, how, and which grant types/scopes they're allowed
  • OAuth2AuthorizationService → oauth2_authorization — every issued token's server-side record (this is what makes revocation work)
  • OAuth2AuthorizationConsentService → oauth2_authorization_consent — "alice approved demo-web for api:read", remembered
  • Your own UserDetailsService → users/authorities — SAS has no user store; you bring it

What nobody warns you about

The gaps between "running SAS" and "running an IdP":

  • Signing keys. SAS generates an ephemeral RSA key at boot — restart invalidates every token in flight. Production needs keys in a table (oidc_signing_keys), wrapped under a KEK env var, with scheduled rotation and a JWKS read cache that keeps serving the last good set through a DB blip.
  • The sub claim. The obvious mapping — username as sub — is a latent account-confusion bug. sub must be an immutable identifier (UUID column, backfilled by migration); the username stays in preferred_username.
  • Two security domains, not one. Your IdP has a browser surface (login form, admin UI — session cookies, CSRF on) and a protocol surface (token endpoints, admin API — stateless, Basic/bearer, CSRF off, 401 not redirect). Mixing them is how "CSRF disabled for convenience" becomes an actual hole.
  • Client auth method matters. client_secret_post puts secrets in request bodies — which land in access logs. Register clients with client_secret_basic only, and migrate old rows to match.
  • Rate limiting is on you. Every credential endpoint (/login, /oauth2/token, /introspect, /userinfo) is a brute-force surface. Per-IP throttling — Redis-backed if you run replicas, per-instance otherwise — isn't optional.

The dev-loop trick that pays for itself

A dev profile on embedded H2 with seeded data — demo users (alice/password), a confidential web client, an M2M service client — means the entire login roundtrip is one mvn spring-boot:run away. It also keeps the prod profile honest: prod gets a startup validator that refuses to boot on missing env vars rather than silently falling back to dev secrets.

Verifying it end to end

Once the provider runs, the first real test is a full authorization-code roundtrip against the relying party (Part 3):

  1. Browser hits the client app → redirected to /oauth2/authorize
  2. Login form → consent screen → redirect back with ?code=
  3. Client exchanges code at /oauth2/token → ID token + access token
  4. /userinfo returns sub = UUID, preferred_username = alice

Watching your own server complete that handshake is the moment the protocol stops being folklore.

Next: the other side of the handshake — building the relying party, and what Spring Security's OAuth2 client handles vs. what it leaves to you.

Building your own OIDC provider: what the server side actually teaches you

Nobody needs to build their own identity provider. Keycloak, Auth0, Entra ID — the mature options are right there. I built one anyway, and it's the most instructive side project I've run in years. This post is the map of what I built and why; the rest of the series goes deep on each piece.

The itch

I've integrated with OIDC providers plenty of times — configured redirect URIs, validated JWTs, cursed at claim mappings. But integrating with a black box teaches you the client half of the protocol and leaves the server half as folklore. What does the authorization server actually do between /authorize and /token? Where do refresh tokens live? What breaks when you rotate signing keys? I wanted to know by building, not by reading.

What got built

A small but complete OIDC ecosystem, five deployable pieces:

  • provider — an authorization server on Spring Authorization Server: registered clients, users, consent, token issuance, JWKS, an admin UI and admin API, Flyway-managed schema.
  • client — a relying-party web app on Spring Security's OAuth2 client: the classic login dance, server-side sessions, Thymeleaf.
  • resource — an edge gateway that validates JWTs it didn't issue: JWKS resolution, route-level authorization, trusted-header propagation, rate limiting.
  • sample-webapp — a "third-party" RP: what an external developer integrating with my IdP actually experiences — login, consent, calling the gateway with the user's token.
  • sample-m2m — machine-to-machine: client_credentials flow end to end.

Plus the plumbing that makes it feel real: a MySQL-backed compose harness for a prod profile, Kubernetes manifests, and an edge design for a cloud application gateway.

What "production-shaped" means here

A toy IdP is a weekend. A convincing one keeps pulling you deeper. The review backlog on this project reads like a real audit:

  • Session-authenticated admin API needed its own stateless security chain — CSRF-off plus cookies is a hole, not a convenience.
  • sub had to move from username to an immutable UUID — mutable subjects are account-confusion bugs waiting for a re-registered username.
  • client_secret_post had to die — secrets in request bodies end up in access logs.
  • Prod cookies needed secure/same-site set in config, not in a README checklist nobody re-reads.

Every one of those is a "oh, that's why the spec says that" moment — the kind you don't get from the client side.

The series

  1. This post — the architecture and the why.
  2. Spring Authorization Server from zero to first login.
  3. The relying party: Spring Security OAuth2 client, Thymeleaf and React variants.
  4. The edge gateway: validating tokens you didn't issue.
  5. Third parties: client_credentials, consent screens, and scope design.
  6. Operating it: health probes, observability, deploy manifests, and the security review that hurt.

Next up: standing up the provider — what Spring Authorization Server hands you for free, and the surprising amount it doesn't.

Monday, November 30, 2026

jq recipes you'll actually use

Companion cheatsheet with every recipe: jq quick reference — knowledge base entry.

You have JSON from an API, a CLI, a config file — and you need three fields out of it, flattened, without writing a script. That's the jq sweet spot: it reads JSON, applies a small filter language, and prints exactly what you asked for. Below are the patterns I reach for daily.

Reading fields

jq '.field'              # one field
jq '.a.b.c'              # nested
jq '.items[0]'           # first array element
jq '.[]'                 # every element

Shaping output

jq '.[] | {name, id}'                       # object per element
jq -r '.[] | [.id, .name] | @tsv'           # tab-separated rows
jq 'map(.name) | unique | sort'             # dedupe + sort

Filtering

jq '.[] | select(.x > 5)'
jq 'first(.[] | select(.active))'
jq '.[] | select(.name | test("^harbour-"))'

gh api + jq — the power combo

gh api 'orgs/ORG/repos?per_page=100' --jq '.[].name'
gh api repos/ORG/REPO/git/trees/main?recursive=1 --jq '.tree[].path'

--jq on gh api is exactly the same as piping to jq — it just saves a pipe.

Gotchas that bite everyone

  • .foo.bar dies on a null parent — use .foo?.bar or .foo // {}
  • select() filters, map() transforms — mixing them up is the #1 mistake
  • @tsv/@csv need -r or the output looks wrong
  • Piping one jq into another? Stay in JSON mode — only add -r at the end.

The full table of recipes — aggregation, objects, interpolation, conditionals — is in the KB entry.

Saturday, November 28, 2026

Markdown to Word without the template tax

Full writeup with reproducible steps: How to convert Markdown to Word (.docx) without templates — knowledge base entry.

Every so often a runbook, note, or tracking doc written in Markdown needs to reach someone who lives in Word. Pandoc works, but the output usually needs a manual cleanup pass — and corporate recipients just want a native .docx.

I packaged the conversion as a Devin/agent skill: simple-md-docx-converter. Feed it any well-formed .md file and it produces a Word document using native constructs — real headings, tables, code blocks, task lists — powered by python-docx. No template file, no placeholder contract to maintain.

  • Headings, lists (incl. task lists), tables, code fences, blockquotes, strikethrough, horizontal rules
  • <mark> highlighting, inline images, {{toc}} fields, page breaks
  • Multi-file merge into a single document
  • Mermaid diagrams render to images when mmdc/Kroki is available, else degrade to labelled text
  • Optional --template (.docx/.dotx or a named template) to inherit corporate styles and fill {{key}} tokens

Quick start:

git clone https://gitlab.com/shoujunni/skill-md-docx-converter.git
cd skill-md-docx-converter
./scripts/setup.sh
.venv/bin/python scripts/convert_md_to_docx.py input.md

The git workflow trick worth stealing: it degrades gracefully — if Mermaid tooling isn't installed, diagrams become clearly-labelled text instead of failing. Source and tests are on GitLab.

Wednesday, September 28, 2016

10 of the Worlds Most Powerful Trading Rules

1. A winning trading system must either be designed to have a large winning percentage of trades or big wins and small losses.

2. Your trading system must be built on quantifiable facts not opinions.

3. Start with the weekly price chart to establish the long term trend, and then work down through the daily and hourly charts to trade in the direction of that trend. The odds are better if you are trading in the direction of the long term trend.

4. The more times a support or resistance level is tested, the greater the odds that it will be broken. Old resistance can become the new support, and the old support may become the new resistance.

5. Moving averages can quantify trends and create signals for entries, exits, and trailing stops.

6. Bull Markets have no long term resistance, and Bear Markets have no long term support.

7. “The larger the market gaps, the greater the odds of continuation and a trend.” – Linda Raschke

8. “The last hour often tells the truth about how strong a trend truly is. “Smart” money shows their hand in the last hour, continuing to mark positions in their favor. As long as a market is having consecutive strong closes, look for an up-trend to continue. The up trend is most likely to end when there is a morning rally first, followed by a weak close.” – Linda Raschkee

9. Above the 200 day is where bulls create uptrends. Bad things happen below the 200 day; downtrends, distribution, bear markets, crashes, and bankruptcies.

10. “It is much easier to watch a few than many.” – Jesse Livermore

These are 10 powerful trading rules from new book “Trading Habits: 39 of the World’s Most Powerful Stock Market Rules.” The book explains these rules in great detail and how to profit from them along with 29 others.

Thursday, September 8, 2016

The 10 Trading Rules of Jesse Livermore

The 10 Trading Rules of Jesse Livermore

Before there was a William J. O’Neil or a Nicolas Darvas there was Jesse Livermore. Livermore was considered to be one of the greatest traders to ever live. He is said to have made over $100 million shorting the 1929 crash, an unthinkable amount in his time. He made and lost millions on several occasions, he was a master of the market. No one blew up as many trading accounts or came back to be a millionaire more times in trading history that I know of. We would all do well to sit up and listen to the primary rules and the methodology that he traded with. His strength was his ability to trade with size and ride a trend for huge wins. Livermore’s weaknesses were likely his lack of discipline at times to follow his own rules and he did not manage his risk of ruin throughout his career going through too many cycles of boom and bust. I would assume with his style of trading he was chopped up in range bound markets and spent a lot on commissions, in his day there were no discount brokers and commissions would add up.

Here were his basic rules from his book How to Trade In Stocks which is recommended reading by many top stock traders.

Buy rising stocks and sell falling stocks.Do not trade every day of every year. Trade only when the market is clearly bullish or bearish. Trade in the direction of the general market. If it’s rising you should be long, if it’s falling you should be short.Co-ordinate your trading activity with pivot points.Only enter a trade after the action of the market confirms your opinion and then enter promptly.Continue with trades that show you a profit, end trades that show a loss.End trades when it is clear that the trend you are profiting from is over.In any sector, trade the leading stock – the one showing the strongest trend.Never average losses by, for example, buying more of a stock that has fallen.Never meet a margin call – get out of the trade.Go long when stocks reach a new high. Sell short when they reach a new low.

While Livermore won in the markets over the long term he also lost everything many times, he even went into bankruptcy before making his unbelievable wealth. While he was a true pioneer in trend following, his weakness was the proper respect of risk management, especially his understanding of the odds that he would be ruined if he risked large amounts of his capital on each trade. He was living proof that if you do not respect the risk of ruin you will eventually be ruined by a string of losses. It is popularly believed that Livermore died broke, this is not true, he set up a trust for himself after one of his comebacks to make sure he would never be broke again. According to the books I read and Wikipedia he had untouchable trusts and cash assets at his death totaling over $5 million. He had a  lifelong history of clinical depression and it had become the dominant factor in his final years. He may have faced and been overcome by mental ruin at the end when he committed suicide after a life spent on the boom and bust wealth cycle along with a materialistic lifestyle. Jesse Livermore’s life is both an example of success with making the kind of money most new traders dream about and also a cautionary tale that shows the dangers of trading and the mental toll it can take when done incorrectly and with the wrong mindset.

Java, JavaScript, HTML, XHTML, AJAX, CSS, etc.