All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fi.evolver.basics.spring.auth.JwtAuthorizationService Maven / Gradle / Ivy

There is a newer version: 6.5.1
Show newest version
package fi.evolver.basics.spring.auth;

import static fi.evolver.basics.spring.http.HttpInterceptor.CONTEXT_SOURCE_SYSTEM;
import static fi.evolver.basics.spring.http.HttpInterceptor.addMetadata;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import fi.evolver.basics.spring.auth.entity.JwtToken;
import fi.evolver.utils.ContextUtils;
import fi.evolver.utils.attribute.ContextAttribute;

@Service
@ConditionalOnExpression("environment.containsProperty(T(fi.evolver.basics.spring.auth.JwtAuthorization).ENV_AUTHORIZATION_SECRET) and !environment.containsProperty(\"DISABLE_INTERCEPTOR_AUTH\")")
public class JwtAuthorizationService implements AuthorizationService {
	private static final Logger LOG = LoggerFactory.getLogger(JwtAuthorizationService.class);

	private static final ContextAttribute CONTEXT_AUTHORIZATION_PERMISSIONS = new ContextAttribute<>(JwtAuthorizationService.class.getSimpleName() + ".AuthorizationPermissions", JwtToken.class);

	@Autowired
	private JwtAuthorization jwtAuthorization;

	public JwtAuthorizationService() {
		LOG.info("HttpInterceptor authenticating with jwt");
	}


	@Override
	public void authenticate(String authorization) {
		Assert.isTrue(ContextUtils.withinContext(), "Must have a context in order to authenticate");

		if (getAuthorizationToken().isPresent())
			throw new IllegalStateException("Nested authorization attempt: not supported for now");

		JwtToken token = jwtAuthorization.authorizeToken(authorization);
		setAuthorizationToken(token);
		addMetadata("JwtId", token.getJwtId());
		if (token.isFullyAuthenticated())
			CONTEXT_SOURCE_SYSTEM.set(token.getOwner());
	}


	@Override
	public boolean hasPermission(String permission) {
		JwtToken token = getAuthorizationToken().orElse(JwtToken.UNKNOWN);

		boolean result = token.hasPermission(permission);

		LOG.info("HasPermission: {} => {}", permission, result);
		if (!result)
			LOG.warn("Token {} missing permission {}", token.getJwtId(), permission);

		return result;
	}


	private static Optional getAuthorizationToken() {
		return CONTEXT_AUTHORIZATION_PERMISSIONS.get();
	}


	private static void setAuthorizationToken(JwtToken token) {
		CONTEXT_AUTHORIZATION_PERMISSIONS.set(token);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy