Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@
*/
package org.apache.bigtop.manager.server;

import org.apache.bigtop.manager.server.config.JwtProperties;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync
@EnableScheduling
@EnableConfigurationProperties(JwtProperties.class)
@SpringBootApplication(
scanBasePackages = {
"org.apache.bigtop.manager.server",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bigtop.manager.server.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Data;

@Data
@ConfigurationProperties(prefix = "bigtop-manager.security.jwt")
public class JwtProperties {

/**
* JWT signing secret.
* <p>
* Must be set in production (e.g. via env var) to prevent forged tokens.
*/
private String secret;

/** Issuer to embed and to require during verification. */
private String issuer = "bigtop-manager";

/** Audience to embed and to require during verification. */
private String audience = "bigtop-manager";

/** Token validity period in days. */
private int expirationDays = 7;

/**
* Whether to allow a built-in dev secret as fallback.
* <p>
* Keep this false in production.
*/
private boolean allowDefaultSecret = false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ public class AuthInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;

@Autowired
private JWTUtils jwtUtils;

private ResponseEntity<?> responseEntity;

@Override
Expand Down Expand Up @@ -89,7 +92,7 @@ private Boolean checkLogin(HttpServletRequest request) {
}

try {
DecodedJWT decodedJWT = JWTUtils.resolveToken(token);
DecodedJWT decodedJWT = jwtUtils.resolveToken(token);
Long userId = decodedJWT.getClaim(JWTUtils.CLAIM_ID).asLong();
Integer tokenVersion =
decodedJWT.getClaim(JWTUtils.CLAIM_TOKEN_VERSION).asInt();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public class LoginServiceImpl implements LoginService {
@Resource
private UserDao userDao;

@Resource
private JWTUtils jwtUtils;

@Override
public LoginVO login(LoginDTO loginDTO) {
String username = loginDTO.getUsername();
Expand Down Expand Up @@ -75,7 +78,7 @@ public LoginVO login(LoginDTO loginDTO) {
CacheUtils.setCache(
Caches.CACHE_USER, user.getId().toString(), userVO, Caches.USER_EXPIRE_TIME_DAYS, TimeUnit.DAYS);

String token = JWTUtils.generateToken(user.getId(), user.getUsername(), user.getTokenVersion());
String token = jwtUtils.generateToken(user.getId(), user.getUsername(), user.getTokenVersion());
LoginVO loginVO = new LoginVO();
loginVO.setToken(token);
return loginVO;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,21 @@
*/
package org.apache.bigtop.manager.server.utils;

import org.apache.bigtop.manager.server.config.JwtProperties;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Component
public class JWTUtils {

public static final String CLAIM_ID = "id";
Expand All @@ -33,23 +41,69 @@ public class JWTUtils {

public static final String CLAIM_TOKEN_VERSION = "token_version";

protected static final String SIGN = "r0PGVyvjKOxUBwGt";
/**
* Dev-only fallback secret to preserve local boot for contributors.
* <p>
* In production, configure `bigtop-manager.security.jwt.secret`.
*/
static final String DEFAULT_DEV_SECRET = "r0PGVyvjKOxUBwGt";

private final JwtProperties jwtProperties;

// Token validity period (days)
private static final int TOKEN_EXPIRATION_DAYS = 7;
public JWTUtils(JwtProperties jwtProperties) {
this.jwtProperties = jwtProperties;
}

public static String generateToken(Long userId, String username, Integer tokenVersion) {
Instant expireTime = Instant.now().plus(TOKEN_EXPIRATION_DAYS, ChronoUnit.DAYS);
public String generateToken(Long userId, String username, Integer tokenVersion) {
Instant now = Instant.now();
Instant expireTime = now.plus(jwtProperties.getExpirationDays(), ChronoUnit.DAYS);

return JWT.create()
.withIssuer(jwtProperties.getIssuer())
.withAudience(jwtProperties.getAudience())
.withIssuedAt(Date.from(now))
.withClaim(CLAIM_ID, userId)
.withClaim(CLAIM_USERNAME, username)
.withClaim(CLAIM_TOKEN_VERSION, tokenVersion)
.withExpiresAt(expireTime)
.sign(Algorithm.HMAC256(SIGN));
.withExpiresAt(Date.from(expireTime))
.sign(Algorithm.HMAC256(getSigningSecret()));
}

public DecodedJWT resolveToken(String token) throws JWTVerificationException {
Algorithm algorithm = Algorithm.HMAC256(getSigningSecret());
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(jwtProperties.getIssuer())
.withAudience(jwtProperties.getAudience())
.build();

DecodedJWT decodedJWT = verifier.verify(token);

// Enforce issued-at to mitigate tokens without freshness metadata.
Date issuedAt = decodedJWT.getIssuedAt();
if (issuedAt == null) {
throw new JWTVerificationException("Missing iat");
}

// Reject tokens issued too far in the future (clock skew).
Instant now = Instant.now();
if (issuedAt.toInstant().isAfter(now.plus(5, ChronoUnit.MINUTES))) {
throw new JWTVerificationException("iat is in the future");
}

return decodedJWT;
}

public static DecodedJWT resolveToken(String token) {
return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
private String getSigningSecret() {
String secret = jwtProperties.getSecret();
if (secret != null && !secret.isBlank()) {
return secret;
}

if (jwtProperties.isAllowDefaultSecret()) {
return DEFAULT_DEV_SECRET;
}

throw new IllegalStateException(
"JWT secret is not configured. Please set bigtop-manager.security.jwt.secret (or enable allowDefaultSecret for dev only).");
}
}
13 changes: 12 additions & 1 deletion bigtop-manager-server/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,15 @@ springdoc:
pagehelper:
reasonable: false
params: count=countSql
support-methods-arguments: true
support-methods-arguments: true

bigtop-manager:
security:
jwt:
# IMPORTANT: Set a strong, random secret in production (e.g. via env var BIGTOP_MANAGER_JWT_SECRET)
secret: ${BIGTOP_MANAGER_JWT_SECRET:}
issuer: bigtop-manager
audience: bigtop-manager
expiration-days: 7
# Dev-only compatibility switch. Keep false in production.
allow-default-secret: false
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.apache.bigtop.manager.server.model.dto.LoginDTO;
import org.apache.bigtop.manager.server.service.impl.LoginServiceImpl;
import org.apache.bigtop.manager.server.utils.CacheUtils;
import org.apache.bigtop.manager.server.utils.JWTUtils;
import org.apache.bigtop.manager.server.utils.PasswordUtils;
import org.apache.bigtop.manager.server.utils.Pbkdf2Utils;

Expand All @@ -51,6 +52,9 @@ public class LoginServiceTest {
@Mock
private UserDao userDao;

@Mock
private JWTUtils jwtUtils;

@InjectMocks
private LoginService loginService = new LoginServiceImpl();

Expand Down Expand Up @@ -107,6 +111,7 @@ public void testLogin_WhenValidCredentials_ShouldReturnToken() {
LoginDTO loginDTO = createLoginDTO(RAW_PASSWORD);

when(userDao.findByUsername(any())).thenReturn(mockUser);
when(jwtUtils.generateToken(any(), any(), any())).thenReturn("test-token");

Object result = loginService.login(loginDTO);
assertNotNull(result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/
package org.apache.bigtop.manager.server.utils;

import org.apache.bigtop.manager.server.config.JwtProperties;

import org.junit.jupiter.api.Test;

import com.auth0.jwt.JWT;
Expand All @@ -35,15 +37,26 @@

public class JWTUtilsTest {

private static JWTUtils newJwtUtilsWithDevSecretAllowed() {
JwtProperties props = new JwtProperties();
props.setAllowDefaultSecret(true);
props.setIssuer("bigtop-manager");
props.setAudience("bigtop-manager");
props.setExpirationDays(7);
return new JWTUtils(props);
}

@Test
public void testGenerateTokenNormal() {
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

Long id = 1L;
String username = "testUser";
Integer tokenVersion = 1;
String token = JWTUtils.generateToken(id, username, tokenVersion);
String token = jwtUtils.generateToken(id, username, tokenVersion);
assertNotNull(token);

DecodedJWT decodedJWT = JWTUtils.resolveToken(token);
DecodedJWT decodedJWT = jwtUtils.resolveToken(token);
assertEquals(id, decodedJWT.getClaim(JWTUtils.CLAIM_ID).asLong());
assertEquals(username, decodedJWT.getClaim(JWTUtils.CLAIM_USERNAME).asString());
assertEquals(
Expand All @@ -52,40 +65,76 @@ public void testGenerateTokenNormal() {

@Test
public void testResolveTokenExpired() {
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

Long id = 2L;
String username = "expiredUser";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -1);
Date date = calendar.getTime();

String token = JWT.create()
.withIssuer("bigtop-manager")
.withAudience("bigtop-manager")
.withIssuedAt(new Date())
.withClaim(JWTUtils.CLAIM_ID, id)
.withClaim(JWTUtils.CLAIM_USERNAME, username)
.withExpiresAt(date)
.sign(Algorithm.HMAC256(JWTUtils.SIGN));
.sign(Algorithm.HMAC256(JWTUtils.DEFAULT_DEV_SECRET));

assertThrows(JWTVerificationException.class, () -> JWTUtils.resolveToken(token));
assertThrows(JWTVerificationException.class, () -> jwtUtils.resolveToken(token));
}

@Test
public void testResolveTokenIllegal() {
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

String illegalToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
assertThrows(JWTVerificationException.class, () -> JWTUtils.resolveToken(illegalToken));
assertThrows(JWTVerificationException.class, () -> jwtUtils.resolveToken(illegalToken));
}

@Test
public void testResolveTokenWrongFormat() {
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

String wrongFormatToken = "wrong_format_token";
assertThrows(JWTDecodeException.class, () -> JWTUtils.resolveToken(wrongFormatToken));
assertThrows(JWTDecodeException.class, () -> jwtUtils.resolveToken(wrongFormatToken));
}

@Test
public void testGenerateTokenUsernameEmpty() {
String token = JWTUtils.generateToken(1L, "", 1);
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

String token = jwtUtils.generateToken(1L, "", 1);
assertNotNull(token);

DecodedJWT decodedJWT = JWTUtils.resolveToken(token);
DecodedJWT decodedJWT = jwtUtils.resolveToken(token);
assertEquals("", decodedJWT.getClaim(JWTUtils.CLAIM_USERNAME).asString());
}

@Test
public void testResolveTokenMissingIatRejected() {
JWTUtils jwtUtils = newJwtUtilsWithDevSecretAllowed();

String token = JWT.create()
.withIssuer("bigtop-manager")
.withAudience("bigtop-manager")
.withClaim(JWTUtils.CLAIM_ID, 1L)
.withClaim(JWTUtils.CLAIM_TOKEN_VERSION, 1)
.withExpiresAt(new Date(System.currentTimeMillis() + 60_000))
// intentionally no iat
.sign(Algorithm.HMAC256(JWTUtils.DEFAULT_DEV_SECRET));

assertThrows(JWTVerificationException.class, () -> jwtUtils.resolveToken(token));
}

@Test
public void testSecretRequiredByDefault() {
JwtProperties props = new JwtProperties();
props.setAllowDefaultSecret(false);
JWTUtils jwtUtils = new JWTUtils(props);

assertThrows(IllegalStateException.class, () -> jwtUtils.generateToken(1L, "u", 1));
}
}
Loading
Loading