๐Ÿ”“ Unsecured plain JWT (JSON Web Token) in Spring Security

ยท 372 words ยท 2 minute read

Spring Security rejects unsecured JSON Web Tokens โ€” tokens with alg: none and no signature โ€” by design. If you still need to accept them, it’s usually because a trusted component upstream, such as an API gateway, has already authenticated the caller and issues the token internally. In that case, you have to parse and authenticate the token yourself.

Only accept unsecured JWTs on a boundary you trust. If this endpoint is reachable directly, anyone can forge a token and authenticate as any user, since there is no signature to verify.

public class JwtAuthFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		String header = request.getHeader("Authorization");
		if (header != null && header.startsWith("Bearer ")) {
			String token = header.substring(7);
			try {
				SecurityContextHolder.getContext()
					.setAuthentication(new UnsecuredToken(PlainJWT.parse(token)));
			} catch (ParseException e) {
				// Not a valid unsecured JWT, proceed unauthenticated
			}
		}
		chain.doFilter(request, response);
	}
}

To hold the parsed token as the request’s Authentication, subclass AbstractAuthenticationToken:

public class UnsecuredToken extends AbstractAuthenticationToken {

	private final JWT token;

	public UnsecuredToken(JWT token) {
		super(Collections.emptyList());
		this.token = Objects.requireNonNull(token);
		setAuthenticated(true);
	}

	@Override
	public Object getCredentials() {
		return token;
	}

	@Override
	public Object getPrincipal() {
		return token;
	}
}

AbstractAuthenticationToken’s constructor marks the token as not authenticated by default, so setAuthenticated(true) must be called explicitly, otherwise Spring Security won’t treat the request as authenticated.

Hooking the filter into Spring Security#

JwtAuthFilter never clears SecurityContextHolder itself: Spring Security already does that for every request, so there’s nothing to clean up here.


@Configuration
public class SecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
			.formLogin(AbstractHttpConfigurer::disable)
			.httpBasic(AbstractHttpConfigurer::disable)
			.csrf(AbstractHttpConfigurer::disable)
			.addFilterBefore(new JwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
		return http.build();
	}
}

formLogin and httpBasic are disabled since JwtAuthFilter is now the only way to authenticate a request.

Generating an unsecured JWT with Bruno Bruno#

If you are using Bruno to send requests to your service, you can use the following Pre-Request script at the collection level to attach the Authorization header to every request.

const jwt = require('jsonwebtoken');

const payload = {
    sub: '1234567890',
    name: 'Test User',
    iat: Math.floor(Date.now() / 1000),
    customClaim: ["<custom>"]
};

// alg: "none" means no signature โ€” pass null as the secret/key
const unsecuredToken = jwt.sign(payload, null, { algorithm: 'none' });

bru.setVar('unsecured_jwt', unsecuredToken);
req.setHeader('Authorization', `Bearer ${unsecuredToken}`);