Broken authentication¶
When is it relevant¶
A new or changed entry point (route, socket event, webhook, job trigger) that should only be reachable by a known caller. Also a change to how callers are identified: login, sessions, tokens, API keys or SSO.
Attack¶
The attacker calls the entry point with no credentials, or with expired, forged or wrongly scoped ones, and the server still treats them as an authenticated user. Common causes:
- A route is mounted outside the authentication middleware.
- Middleware fails open on errors or missing headers.
- Tokens are decoded without being verified.
- Credentials from one identity system are accepted as another.
Mitigation¶
- Apply authentication at the router level so new routes are protected by default, and list public routes explicitly.
- Fail closed: missing, malformed or unverifiable credentials end the request with
401. - Verify tokens fully: signature with a pinned algorithm, expiry, issuer and audience. Check that the session or key is still active.
Test¶
- Point-in-time: call each entry point with no credentials, an expired token, a token with a bad signature and a token from another issuer or audience. Every one must return
401. - Continuous: an integration test that walks the route table and asserts every route not on the public list rejects an anonymous request, so a new route outside the middleware fails the build.
Examples¶
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
express-session + a server-side store |
Cookie-based web apps; lets you revoke a session server-side | express-session |
JWT (jsonwebtoken) |
Stateless APIs and service-to-service calls; revocation needs extra work | node-jsonwebtoken |
| Passport strategies | Delegated login (OIDC, SAML, social) on top of either of the above | Passport sessions |
Vulnerable — session that survives login
app.use(session({
secret: 'dev-secret', // hardcoded, shared across environments
resave: false,
saveUninitialized: true, // issues a cookie to anonymous visitors
cookie: { maxAge: 86400000 }, // no httpOnly, no secure, no sameSite
}))
app.post('/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email })
if (!user || user.password !== hash(req.body.password)) {
return res.status(401).json({ error: 'Invalid credentials' })
}
req.session.userId = user._id // same session ID as before login
res.json({ ok: true })
})
The session ID is never rotated, so an ID an attacker planted in the victim's browser before login becomes an authenticated session (session fixation).
Vulnerable — JWT that is read but not verified
const payload = jwt.decode(req.headers.authorization.slice(7))
req.user = payload // no signature check at all
Mitigated — express-session
app.set('trust proxy', 1)
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.MONGO_URL }),
cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 3600000 },
}))
app.post('/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email })
const ok = user && await bcrypt.compare(req.body.password, user.passwordHash)
if (!ok) return res.status(401).json({ error: 'Invalid credentials' })
req.session.regenerate((err) => { // new session ID after login
if (err) return res.status(500).end()
req.session.userId = user.id
req.session.save(() => res.json({ ok: true }))
})
})
app.post('/logout', (req, res) => {
req.session.destroy(() => res.clearCookie('connect.sid').json({ ok: true }))
})
bcrypt.compare is constant-time, and the same 401 is returned whether the
email exists or not, so the response can't be used to enumerate accounts.
Docs: express-session · session.regenerate · connect-mongo · bcrypt
Mitigated — JWT
function requireAuth(req, res, next) {
const [scheme, token] = (req.headers.authorization || '').split(' ')
if (scheme !== 'Bearer' || !token) return res.sendStatus(401)
try {
req.user = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'], // pin it: never trust the header's alg
issuer: 'api.example.com',
audience: 'example-web',
maxAge: '1h',
})
next()
} catch {
return res.sendStatus(401)
}
}
Docs: jsonwebtoken
Bypasses to check
jwt.decode()used anywhere in the auth path — it parses without verifying.jwt.verify()withoutalgorithms— an attacker may switchalgtononeor toHS256signed with a public RSA key the server trusts.- No
req.session.regenerate()on login (fixation), or logout that only clearsreq.session.userIdwithoutdestroy(), leaving the old ID valid. - Identity taken from a client-supplied field (
req.body.userId,X-User-Id) rather than from the verified session or token. - Password compared with
===against a hash, or with a non-constant-time helper; different responses or timings for "no such user" vs "wrong password". saveUninitialized: trueplus a login that writes into the pre-existing session object.- Rate limiting applied only to
/loginwhile/register, password reset or token refresh reach the same credential check.
What to grep for
jwt.decode(,jwt.verify(,algorithms,ignoreExpirationsession(,saveUninitialized,regenerate(,destroy(,cookie:bcrypt.compare,createHash(,=== user.password
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
Form login + HttpSession (Spring Security defaults) |
Server-rendered apps; sessions can be revoked server-side | Form login |
OAuth2 resource server (oauth2ResourceServer().jwt()) |
Stateless APIs; Spring verifies signature, exp and nbf for you |
JWT resource server |
| OAuth2 / OIDC login | Delegated login to an identity provider | OAuth2 login |
Custom OncePerRequestFilter with jjwt |
Only when the above can't fit; you own every check | jjwt |
Once you declare your own SecurityFilterChain bean, Spring Boot's default
("every request needs a login") no longer applies: requests are protected only
by the rules you write, and the first matching rule wins. So review the chain
as a whole: the order of requestMatchers, the final anyRequest(), every
path in web.ignoring(), and every filter added before the authorization
filter.
Vulnerable — custom JWT filter that parses without verifying
public class JwtAuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String token = bearer(req);
if (token != null) {
Claims claims = Jwts.parser().unsecured().build() // accepts alg "none"
.parseUnsecuredClaims(token).getPayload();
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(claims.getSubject(), null, List.of()));
}
chain.doFilter(req, res);
}
}
Anyone can write their own token with any sub. The same happens when the
filter base64-decodes the payload by hand, or catches the verification
exception and carries on with the decoded claims.
Vulnerable — the last rule lets everything through
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()); // /actuator, /internal, /h2-console …
@Bean
WebSecurityCustomizer ignore() {
return web -> web.ignoring().requestMatchers("/api/public/**", "/api/reports/**");
}
web.ignoring() removes the whole filter chain for those paths: no
authentication, no CSRF, no security headers. Paths added under them later are
public by accident.
Vulnerable — plaintext or fast password hashing
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance(); // or new MessageDigestPasswordEncoder("SHA-256")
}
Mitigated — form login with the defaults
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login", "/register", "/css/**").permitAll()
.anyRequest().authenticated()) // default-deny
.formLogin(form -> form.loginPage("/login"))
.logout(logout -> logout.deleteCookies("JSESSIONID")) // invalidates the session
.sessionManagement(s -> s.sessionFixation(f -> f.changeSessionId()));
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // bcrypt, upgradable
}
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=lax
changeSessionId() is the default, so a session ID planted before login stops
working after it. DaoAuthenticationProvider runs a dummy hash when the user
doesn't exist, so the response time doesn't reveal valid usernames.
Docs: Session fixation · Password storage · Session cookie properties
Mitigated — JWT resource server
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
JwtDecoder jwtDecoder(@Value("${app.jwt-secret}") String secret) {
SecretKey key = new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA256");
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key)
.macAlgorithm(MacAlgorithm.HS256).build(); // algorithm pinned
decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer("https://api.example.com"));
return decoder;
}
Docs: JWT resource server · NimbusJwtDecoder
Mitigated — custom filter, if you must
Optional<String> verify(String token) {
try {
return Optional.ofNullable(Jwts.parser()
.verifyWith(key) // signature required
.requireIssuer("https://api.example.com")
.build()
.parseSignedClaims(token) // rejects unsigned tokens
.getPayload()
.getSubject());
} catch (JwtException | IllegalArgumentException e) {
return Optional.empty(); // no authentication set
}
}
parseSignedClaims throws on an unsigned or tampered token, and exp is
checked automatically. Set the authentication only on success, and leave the
decision to the authorization rules rather than returning early from the
filter.
Docs: jjwt reading a JWS
Bypasses to check
parseUnsecuredClaims,.unsecured(),Jwts.parser().parse(token)withoutverifyWith, or a hand-rolledBase64.getDecoder()on the token's payload.- The verification exception caught and logged, with the request continuing as the decoded user; or a filter that accepts an expired token "for refresh" on every route.
- Weak or shared secrets: a default in
application.properties, the same key in every environment, or a key shorter than the algorithm needs. anyRequest().permitAll()as the last rule,web.ignoring()on application paths, and Actuator endpoints exposed (management.endpoints.web.exposure.include=*) with no rule covering them.- Rule order: a broad
permitAll()matcher listed before a narrowerauthenticated()one wins, because the first match decides. - Identity taken from a header or body field (
X-User-Id,userId) instead ofSecurityContextHolder/@AuthenticationPrincipal. - Logout that only clears the cookie while the JWT stays valid until
exp, or a session that isn't invalidated. NoOpPasswordEncoder,{noop}in a delegating encoder's stored values,MessageDigestPasswordEncoder,StandardPasswordEncoder.- Different messages or status codes for "no such user" and "wrong password" in a custom login controller.
What to grep for
SecurityFilterChain,authorizeHttpRequests,permitAll(),anyRequest(),web.ignoring(),securityMatcher(OncePerRequestFilter,addFilterBefore(,SecurityContextHolder.getContext().setAuthentication(parseUnsecuredClaims,unsecured(),parseSignedClaims,verifyWith,NimbusJwtDecoder,Base64.getDecoder()near a tokenNoOpPasswordEncoder,{noop},MessageDigestPasswordEncoder,PasswordEncodersessionFixation,sessionCreationPolicy,management.endpoints.web.exposure
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
| Flask's signed cookie session + a login decorator | Server-rendered apps; the session is signed, not encrypted | Flask sessions |
| Flask-Login | The same, with login_required, "remember me" and user loading built in |
Flask-Login |
| Server-side sessions (Flask-Session) | You need to revoke a session on the server | Flask-Session |
JWT (PyJWT, Flask-JWT-Extended) |
APIs used by non-browser clients; revocation needs extra work | PyJWT, Flask-JWT-Extended |
Vulnerable — weak secret, session kept across login
app.secret_key = 'dev' # anyone can sign their own session cookie
@app.post('/login')
def login():
user = db.users.find_one({'email': request.form['email']})
if user and user['password'] == hashlib.md5(request.form['password'].encode()).hexdigest():
session['user_id'] = str(user['_id']) # no session.clear(), no slow hash
return redirect('/')
return 'Invalid credentials', 401
Flask's session is a cookie signed with SECRET_KEY. Anyone who knows the
key can write {"user_id": "<any id>"} and sign it, with tools like
flask-unsign.
Vulnerable — a route that forgot the decorator
@app.get('/admin/export') # no @login_required, so anyone can call it
def export():
return jsonify(list(db.users.find({}, {'password_hash': 0})))
Vulnerable — JWT decoded without verification or without pinning the algorithm
payload = jwt.decode(token, options={'verify_signature': False})
payload = jwt.decode(token, key, algorithms=jwt.algorithms.get_default_algorithms())
Mitigated — session with a strong key, bcrypt, and a fresh session on login
app.config.update(
SECRET_KEY=os.environ['SECRET_KEY'], # long, random, per environment
SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SECURE=True, SESSION_COOKIE_SAMESITE='Lax',
)
@app.post('/login')
def login():
user = users.find_by_email(request.form.get('email', ''))
if not user or not bcrypt.checkpw(request.form.get('password', '').encode(), user['password_hash'].encode()):
return render_template('login.html', error='Invalid credentials'), 401
session.clear() # drop anything set before login
session['user_id'] = user['id']
session['pw'] = user['password_hash'][-16:] # changes when the password does
return redirect(url_for('home'))
@app.before_request
def load_user():
g.user = None
if (uid := session.get('user_id')) and (u := users.find_by_id(uid)) and session.get('pw') == u['password_hash'][-16:]:
g.user = u
elif uid:
session.clear() # password changed: sign this session out
Flask can't revoke a signed cookie on the server. Binding it to the password hash is what makes a password change sign out the other sessions.
Docs: Flask sessions · SECRET_KEY · bcrypt
Mitigated — JWT for the API
def require_token(view):
@wraps(view)
def wrapped(*a, **kw):
scheme, _, token = request.headers.get('Authorization', '').partition(' ')
if scheme != 'Bearer' or not token:
return jsonify(error='Authorization required'), 401
try:
claims = jwt.decode(token, current_app.config['JWT_SECRET'], algorithms=['HS256'],
options={'require': ['exp', 'sub', 'pwv']})
except jwt.PyJWTError:
return jsonify(error='Invalid token'), 401
user = users.find_by_id(claims['sub'])
if not user or claims['pwv'] != user['password_version']: # revoked by a password change
return jsonify(error='Invalid token'), 401
g.user = user
return view(*a, **kw)
return wrapped
Docs: PyJWT decode
Bypasses to check
SECRET_KEYhard-coded, committed in.env.example, or the same in every environment.- A password change that ends the web session but not the API tokens, or the other way round.
jwt.decodewithoutalgorithms=[…], or withverify_signature: Falseanywhere in the auth path.- Blueprints or
add_url_ruleroutes registered without the decorator. Compare every view with its siblings. request.headers['X-User-Id'], or a user ID taken from the body, trusted as the identity.- No rate limit on the login routes; see Flask-Limiter.
What to grep for
secret_key,SECRET_KEY,session[,session.clear(,before_requestlogin_required,@app.route,@bp.route,add_url_rule(jwt.decode(,verify_signature,algorithms,bcrypt.checkpw(,hashlib.md5,check_password_hash(