├── src ├── main │ ├── resources │ │ └── META-INF │ │ │ └── spring.factories │ └── java │ │ └── com │ │ └── codingcube │ │ └── simpleauth │ │ ├── validated │ │ ├── util │ │ │ ├── BooleanCompute.java │ │ │ ├── BooleanGenericCompute.java │ │ │ └── Regex.java │ │ ├── strategic │ │ │ ├── ValidateRejectedStratagem.java │ │ │ └── DefaultValidateRejectedStratagem.java │ │ ├── annotation │ │ │ └── SimpleValidate.java │ │ ├── domain │ │ │ └── ReflectMethod.java │ │ └── postprocessor │ │ │ └── CacheAutoValidatedBeanPostProcessor.java │ │ ├── auth │ │ ├── handler │ │ │ ├── SimpleAuthHandler.java │ │ │ ├── SimpleAuthHandlerChain.java │ │ │ ├── DefaultAuthHandlerChain.java │ │ │ ├── ProfileConfigurationHandlerChain.java │ │ │ ├── prepare │ │ │ │ └── VerifyKeyHandler.java │ │ │ ├── AutoAuthHandler.java │ │ │ ├── DefaultAuthHandler.java │ │ │ └── AutoAuthHandlerChain.java │ │ ├── dynamic │ │ │ ├── RequestAuthItemProvider.java │ │ │ ├── sign │ │ │ │ └── DynamicSignBean.java │ │ │ ├── provider │ │ │ │ └── CacheAuthItemProvider.java │ │ │ ├── FilterAuthWebConfig.java │ │ │ └── RequestAuthItem.java │ │ ├── strategic │ │ │ ├── AuthRejectedStratagem.java │ │ │ ├── SignStrategic.java │ │ │ ├── DefaultItemStrategic.java │ │ │ ├── DefaultSignStrategic.java │ │ │ └── DefaultAuthRejectedStratagem.java │ │ ├── annotation │ │ │ ├── EnableDynamicAuthRequest.java │ │ │ ├── SimpleAuth.java │ │ │ └── IsAuthor.java │ │ ├── filter │ │ │ ├── CacheRequestContentFilter.java │ │ │ └── CacheBodyHttpServletRequest.java │ │ ├── autoconfig │ │ │ ├── FilterAuthWebAutoConfig.java │ │ │ └── AutoConfigAuthInterceptor.java │ │ ├── interceptor │ │ │ ├── DynamicAuthInterceptor.java │ │ │ ├── AutoAuthChainInterceptor.java │ │ │ └── AutoAuthInterceptor.java │ │ └── PermissionOperate.java │ │ ├── limit │ │ ├── dynamic │ │ │ ├── RequestLimitItemProvider.java │ │ │ ├── sign │ │ │ │ └── DynamicLimitSignBean.java │ │ │ ├── provider │ │ │ │ └── CacheLimitItemProvider.java │ │ │ ├── FilterLimitWebConfig.java │ │ │ ├── DynamicLimitInterceptor.java │ │ │ ├── advice │ │ │ │ └── DynamicLimitAdvice.java │ │ │ └── RequestLimitItem.java │ │ ├── strategic │ │ │ ├── BanKeyStratagem.java │ │ │ ├── EffectiveStrategic.java │ │ │ ├── RejectedStratagem.java │ │ │ ├── DefaultEffectiveStrategic.java │ │ │ ├── DefaultLimitRejectedStratagem.java │ │ │ ├── sign │ │ │ │ └── DiffParameterSign.java │ │ │ └── SimpleJoinPoint.java │ │ ├── cache │ │ │ ├── KeyCache.java │ │ │ └── impl │ │ │ │ └── DefaultCache.java │ │ ├── annotation │ │ │ ├── EnableDynamicLimit.java │ │ │ ├── EnableAutoClearExpiredRecord.java │ │ │ ├── IsLimit.java │ │ │ └── SimpleLimit.java │ │ ├── scheduled │ │ │ └── AutoClearExpiredRecordScheduled.java │ │ ├── util │ │ │ ├── TokenLimit.java │ │ │ ├── TokenBucket.java │ │ │ ├── CompleteLimit.java │ │ │ └── LimitHandlerUtil.java │ │ └── autoconfig │ │ │ ├── FilterLimitWebAutoConfig.java │ │ │ ├── AutoConfigLimitInterceptor.java │ │ │ └── AutoConfigLimitAdvice.java │ │ ├── security │ │ ├── crypto │ │ │ ├── encryptor │ │ │ │ ├── TextEncryptor.java │ │ │ │ ├── ByteEncryptor.java │ │ │ │ └── impl │ │ │ │ │ ├── TextAesEncryptor.java │ │ │ │ │ └── AesByteEncryptor.java │ │ │ ├── password │ │ │ │ ├── PasswordEncoder.java │ │ │ │ └── BCryptPasswordEncoder.java │ │ │ └── Encryptors.java │ │ ├── interceptor │ │ │ ├── AddXFrameOptionsInterceptor.java │ │ │ └── ContentSecurityPolicyInterceptor.java │ │ ├── handler │ │ │ └── session │ │ │ │ ├── ChangeSessionHandler.java │ │ │ │ ├── SessionMigratorHandler.java │ │ │ │ └── ChangeSessionIdHandler.java │ │ └── config │ │ │ └── SecurityWebConfigurer.java │ │ ├── SimpleAuthApplication.java │ │ ├── exception │ │ ├── AccessIsRestrictedException.java │ │ ├── ValidateException.java │ │ ├── TargetNotFoundException.java │ │ ├── ValidateMethodException.java │ │ ├── PermissionsException.java │ │ └── LogException.java │ │ ├── annotation │ │ └── SimpleCache.java │ │ ├── util │ │ ├── support │ │ │ ├── scope │ │ │ │ ├── ScopeType.java │ │ │ │ ├── Scope.java │ │ │ │ ├── FalseScope.java │ │ │ │ ├── ProtoScope.java │ │ │ │ ├── SessionScope.java │ │ │ │ ├── RequestScope.java │ │ │ │ └── SingletonScope.java │ │ │ └── BeanDefinition.java │ │ ├── NullTarget.java │ │ ├── LambdaEnhance.java │ │ └── ApplicationContextProvider.java │ │ ├── autoconfig │ │ ├── Config2SimpleAuthObject.java │ │ ├── execption │ │ │ ├── JSONParseException.java │ │ │ ├── XMLParseException.java │ │ │ └── ConfigurationParseException.java │ │ ├── json │ │ │ └── utils │ │ │ │ └── JSONUtils.java │ │ └── domain │ │ │ ├── Paths.java │ │ │ ├── SimpleAuthConfig.java │ │ │ ├── HandlerChain.java │ │ │ └── Handler.java │ │ ├── properties │ │ ├── ClearProper.java │ │ ├── ValidateProper.java │ │ ├── LogProper.java │ │ ├── SecurityProper.java │ │ ├── FunctionProper.java │ │ ├── EvaluationEnvironmentContext.java │ │ ├── AuthProper.java │ │ ├── LimitProper.java │ │ └── Bean2Static.java │ │ ├── config │ │ ├── AuthAutoConfiguration.java │ │ └── SimpleAuthWebConfig.java │ │ └── logging │ │ ├── Log.java │ │ ├── logformat │ │ ├── LogValidatedFormat.java │ │ ├── LogAuthFormat.java │ │ └── LogLimitFormat.java │ │ ├── nologging │ │ └── NoLoggingImpl.java │ │ ├── stdout │ │ └── StdOutImpl.java │ │ ├── jdk │ │ └── Jdk14LoggingImpl.java │ │ └── LogFactory.java └── test │ └── java │ └── com │ ├── LimitInfoMapJUCTest.java │ └── LimitInfoMapTest.java ├── README.md └── LICENSE /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | com.codingcube.simpleauth.config.AuthAutoConfiguration -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/util/BooleanCompute.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.util; 2 | 3 | @FunctionalInterface 4 | public interface BooleanCompute { 5 | boolean run(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/util/BooleanGenericCompute.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.util; 2 | 3 | @FunctionalInterface 4 | public interface BooleanGenericCompute { 5 | boolean run(T t); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/SimpleAuthHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | /** 4 | * @author CodingCube
5 | * Authentication Handler* 6 | */ 7 | public abstract class SimpleAuthHandler extends AutoAuthHandler{ 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/SimpleAuthHandlerChain.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | /** 4 | * @author CodingCube
5 | * Authentication Handler Chain 6 | */ 7 | public abstract class SimpleAuthHandlerChain extends AutoAuthHandlerChain{ 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/RequestLimitItemProvider.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic; 2 | 3 | 4 | import java.util.List; 5 | /** 6 | * @author CodingCube
* 7 | * Provider of Dynamic Limit Data* 8 | */ 9 | public interface RequestLimitItemProvider { 10 | List getRequestLimitItem(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/dynamic/RequestAuthItemProvider.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.dynamic; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author CodingCube
* 7 | * Provider of Dynamic Permission Control Data* 8 | */ 9 | public interface RequestAuthItemProvider { 10 | List getRequestAuthItem(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/BanKeyStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | /** 4 | * @author CodingCube
* 5 | * Ban Flag Generation Strategy* 6 | */ 7 | public class BanKeyStratagem { 8 | public static String getBanKey(String recordItem, String sign){ 9 | return recordItem + sign; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/encryptor/TextEncryptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.encryptor; 2 | 3 | public interface TextEncryptor { 4 | 5 | /** 6 | * Encrypt the byte array. 7 | */ 8 | String encrypt(String text); 9 | 10 | /** 11 | * Decrypt the byte array. 12 | */ 13 | String decrypt(String encryptedText); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/strategic/ValidateRejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.strategic; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | public interface ValidateRejectedStratagem { 7 | void doRejected(HttpServletRequest request, HttpServletResponse response, Object validationObj); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/encryptor/ByteEncryptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.encryptor; 2 | 3 | public interface ByteEncryptor { 4 | 5 | /** 6 | * Encrypt the byte array. 7 | */ 8 | byte[] encrypt(byte[] byteArray); 9 | 10 | /** 11 | * Decrypt the byte array. 12 | */ 13 | byte[] decrypt(byte[] encryptedByteArray); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/password/PasswordEncoder.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.password; 2 | 3 | public interface PasswordEncoder { 4 | String encode(CharSequence password); 5 | 6 | boolean matches(CharSequence password, String passwordEncodeString); 7 | 8 | default boolean upgradeEncoding(String encodedPassword) { 9 | return false; 10 | } 11 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/cache/KeyCache.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.cache; 2 | 3 | 4 | import java.util.Set; 5 | 6 | public interface KeyCache{ 7 | T remove(String key); 8 | 9 | T get(String key); 10 | 11 | T put(String key, T data); 12 | 13 | int size(); 14 | 15 | boolean containsKey(String key); 16 | 17 | Set keySet(); 18 | 19 | void clear(); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/SimpleAuthApplication.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | 7 | @SpringBootApplication 8 | public class SimpleAuthApplication { 9 | public static void main(String[] args) { 10 | SpringApplication.run(SimpleAuthApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/AccessIsRestrictedException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.exception; 2 | 3 | public class AccessIsRestrictedException extends RuntimeException{ 4 | public AccessIsRestrictedException(String message) { 5 | super(message); 6 | } 7 | 8 | public AccessIsRestrictedException() { 9 | super("Access is restricted.Is there an ExceptionHandler for AccessIsRestricted"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/strategic/AuthRejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.strategic; 2 | 3 | import com.codingcube.simpleauth.logging.logformat.LogAuthFormat; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | public interface AuthRejectedStratagem { 9 | void doRejected(HttpServletRequest request, HttpServletResponse response, LogAuthFormat authFormat); 10 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/EffectiveStrategic.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | /** 8 | * @author CodingCube
* 9 | * Effective Record Class* 10 | */ 11 | public interface EffectiveStrategic { 12 | Boolean effective(HttpServletRequest request, SimpleJoinPoint joinPoint, Object result); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/RejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | import com.codingcube.simpleauth.logging.logformat.LogLimitFormat; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | public interface RejectedStratagem { 9 | void doRejected(HttpServletRequest request, HttpServletResponse response, LogLimitFormat limitFormat); 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/com/LimitInfoMapJUCTest.java: -------------------------------------------------------------------------------- 1 | package com; 2 | 3 | public class LimitInfoMapJUCTest { 4 | public static void main(String[] args) { 5 | JUCTest(); 6 | } 7 | 8 | public static void JUCTest(){ 9 | // final Boolean aBoolean = LimitInfoMap.addRecord("check", "CodingCube", 10, 2000); 10 | // final Boolean bBoolean = LimitInfoMap.addRecord("check", "CodingCube2", 10, 2000); 11 | // System.out.println(aBoolean); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/DefaultAuthHandlerChain.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | /** 6 | * @author CodingCube
7 | * Default Authentication Handler Chain Class* 8 | */ 9 | @Component 10 | public final class DefaultAuthHandlerChain extends AutoAuthHandlerChain { 11 | @Override 12 | public void addChain() { 13 | //The default is empty. 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/annotation/SimpleCache.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.TYPE}) 10 | public @interface SimpleCache { 11 | //"false" is no cache 12 | //"singleton" 13 | String type() default "false"; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/strategic/SignStrategic.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.strategic; 2 | 3 | import com.codingcube.simpleauth.limit.strategic.SimpleJoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | /** 9 | * @author CodingCube
* 10 | * sign Generation Strategy* 11 | */ 12 | public interface SignStrategic { 13 | String sign(HttpServletRequest request, SimpleJoinPoint joinPoint); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/ScopeType.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | /** 4 | * @author dhc 5 | */ 6 | public enum ScopeType { 7 | /** 8 | * false 9 | */ 10 | FALSE, 11 | /** 12 | * proto 13 | */ 14 | PROTO, 15 | /** 16 | * singleton 17 | */ 18 | SINGLETON, 19 | /** 20 | * request 21 | */ 22 | REQUEST, 23 | /** 24 | * session 25 | */ 26 | SESSION 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/NullTarget.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 4 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 5 | import com.codingcube.simpleauth.validated.strategic.ValidateRejectedStratagem; 6 | 7 | 8 | public abstract class NullTarget implements 9 | ValidateRejectedStratagem, 10 | RejectedStratagem, 11 | AuthRejectedStratagem { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/strategic/DefaultItemStrategic.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.strategic; 2 | 3 | import com.codingcube.simpleauth.limit.strategic.SimpleJoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | public class DefaultItemStrategic implements SignStrategic{ 9 | @Override 10 | public String sign(HttpServletRequest request, SimpleJoinPoint joinPoint) { 11 | return request.getRequestURI(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/LambdaEnhance.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util; 2 | 3 | import java.util.function.BiConsumer; 4 | import java.util.function.Consumer; 5 | 6 | public class LambdaEnhance { 7 | public static Consumer consumerWithIndex(BiConsumer consumer) { 8 | class Obj { 9 | int i; 10 | } 11 | Obj obj = new Obj(); 12 | return t -> { 13 | int index = obj.i++; 14 | consumer.accept(t, index); 15 | }; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/annotation/EnableDynamicLimit.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.annotation; 2 | 3 | import com.codingcube.simpleauth.limit.dynamic.sign.DynamicLimitSignBean; 4 | import org.springframework.context.annotation.Import; 5 | 6 | import java.lang.annotation.*; 7 | 8 | /** 9 | * @author CodingCube
10 | * Turn on goble limit * 11 | */ 12 | @Target({ElementType.TYPE}) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Inherited 15 | @Import({DynamicLimitSignBean.class}) 16 | public @interface EnableDynamicLimit { 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/ProfileConfigurationHandlerChain.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | import com.codingcube.simpleauth.autoconfig.domain.HandlerChain; 4 | 5 | import java.util.List; 6 | 7 | public class ProfileConfigurationHandlerChain extends AutoAuthHandlerChain { 8 | public ProfileConfigurationHandlerChain(List autoAuthServiceList) { 9 | this.autoAuthServiceList = autoAuthServiceList; 10 | } 11 | 12 | @Override 13 | public void addChain() { 14 | //pass 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/DefaultEffectiveStrategic.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | /** 8 | * @author CodingCube
* 9 | * Default Effective Record Class* 10 | */ 11 | public class DefaultEffectiveStrategic implements EffectiveStrategic { 12 | 13 | @Override 14 | public Boolean effective(HttpServletRequest request, SimpleJoinPoint joinPoint, Object result) { 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/annotation/EnableDynamicAuthRequest.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.annotation; 2 | 3 | import com.codingcube.simpleauth.auth.dynamic.sign.DynamicSignBean; 4 | import org.springframework.context.annotation.Import; 5 | 6 | import java.lang.annotation.*; 7 | 8 | /** 9 | * @author CodingCube
10 | * Turn on dynamic rights management * 11 | */ 12 | @Target({ElementType.TYPE}) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Inherited 15 | @Import(DynamicSignBean.class) 16 | public @interface EnableDynamicAuthRequest { 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/scheduled/AutoClearExpiredRecordScheduled.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.scheduled; 2 | 3 | import com.codingcube.simpleauth.limit.LimitInfoUtil; 4 | import org.springframework.scheduling.annotation.Scheduled; 5 | 6 | /** 7 | * @author CodingCube
* 8 | * Configuration Class for Scheduled Cleanup of Expired Access Records* 9 | */ 10 | public class AutoClearExpiredRecordScheduled { 11 | @Scheduled(cron = "${simple-auth.clear.cron:0 30 3 * * 1}") 12 | public void execute(){ 13 | LimitInfoUtil.clearExpiredRecord(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/strategic/DefaultSignStrategic.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.strategic; 2 | 3 | import com.codingcube.simpleauth.limit.strategic.SimpleJoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | /** 9 | * @author CodingCube
* 10 | * Default sign Generation Strategy Class* 11 | */ 12 | public class DefaultSignStrategic implements SignStrategic{ 13 | @Override 14 | public String sign(HttpServletRequest request, SimpleJoinPoint joinPoint) { 15 | return request.getRemoteAddr(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/strategic/DefaultValidateRejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.strategic; 2 | 3 | import com.codingcube.simpleauth.exception.ValidateException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | public class DefaultValidateRejectedStratagem implements ValidateRejectedStratagem{ 9 | @Override 10 | public void doRejected(HttpServletRequest request, HttpServletResponse response, Object validationObj) { 11 | throw new ValidateException(validationObj + " verification failed."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/prepare/VerifyKeyHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler.prepare; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.properties.AuthProper; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | public class VerifyKeyHandler extends AutoAuthHandler { 9 | @Override 10 | public boolean isAuthor(HttpServletRequest request, String permission) { 11 | return AuthProper.getVerifyValueStatic().equals( 12 | request.getParameter(AuthProper.getVerifyKeyStatic()) 13 | ); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/AutoAuthHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | 4 | import com.codingcube.simpleauth.auth.PermissionOperate; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | /** 9 | * @author CodingCube
10 | * Authentication Handler* 11 | */ 12 | public abstract class AutoAuthHandler implements PermissionOperate { 13 | 14 | /** 15 | * Judge whether the permission is met. * 16 | * @param request HttpServletRequest 17 | * @return True passes false, but not true. 18 | */ 19 | public abstract boolean isAuthor(HttpServletRequest request, String permission); 20 | 21 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/Scope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.util.support.BeanDefinition; 4 | 5 | /** 6 | * @author dhc 7 | */ 8 | public abstract class Scope { 9 | 10 | /** 11 | * init JavaBean 12 | * @param beanDefinition beanDefinition 13 | * @return JavaBean 14 | */ 15 | public abstract T initBean(BeanDefinition beanDefinition); 16 | 17 | /** 18 | * get JavaBean 19 | * @param beanDefinition beanDefinition 20 | * @return JavaBean 21 | */ 22 | public abstract T getBean(BeanDefinition beanDefinition); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/strategic/DefaultAuthRejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.strategic; 2 | 3 | import com.codingcube.simpleauth.exception.PermissionsException; 4 | import com.codingcube.simpleauth.logging.logformat.LogAuthFormat; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | public class DefaultAuthRejectedStratagem implements AuthRejectedStratagem { 10 | @Override 11 | public void doRejected(HttpServletRequest request, HttpServletResponse response, LogAuthFormat authFormat) { 12 | throw new PermissionsException("lack of permissions"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/FalseScope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.util.support.BeanDefinition; 4 | import org.springframework.cglib.core.ReflectUtils; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | 8 | public class FalseScope extends Scope{ 9 | @Override 10 | public T initBean(BeanDefinition beanDefinition) { 11 | return null; 12 | } 13 | 14 | @Override 15 | public T getBean(BeanDefinition beanDefinition) { 16 | final Class clazz = beanDefinition.getClazz(); 17 | return (T) ReflectUtils.newInstance(clazz); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/ProtoScope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.util.support.BeanDefinition; 4 | import org.springframework.cglib.core.ReflectUtils; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | 8 | public class ProtoScope extends Scope{ 9 | @Override 10 | public T initBean(BeanDefinition beanDefinition) { 11 | return null; 12 | } 13 | 14 | @Override 15 | public T getBean(BeanDefinition beanDefinition) { 16 | final Class clazz = beanDefinition.getClazz(); 17 | return (T) ReflectUtils.newInstance(clazz); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/dynamic/sign/DynamicSignBean.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.dynamic.sign; 2 | 3 | import com.codingcube.simpleauth.auth.dynamic.FilterAuthWebConfig; 4 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ConfigurableApplicationContext; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | public class DynamicSignBean { 10 | @Bean 11 | @ConditionalOnMissingBean(FilterAuthWebConfig.class) 12 | public FilterAuthWebConfig filterAuthWebConfig(){ 13 | return new FilterAuthWebConfig(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/Config2SimpleAuthObject.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig; 2 | 3 | import com.codingcube.simpleauth.autoconfig.domain.SimpleAuthConfig; 4 | 5 | import java.util.List; 6 | 7 | 8 | public interface Config2SimpleAuthObject { 9 | void initAttr(SimpleAuthConfig simpleAuthConfig); 10 | void initConfig(); 11 | List getConfig(); 12 | void initPaths(); 13 | void initHandler(); 14 | void initHandlerChain(); 15 | void initLimit(); 16 | 17 | default void init(){ 18 | initConfig(); 19 | initPaths(); 20 | initHandler(); 21 | initLimit(); 22 | initHandlerChain(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/ClearProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | 6 | @ConfigurationProperties(prefix = "simple-auth.clear") 7 | public class ClearProper { 8 | private boolean clear = false; 9 | private String cron = "0 30 3 * * 1"; 10 | 11 | public boolean isClear() { 12 | return clear; 13 | } 14 | 15 | public void setClear(boolean clear) { 16 | this.clear = clear; 17 | } 18 | 19 | public String getCron() { 20 | return cron; 21 | } 22 | 23 | public void setCron(String cron) { 24 | this.cron = cron; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/DefaultLimitRejectedStratagem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | import com.codingcube.simpleauth.exception.AccessIsRestrictedException; 4 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 5 | import com.codingcube.simpleauth.logging.logformat.LogLimitFormat; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | public class DefaultLimitRejectedStratagem implements RejectedStratagem{ 11 | @Override 12 | public void doRejected(HttpServletRequest request, HttpServletResponse response, LogLimitFormat limitFormat) { 13 | throw new AccessIsRestrictedException(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/ValidateException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.exception; 2 | 3 | public class ValidateException extends RuntimeException{ 4 | public ValidateException() { 5 | } 6 | 7 | public ValidateException(String message) { 8 | super(message); 9 | } 10 | 11 | public ValidateException(String message, Throwable cause) { 12 | super(message, cause); 13 | } 14 | 15 | public ValidateException(Throwable cause) { 16 | super(cause); 17 | } 18 | 19 | public ValidateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 20 | super(message, cause, enableSuppression, writableStackTrace); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/execption/JSONParseException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.execption; 2 | 3 | public class JSONParseException extends RuntimeException{ 4 | 5 | public JSONParseException() { 6 | } 7 | 8 | public JSONParseException(String message) { 9 | super(message); 10 | } 11 | 12 | public JSONParseException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | public JSONParseException(Throwable cause) { 17 | super(cause); 18 | } 19 | 20 | public JSONParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 21 | super(message, cause, enableSuppression, writableStackTrace); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/execption/XMLParseException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.execption; 2 | 3 | public class XMLParseException extends RuntimeException{ 4 | 5 | public XMLParseException() { 6 | } 7 | 8 | public XMLParseException(String message) { 9 | super(message); 10 | } 11 | 12 | public XMLParseException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | public XMLParseException(Throwable cause) { 17 | super(cause); 18 | } 19 | 20 | public XMLParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 21 | super(message, cause, enableSuppression, writableStackTrace); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/Encryptors.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto; 2 | 3 | import com.codingcube.simpleauth.security.crypto.encryptor.ByteEncryptor; 4 | import com.codingcube.simpleauth.security.crypto.encryptor.TextEncryptor; 5 | import com.codingcube.simpleauth.security.crypto.encryptor.impl.AesByteEncryptor; 6 | import com.codingcube.simpleauth.security.crypto.encryptor.impl.TextAesEncryptor; 7 | 8 | public class Encryptors { 9 | public static ByteEncryptor stronger(String password, String salt){ 10 | return new AesByteEncryptor(password, salt); 11 | } 12 | 13 | public static TextEncryptor text(String password, String salt) { 14 | return new TextAesEncryptor(stronger(password, salt)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/TargetNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.exception; 2 | 3 | public class TargetNotFoundException extends RuntimeException { 4 | public TargetNotFoundException() { 5 | } 6 | 7 | public TargetNotFoundException(String message) { 8 | super(message); 9 | } 10 | 11 | public TargetNotFoundException(String message, Throwable cause) { 12 | super(message, cause); 13 | } 14 | 15 | public TargetNotFoundException(Throwable cause) { 16 | super(cause); 17 | } 18 | 19 | public TargetNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 20 | super(message, cause, enableSuppression, writableStackTrace); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/ValidateMethodException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.exception; 2 | 3 | public class ValidateMethodException extends RuntimeException{ 4 | 5 | public ValidateMethodException() { 6 | } 7 | 8 | public ValidateMethodException(String message) { 9 | super(message); 10 | } 11 | 12 | public ValidateMethodException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | public ValidateMethodException(Throwable cause) { 17 | super(cause); 18 | } 19 | 20 | public ValidateMethodException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 21 | super(message, cause, enableSuppression, writableStackTrace); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/annotation/SimpleValidate.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.annotation; 2 | 3 | 4 | import com.codingcube.simpleauth.util.NullTarget; 5 | import com.codingcube.simpleauth.validated.strategic.ValidateRejectedStratagem; 6 | 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}) 14 | public @interface SimpleValidate { 15 | Class value() default Object.class; 16 | String[] methods() default {}; 17 | Class rejected() default NullTarget.class; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/PermissionsException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.exception; 2 | 3 | /** 4 | * @author dhc 5 | */ 6 | public class PermissionsException extends RuntimeException{ 7 | 8 | public PermissionsException() { 9 | } 10 | 11 | public PermissionsException(String message) { 12 | super(message); 13 | } 14 | 15 | public PermissionsException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public PermissionsException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | public PermissionsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 24 | super(message, cause, enableSuppression, writableStackTrace); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/execption/ConfigurationParseException.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.execption; 2 | 3 | public class ConfigurationParseException extends RuntimeException{ 4 | public ConfigurationParseException() { 5 | } 6 | 7 | public ConfigurationParseException(String message) { 8 | super(message); 9 | } 10 | 11 | public ConfigurationParseException(String message, Throwable cause) { 12 | super(message, cause); 13 | } 14 | 15 | public ConfigurationParseException(Throwable cause) { 16 | super(cause); 17 | } 18 | 19 | public ConfigurationParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 20 | super(message, cause, enableSuppression, writableStackTrace); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/interceptor/AddXFrameOptionsInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.interceptor; 2 | 3 | import org.springframework.web.servlet.HandlerInterceptor; 4 | 5 | import javax.crypto.KeyGenerator; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | public class AddXFrameOptionsInterceptor implements HandlerInterceptor { 10 | private final String xFrameOptions; 11 | 12 | public AddXFrameOptionsInterceptor(String xFrameOptions) { 13 | this.xFrameOptions = xFrameOptions; 14 | } 15 | 16 | @Override 17 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ 18 | response.setHeader("X-Frame-Options", xFrameOptions); 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/filter/CacheRequestContentFilter.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.filter; 2 | 3 | import javax.servlet.*; 4 | import javax.servlet.http.HttpServletRequest; 5 | import java.io.IOException; 6 | 7 | public class CacheRequestContentFilter implements Filter { 8 | 9 | @Override 10 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { 11 | if (request instanceof HttpServletRequest) { 12 | String contentType = request.getContentType(); 13 | if (contentType == null || !contentType.contains("multipart/form-data")) { 14 | request = new CacheBodyHttpServletRequest((HttpServletRequest) request); 15 | } 16 | } 17 | chain.doFilter(request, response); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/interceptor/ContentSecurityPolicyInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.interceptor; 2 | 3 | import org.springframework.web.servlet.HandlerInterceptor; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | public class ContentSecurityPolicyInterceptor implements HandlerInterceptor { 9 | private final String contentSecurityPolicy; 10 | 11 | public ContentSecurityPolicyInterceptor(String contentSecurityPolicy) { 12 | this.contentSecurityPolicy = contentSecurityPolicy; 13 | } 14 | 15 | @Override 16 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ 17 | response.setHeader("Content-Security-Policy", contentSecurityPolicy); 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/annotation/EnableAutoClearExpiredRecord.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.annotation; 2 | 3 | import com.codingcube.simpleauth.limit.scheduled.AutoClearExpiredRecordScheduled; 4 | import org.springframework.context.annotation.Import; 5 | import org.springframework.scheduling.annotation.EnableScheduling; 6 | 7 | import java.lang.annotation.*; 8 | 9 | /** 10 | * @author CodingCube
11 | * Turn on the function of regularly cleaning expired access records.
12 | * By default, cleanup occurs every Monday at 3:30 AM. You can configure a specific schedule using the 'simple-auth.cron' property in the configuration file.* 13 | */ 14 | @Target({ElementType.TYPE}) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Inherited 17 | @EnableScheduling 18 | @Import(AutoClearExpiredRecordScheduled.class) 19 | public @interface EnableAutoClearExpiredRecord { 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/DefaultAuthHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import java.security.InvalidParameterException; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | /** 11 | * @author CodingCube
12 | * Default Authentication Handler Class* 13 | */ 14 | @Component 15 | public final class DefaultAuthHandler extends AutoAuthHandler { 16 | @Override 17 | public boolean isAuthor(HttpServletRequest request, String permission) { 18 | final List userPermissions = getPermissions(); 19 | if (userPermissions!=null){ 20 | return userPermissions.contains(permission); 21 | }else { 22 | throw new InvalidParameterException("Missing permission list"); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SimpleAuth 2 | 👉[中文官方文档](https://liuye744.github.io/simpleauthDoc/doc1/index.html) 3 | 4 | 👉[English Document](https://liuye744.github.io/simpleauthDoc/doc2/) 5 | 6 | # 特性 7 | 这是一款基于SpringBoot的轻量化渐进式的权限校验和访问控制的框架。适用于快速构建中小型项目。 8 | 9 | 10 | # 适用场景 11 | * 项目复杂度不高,权限校验简单 12 | * 鉴权方案未固定,随时可能更改 13 | * 快速构建RBAC(基于角色的访问控制) 14 | 15 | * 限制用户访问次数 16 | * 小粒度的访问控制 17 | * 简单的安全防护 18 | 19 | # Features 20 | This is a lightweight and progressive framework for permission validation and access control based on SpringBoot. It is suitable for quickly building small to medium-sized projects. It's easy to get started with. 21 | 22 | 23 | # Use Cases 24 | * Low project complexity with simple permission validation 25 | * Flexible authentication requirements subject to change 26 | * Quick setup for RBAC (Role-Based Access Control) 27 | 28 | * Limiting user access counts 29 | * Fine-grained access control 30 | * Simple security measures -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/config/AuthAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.config; 2 | 3 | import com.codingcube.simpleauth.properties.ClearProper; 4 | import org.springframework.boot.context.properties.ConfigurationPropertiesScan; 5 | import org.springframework.context.annotation.ComponentScan; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | 9 | /** 10 | * @author CodingCube
11 | * Directory Scanning Configuration* 12 | */ 13 | @Configuration 14 | @ComponentScan("com.codingcube.simpleauth.auth") 15 | @ComponentScan("com.codingcube.simpleauth.limit") 16 | @ComponentScan("com.codingcube.simpleauth.validated") 17 | @ComponentScan("com.codingcube.simpleauth.logging") 18 | @ComponentScan("com.codingcube.simpleauth.properties") 19 | @ComponentScan("com.codingcube.simpleauth.security") 20 | @ConfigurationPropertiesScan("com.codingcube.simpleauth.properties") 21 | public class AuthAutoConfiguration { 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/sign/DiffParameterSign.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic.sign; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 4 | import com.codingcube.simpleauth.limit.strategic.SimpleJoinPoint; 5 | import org.aspectj.lang.ProceedingJoinPoint; 6 | import org.aspectj.lang.Signature; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | public class DiffParameterSign implements SignStrategic { 11 | @Override 12 | public String sign(HttpServletRequest request, SimpleJoinPoint joinPoint) { 13 | final Object[] args = joinPoint.getArgs(); 14 | final Signature signature = joinPoint.getSignature(); 15 | StringBuilder sb = new StringBuilder(); 16 | sb.append(signature); 17 | for (Object arg : args) { 18 | sb.append("$"); 19 | sb.append(arg.toString()); 20 | } 21 | return sb.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/encryptor/impl/TextAesEncryptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.encryptor.impl; 2 | 3 | import com.codingcube.simpleauth.security.crypto.encryptor.ByteEncryptor; 4 | import com.codingcube.simpleauth.security.crypto.encryptor.TextEncryptor; 5 | 6 | import java.nio.charset.StandardCharsets; 7 | 8 | public class TextAesEncryptor implements TextEncryptor { 9 | private final ByteEncryptor byteEncryptor; 10 | 11 | public TextAesEncryptor(ByteEncryptor byteEncryptor) { 12 | this.byteEncryptor = byteEncryptor; 13 | } 14 | 15 | @Override 16 | public String encrypt(String text) { 17 | return new String(byteEncryptor.encrypt(text.getBytes(StandardCharsets.UTF_8))); 18 | } 19 | 20 | @Override 21 | public String decrypt(String encryptedText) { 22 | return new String(byteEncryptor.encrypt(encryptedText.getBytes(StandardCharsets.UTF_8))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/sign/DynamicLimitSignBean.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic.sign; 2 | 3 | import com.codingcube.simpleauth.limit.dynamic.FilterLimitWebConfig; 4 | import com.codingcube.simpleauth.limit.dynamic.advice.DynamicLimitAdvice; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | public class DynamicLimitSignBean { 10 | 11 | @Bean 12 | @ConditionalOnMissingBean(DynamicLimitAdvice.class) 13 | public DynamicLimitAdvice filterAuthWebConfig(LogFactory logFactory){ 14 | return new DynamicLimitAdvice(logFactory); 15 | } 16 | 17 | @Bean 18 | @ConditionalOnMissingBean(FilterLimitWebConfig.class) 19 | public FilterLimitWebConfig filterLimitWebConfig(LogFactory logFactory){ 20 | return new FilterLimitWebConfig(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/ApplicationContextProvider.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * @author CodingCube
* 10 | * Utility Class for Obtaining Beans* 11 | */ 12 | @Component 13 | public class ApplicationContextProvider implements ApplicationContextAware { 14 | private static ApplicationContext applicationContextSpring; 15 | 16 | @Override 17 | public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 18 | applicationContextSpring = applicationContext; 19 | } 20 | 21 | /** 22 | * Get Bean through class 23 | */ 24 | public static T getBean(Class clazz) { 25 | return applicationContextSpring.getBean(clazz); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/util/TokenLimit.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.util; 2 | 3 | public interface TokenLimit { 4 | /** 5 | * Try to get* 6 | * @return Is it successful? 7 | */ 8 | boolean tryAcquire(); 9 | 10 | /** 11 | * init * 12 | * @param limit Limit the number of times 13 | * @param seconds Restricted time 14 | */ 15 | void init(Integer limit, Integer seconds); 16 | 17 | /** 18 | * init * 19 | * @param capacity capacity 20 | * @param fillRate Token issuing speed 21 | */ 22 | void init(int capacity, double fillRate); 23 | 24 | /** 25 | * Remove the "latest" operation. * 26 | */ 27 | void removeFirst(); 28 | 29 | /** 30 | * Requested quantity * 31 | */ 32 | int size(); 33 | 34 | /** 35 | * requestable amount * 36 | */ 37 | int optSize(); 38 | 39 | /** 40 | * max requestable amount * 41 | */ 42 | int maxOptSize(); 43 | 44 | /** 45 | * sync data * 46 | */ 47 | void sync(); 48 | 49 | Object getSyncMutex(); 50 | } 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 CodingCube 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/provider/CacheLimitItemProvider.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic.provider; 2 | 3 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 4 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItemProvider; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public abstract class CacheLimitItemProvider implements RequestLimitItemProvider { 10 | List limitItemList = new ArrayList<>(); 11 | volatile boolean updateTag = true; 12 | final Object singletonMutex = new Object(); 13 | 14 | @Override 15 | public final List getRequestLimitItem() { 16 | if (updateTag) { 17 | synchronized (singletonMutex) { 18 | if (updateTag){ 19 | limitItemList = getLimitItem(); 20 | updateTag = false; 21 | } 22 | } 23 | } 24 | return limitItemList; 25 | } 26 | 27 | public void update() { 28 | updateTag = true; 29 | } 30 | 31 | public abstract List getLimitItem(); 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2012 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.codingcube.simpleauth.logging; 17 | 18 | /** 19 | * @author CodingCube 20 | * log interface 21 | * 22 | */ 23 | public interface Log { 24 | 25 | boolean isDebugEnabled(); 26 | 27 | boolean isTraceEnabled(); 28 | 29 | void error(String s, Throwable e); 30 | 31 | void error(String s); 32 | 33 | void debug(String s); 34 | 35 | void trace(String s); 36 | 37 | void warn(String s); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/cache/impl/DefaultCache.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.cache.impl; 2 | 3 | import com.codingcube.simpleauth.limit.cache.KeyCache; 4 | 5 | import java.util.Map; 6 | import java.util.Set; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | 9 | public class DefaultCache implements KeyCache { 10 | private final Map ban = new ConcurrentHashMap<>(); 11 | 12 | 13 | @Override 14 | public T remove(String key) { 15 | return ban.remove(key); 16 | } 17 | 18 | @Override 19 | public T get(String key) { 20 | return ban.get(key); 21 | } 22 | 23 | @Override 24 | public T put(String key, T data) { 25 | return ban.put(key, data); 26 | } 27 | 28 | @Override 29 | public int size() { 30 | return ban.size(); 31 | } 32 | 33 | @Override 34 | public boolean containsKey(String key) { 35 | return ban.containsKey(key); 36 | } 37 | 38 | @Override 39 | public Set keySet() { 40 | return ban.keySet(); 41 | } 42 | 43 | @Override 44 | public void clear() { 45 | ban.clear(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/handler/session/ChangeSessionHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.handler.session; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.logging.Log; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpSession; 10 | 11 | @Component 12 | public class ChangeSessionHandler extends AutoAuthHandler { 13 | private final Log log; 14 | 15 | public ChangeSessionHandler(LogFactory logFactory) { 16 | this.log = logFactory.getLog(this.getClass()); 17 | } 18 | 19 | @Override 20 | public boolean isAuthor(HttpServletRequest request, String permission) { 21 | final HttpSession session = request.getSession(false); 22 | if (session != null){ 23 | final String sessionId = session.getId(); 24 | session.invalidate(); 25 | final HttpSession newSession = request.getSession(true); 26 | log.debug("Changed session id from "+sessionId + " to " + newSession.getId()); 27 | } 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/LimitInfoMapTest.java: -------------------------------------------------------------------------------- 1 | package com; 2 | 3 | import com.codingcube.simpleauth.limit.LimitInfoUtil; 4 | 5 | public class LimitInfoMapTest { 6 | public static void main(String[] args) { 7 | // baseTest(); 8 | System.out.println(); 9 | } 10 | 11 | // public static void baseTest(){ 12 | // int i = 0; 13 | // while (true){ 14 | // i++; 15 | // final Boolean aBoolean = LimitInfoUtil.addRecord("check", "CodingCube", 10, 20, 60); 16 | // System.out.println(aBoolean); 17 | // } 18 | // } 19 | 20 | // public static void JUCTest(){ 21 | // new Thread(()->{ 22 | // final Boolean aBoolean = LimitInfoMap.addRecord("check", "CodingCube", 10, 2000); 23 | // final Boolean bBoolean = LimitInfoMap.addRecord("check", "CodingCube2", 10, 2000); 24 | // System.out.println(aBoolean); 25 | // }).start(); 26 | // new Thread(()->{ 27 | // final Boolean aBoolean = LimitInfoMap.addRecord("check", "CodingCube", 10, 2000); 28 | // final Boolean bBoolean = LimitInfoMap.addRecord("check", "CodingCube2", 10, 2000); 29 | // System.out.println(aBoolean); 30 | // }).start(); 31 | // } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/exception/LogException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2012 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.codingcube.simpleauth.exception; 17 | 18 | 19 | /** 20 | * @author CodingCube 21 | */ 22 | public class LogException extends RuntimeException { 23 | 24 | public LogException() { 25 | super(); 26 | } 27 | 28 | public LogException(String message) { 29 | super(message); 30 | } 31 | 32 | public LogException(String message, Throwable cause) { 33 | super(message, cause); 34 | } 35 | 36 | public LogException(Throwable cause) { 37 | super(cause); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/dynamic/provider/CacheAuthItemProvider.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.dynamic.provider; 2 | 3 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItem; 4 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItemProvider; 5 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 6 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItemProvider; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public abstract class CacheAuthItemProvider implements RequestAuthItemProvider { 12 | List limitItemList = new ArrayList<>(); 13 | volatile boolean updateTag = true; 14 | final Object singletonMutex = new Object(); 15 | 16 | @Override 17 | public final List getRequestAuthItem() { 18 | if (updateTag) { 19 | synchronized (singletonMutex) { 20 | if (updateTag){ 21 | limitItemList = getLimitItem(); 22 | updateTag = false; 23 | } 24 | } 25 | } 26 | return limitItemList; 27 | } 28 | 29 | public void update() { 30 | updateTag = true; 31 | } 32 | 33 | public abstract List getLimitItem(); 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/dynamic/FilterAuthWebConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.dynamic; 2 | 3 | 4 | import com.codingcube.simpleauth.auth.interceptor.DynamicAuthInterceptor; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | import javax.annotation.Resource; 12 | 13 | /** 14 | * @author CodingCube
15 | * Dynamic Permission Filtering Configuration Class* 16 | */ 17 | @Configuration 18 | @ConditionalOnProperty("simple-auth.func.dynamic-auth") 19 | public class FilterAuthWebConfig implements WebMvcConfigurer { 20 | @Resource 21 | RequestAuthItemProvider requestAuthItemProvider; 22 | @Resource 23 | private ApplicationContext applicationContext; 24 | @Resource 25 | private LogFactory logFactory; 26 | 27 | @Override 28 | public void addInterceptors(InterceptorRegistry registry) { 29 | registry.addInterceptor(new DynamicAuthInterceptor(requestAuthItemProvider, applicationContext, logFactory)).addPathPatterns("/*").order(Integer.MAX_VALUE); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/domain/ReflectMethod.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.domain; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | public class ReflectMethod { 6 | private final Object instance; 7 | private Method method; 8 | private Class param; 9 | ReflectMethod next; 10 | 11 | public ReflectMethod(Object instance, Method method, Class param, ReflectMethod next) { 12 | this.instance = instance; 13 | this.method = method; 14 | this.param = param; 15 | this.next = next; 16 | } 17 | 18 | public ReflectMethod(Object instance, Method method, Class param) { 19 | this.instance = instance; 20 | this.method = method; 21 | this.param = param; 22 | } 23 | 24 | public Object getInstance() { 25 | return instance; 26 | } 27 | 28 | public Method getMethod() { 29 | return method; 30 | } 31 | 32 | public void setMethod(Method method) { 33 | this.method = method; 34 | } 35 | 36 | public Class getParam() { 37 | return param; 38 | } 39 | 40 | public void setParam(Class param) { 41 | this.param = param; 42 | } 43 | 44 | public ReflectMethod getNext() { 45 | return next; 46 | } 47 | 48 | public void setNext(ReflectMethod next) { 49 | this.next = next; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/annotation/SimpleAuth.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.annotation; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandlerChain; 5 | import com.codingcube.simpleauth.auth.handler.DefaultAuthHandler; 6 | import com.codingcube.simpleauth.auth.handler.DefaultAuthHandlerChain; 7 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 8 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 9 | import com.codingcube.simpleauth.util.NullTarget; 10 | 11 | import java.lang.annotation.ElementType; 12 | import java.lang.annotation.Retention; 13 | import java.lang.annotation.RetentionPolicy; 14 | import java.lang.annotation.Target; 15 | 16 | /** 17 | * @author CodingCube
18 | * Authentication* 19 | */ 20 | @Retention(RetentionPolicy.RUNTIME) 21 | @Target({ElementType.METHOD, ElementType.TYPE}) 22 | public @interface SimpleAuth { 23 | //permission 24 | String value() default ""; 25 | //auth Handler Class 26 | Class[] handler() default DefaultAuthHandler.class; 27 | //Multiple auth Handler Class 28 | Class[] handlerChain() default DefaultAuthHandlerChain.class; 29 | //rejected Stratagem 30 | Class rejected() default NullTarget.class; 31 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/BeanDefinition.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support; 2 | 3 | import com.codingcube.simpleauth.util.support.scope.ScopeType; 4 | 5 | /** 6 | * @author dhc 7 | */ 8 | public class BeanDefinition { 9 | ScopeType type; 10 | String beanName; 11 | Class clazz; 12 | 13 | public BeanDefinition(Class clazz) { 14 | this.clazz = clazz; 15 | type = ScopeType.SINGLETON; 16 | this.beanName = clazz.getName(); 17 | } 18 | 19 | public BeanDefinition(Class clazz, ScopeType type) { 20 | this.clazz = clazz; 21 | this.beanName = clazz.getName(); 22 | this.type = type; 23 | } 24 | 25 | public BeanDefinition(Class clazz, String beanName, ScopeType type) { 26 | this.type = type; 27 | this.beanName = beanName; 28 | this.clazz = clazz; 29 | } 30 | 31 | public ScopeType getType() { 32 | return type; 33 | } 34 | 35 | public void setType(ScopeType type) { 36 | this.type = type; 37 | } 38 | 39 | public String getBeanName() { 40 | return beanName; 41 | } 42 | 43 | public void setBeanName(String beanName) { 44 | this.beanName = beanName; 45 | } 46 | 47 | public Class getClazz() { 48 | return clazz; 49 | } 50 | 51 | public void setClazz(Class clazz) { 52 | this.clazz = clazz; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/json/utils/JSONUtils.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.json.utils; 2 | 3 | 4 | import org.springframework.boot.configurationprocessor.json.JSONArray; 5 | import org.springframework.boot.configurationprocessor.json.JSONException; 6 | import org.springframework.boot.configurationprocessor.json.JSONObject; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class JSONUtils { 12 | 13 | public static List getStringList(JSONObject jsonObject, String key){ 14 | List list = new ArrayList<>(jsonObject.length()); 15 | try { 16 | final JSONArray jsonArray = jsonObject.getJSONArray(key); 17 | for (int i = 0; i < jsonArray.length(); i++) { 18 | list.add((String) jsonArray.get(i)); 19 | } 20 | } catch (JSONException e) { 21 | return null; 22 | } 23 | 24 | return list; 25 | } 26 | public static JSONObject geJSONObject(JSONObject jsonObject, String key){ 27 | try { 28 | return jsonObject.getJSONObject(key); 29 | } catch (JSONException e) { 30 | return null; 31 | } 32 | } 33 | 34 | public static JSONArray geJSONArray(JSONObject jsonObject, String key){ 35 | try { 36 | return jsonObject.getJSONArray(key); 37 | } catch (JSONException e) { 38 | return null; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/annotation/IsAuthor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.annotation; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandlerChain; 5 | import com.codingcube.simpleauth.auth.handler.DefaultAuthHandler; 6 | import com.codingcube.simpleauth.auth.handler.DefaultAuthHandlerChain; 7 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 8 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 9 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 10 | import com.codingcube.simpleauth.util.NullTarget; 11 | 12 | import java.lang.annotation.ElementType; 13 | import java.lang.annotation.Retention; 14 | import java.lang.annotation.RetentionPolicy; 15 | import java.lang.annotation.Target; 16 | 17 | /** 18 | * @author CodingCube
19 | * Authentication* 20 | */ 21 | @Retention(RetentionPolicy.RUNTIME) 22 | @Target({ElementType.METHOD, ElementType.TYPE}) 23 | public @interface IsAuthor { 24 | //permission 25 | String value() default ""; 26 | //auth Handler Class 27 | Class[] handler() default DefaultAuthHandler.class; 28 | //Multiple auth Handler Class 29 | Class[] handlerChain() default DefaultAuthHandlerChain.class; 30 | //rejected Stratagem 31 | Class rejected() default NullTarget.class; 32 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/FilterLimitWebConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic; 2 | 3 | 4 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItemProvider; 5 | import com.codingcube.simpleauth.auth.interceptor.DynamicAuthInterceptor; 6 | import com.codingcube.simpleauth.logging.LogFactory; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 8 | import org.springframework.context.ApplicationContext; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 12 | 13 | import javax.annotation.Resource; 14 | 15 | /** 16 | * @author CodingCube
17 | * Dynamic Permission Filtering Configuration Class* 18 | */ 19 | @Configuration 20 | @ConditionalOnProperty("simple-auth.func.dynamic-limit") 21 | public class FilterLimitWebConfig implements WebMvcConfigurer { 22 | @Resource 23 | RequestLimitItemProvider requestLimitItemProvider; 24 | @Resource 25 | private ApplicationContext applicationContext; 26 | @Resource 27 | private LogFactory logFactory; 28 | 29 | @Override 30 | public void addInterceptors(InterceptorRegistry registry) { 31 | registry.addInterceptor(new DynamicLimitInterceptor(requestLimitItemProvider, applicationContext, logFactory)).addPathPatterns("/*").order(Integer.MAX_VALUE); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/logformat/LogValidatedFormat.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.logging.logformat; 2 | 3 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 4 | 5 | public class LogValidatedFormat { 6 | private final Class validateObjClass; 7 | private final Class validateTargetClass; 8 | private final String validateTarget; 9 | private final Boolean passOrNot; 10 | 11 | public LogValidatedFormat(Class validateObjClass, Class validateTargetClass, String validateTarget, Boolean passOrNot) { 12 | this.validateObjClass = validateObjClass; 13 | this.validateTargetClass = validateTargetClass; 14 | this.validateTarget = validateTarget; 15 | this.passOrNot = passOrNot; 16 | } 17 | 18 | public Class getValidateTargetClass() { 19 | return validateTargetClass; 20 | } 21 | 22 | public Class getValidateObjClass() { 23 | return validateObjClass; 24 | } 25 | 26 | public Boolean getPassOrNot() { 27 | return passOrNot; 28 | } 29 | 30 | public String getValidateTarget() { 31 | return validateTarget; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "SimpleAuth validate => \r\n" + 37 | "\tvalidateObj: " + validateObjClass + "\r\n" + 38 | "\tvalidateTarget: " + validateTargetClass + "\r\n" + 39 | "\tpass or not: " + passOrNot + "\r\n"; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/autoconfig/FilterAuthWebAutoConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.autoconfig; 2 | 3 | import com.codingcube.simpleauth.autoconfig.domain.SimpleAuthConfig; 4 | import com.codingcube.simpleauth.logging.LogFactory; 5 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 10 | import javax.annotation.Resource; 11 | 12 | /** 13 | * @author CodingCube 14 | */ 15 | @Configuration 16 | public class FilterAuthWebAutoConfig implements WebMvcConfigurer { 17 | @Resource 18 | private ApplicationContext applicationContext; 19 | @Resource 20 | private LogFactory logFactory; 21 | 22 | @Override 23 | public void addInterceptors(InterceptorRegistry registry) { 24 | final SimpleAuthConfig simpleAuthConfig = AuthHandlerUtil.simpleAuthConfig; 25 | if (simpleAuthConfig != null){ 26 | if (simpleAuthConfig.getHandlerMap().size() != 0 27 | || 28 | simpleAuthConfig.getHandlerChainMap().size() != 0) { 29 | registry.addInterceptor(new AutoConfigAuthInterceptor(applicationContext, logFactory)).addPathPatterns("/**").order(Integer.MAX_VALUE); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/domain/Paths.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.domain; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | 5 | import java.util.List; 6 | 7 | public class Paths { 8 | @JSONField(name = "id") 9 | private String id; 10 | @JSONField(name = "permission") 11 | private String permission; 12 | @JSONField(name = "path") 13 | private List path; 14 | 15 | public Paths(String id, List path) { 16 | this.id = id; 17 | this.path = path; 18 | } 19 | 20 | public Paths(String id, String permission, List path) { 21 | this.id = id; 22 | this.permission = permission; 23 | this.path = path; 24 | } 25 | 26 | public void setId(String id) { 27 | this.id = id; 28 | } 29 | 30 | public String getPermission() { 31 | return permission; 32 | } 33 | 34 | public void setPermission(String permission) { 35 | this.permission = permission; 36 | } 37 | 38 | public Paths(String id) { 39 | this.id = id; 40 | } 41 | 42 | public List getPath() { 43 | return path; 44 | } 45 | 46 | public void setPath(List path) { 47 | this.path = path; 48 | } 49 | 50 | public String getId() { 51 | return id; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "Paths{" + "id='" + id + '\'' + 57 | ", path=" + path + 58 | '}'; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/strategic/SimpleJoinPoint.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.strategic; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.Signature; 6 | import org.aspectj.lang.reflect.SourceLocation; 7 | 8 | public class SimpleJoinPoint implements JoinPoint { 9 | private final ProceedingJoinPoint joinPoint; 10 | 11 | public SimpleJoinPoint(ProceedingJoinPoint joinPoint) { 12 | this.joinPoint = joinPoint; 13 | } 14 | 15 | @Override 16 | public String toShortString() { 17 | return joinPoint.toShortString(); 18 | } 19 | 20 | @Override 21 | public String toLongString() { 22 | return joinPoint.toLongString(); 23 | } 24 | 25 | @Override 26 | public Object getThis() { 27 | return joinPoint.getThis(); 28 | } 29 | 30 | @Override 31 | public Object getTarget() { 32 | return joinPoint.getTarget(); 33 | } 34 | 35 | @Override 36 | public Object[] getArgs() { 37 | return joinPoint.getArgs(); 38 | } 39 | 40 | @Override 41 | public Signature getSignature() { 42 | return joinPoint.getSignature(); 43 | } 44 | 45 | @Override 46 | public SourceLocation getSourceLocation() { 47 | return joinPoint.getSourceLocation(); 48 | } 49 | 50 | @Override 51 | public String getKind() { 52 | return joinPoint.getKind(); 53 | } 54 | 55 | @Override 56 | public StaticPart getStaticPart() { 57 | return joinPoint.getStaticPart(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/domain/SimpleAuthConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.domain; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | public class SimpleAuthConfig { 7 | Map handlerMap; 8 | Map limitMap; 9 | Map handlerChainMap; 10 | Map pathsMap; 11 | 12 | public SimpleAuthConfig(Map handlerMap, Map limitMap, Map pathsMap, Map handlerChainMap) { 13 | this.handlerMap = handlerMap; 14 | this.limitMap = limitMap; 15 | this.pathsMap = pathsMap; 16 | this.handlerChainMap = handlerChainMap; 17 | } 18 | 19 | public Map getHandlerMap() { 20 | return handlerMap; 21 | } 22 | 23 | public void setHandlerMap(Map handlerMap) { 24 | this.handlerMap = handlerMap; 25 | } 26 | 27 | public Map getLimitMap() { 28 | return limitMap; 29 | } 30 | 31 | public void setLimitMap(Map limitMap) { 32 | this.limitMap = limitMap; 33 | } 34 | 35 | public Map getPathsMap() { 36 | return pathsMap; 37 | } 38 | 39 | public void setPathsMap(Map pathsMap) { 40 | this.pathsMap = pathsMap; 41 | } 42 | 43 | public Map getHandlerChainMap() { 44 | return handlerChainMap; 45 | } 46 | 47 | public void setHandlerChainMap(Map handlerChainMap) { 48 | this.handlerChainMap = handlerChainMap; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/nologging/NoLoggingImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2012 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.codingcube.simpleauth.logging.nologging; 17 | 18 | 19 | import com.codingcube.simpleauth.logging.Log; 20 | 21 | 22 | public class NoLoggingImpl implements Log { 23 | 24 | public NoLoggingImpl(String clazz) { 25 | // Do Nothing 26 | } 27 | 28 | @Override 29 | public boolean isDebugEnabled() { 30 | return false; 31 | } 32 | 33 | @Override 34 | public boolean isTraceEnabled() { 35 | return false; 36 | } 37 | 38 | @Override 39 | public void error(String s, Throwable e) { 40 | // Do Nothing 41 | } 42 | 43 | @Override 44 | public void error(String s) { 45 | // Do Nothing 46 | } 47 | 48 | @Override 49 | public void debug(String s) { 50 | // Do Nothing 51 | } 52 | 53 | @Override 54 | public void trace(String s) { 55 | // Do Nothing 56 | } 57 | 58 | @Override 59 | public void warn(String s) { 60 | // Do Nothing 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/SessionScope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 4 | import com.codingcube.simpleauth.util.support.BeanDefinition; 5 | import org.springframework.cglib.core.ReflectUtils; 6 | import org.springframework.web.context.request.RequestContextHolder; 7 | import org.springframework.web.context.request.ServletRequestAttributes; 8 | 9 | import javax.servlet.http.HttpSession; 10 | import java.util.Objects; 11 | 12 | public class SessionScope extends Scope{ 13 | @Override 14 | public T initBean(BeanDefinition beanDefinition) { 15 | return null; 16 | } 17 | 18 | @Override 19 | public T getBean(BeanDefinition beanDefinition) { 20 | final Class clazz = beanDefinition.getClazz(); 21 | final HttpSession session = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getSession(true); 22 | final String sessionBeanKey = AuthHandlerUtil.requestBeanKey(clazz); 23 | final Object sessionAttribute = session.getAttribute(sessionBeanKey); 24 | if (sessionAttribute != null) { 25 | return (T) sessionAttribute; 26 | } 27 | 28 | synchronized (session){ 29 | final Object tempAttribute = session.getAttribute(sessionBeanKey); 30 | if(tempAttribute != null){ 31 | return (T) tempAttribute; 32 | } 33 | final Object objInstance = ReflectUtils.newInstance(clazz); 34 | session.setAttribute(sessionBeanKey, objInstance); 35 | return (T) objInstance; 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/stdout/StdOutImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2012 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.codingcube.simpleauth.logging.stdout; 17 | 18 | import com.codingcube.simpleauth.logging.Log; 19 | 20 | public class StdOutImpl implements Log { 21 | 22 | public StdOutImpl(String clazz) { 23 | // Do Nothing 24 | } 25 | 26 | @Override 27 | public boolean isDebugEnabled() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean isTraceEnabled() { 33 | return true; 34 | } 35 | 36 | @Override 37 | public void error(String s, Throwable e) { 38 | System.err.println(s); 39 | e.printStackTrace(System.err); 40 | } 41 | 42 | @Override 43 | public void error(String s) { 44 | System.err.println(s); 45 | } 46 | 47 | @Override 48 | public void debug(String s) { 49 | System.out.println(s); 50 | } 51 | 52 | @Override 53 | public void trace(String s) { 54 | System.out.println(s); 55 | } 56 | 57 | @Override 58 | public void warn(String s) { 59 | System.out.println(s); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/filter/CacheBodyHttpServletRequest.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.filter; 2 | 3 | import org.springframework.util.StreamUtils; 4 | 5 | import javax.servlet.ReadListener; 6 | import javax.servlet.ServletInputStream; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletRequestWrapper; 9 | import java.io.ByteArrayInputStream; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | 13 | public class CacheBodyHttpServletRequest extends HttpServletRequestWrapper { 14 | private final byte[] cachedBody; 15 | public CacheBodyHttpServletRequest(HttpServletRequest request) throws IOException { 16 | super(request); 17 | InputStream requestInputStream = request.getInputStream(); 18 | cachedBody = StreamUtils.copyToByteArray(requestInputStream); 19 | } 20 | 21 | @Override 22 | public ServletInputStream getInputStream() { 23 | ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody); 24 | return new ServletInputStream() { 25 | @Override 26 | public boolean isFinished() { 27 | return inputStream.available() == 0; 28 | } 29 | 30 | @Override 31 | public boolean isReady() { 32 | return true; 33 | } 34 | 35 | @Override 36 | public void setReadListener(ReadListener readListener) { 37 | 38 | } 39 | 40 | @Override 41 | public int read() { 42 | return inputStream.read(); 43 | } 44 | }; 45 | } 46 | 47 | public byte[] getCachedBody() { 48 | return cachedBody; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/RequestScope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 4 | import com.codingcube.simpleauth.util.support.BeanDefinition; 5 | import org.springframework.cglib.core.ReflectUtils; 6 | import org.springframework.web.context.request.RequestContextHolder; 7 | import org.springframework.web.context.request.ServletRequestAttributes; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import java.util.Objects; 11 | 12 | @SuppressWarnings("unchecked") 13 | public class RequestScope extends Scope{ 14 | @Override 15 | public T initBean(BeanDefinition beanDefinition) { 16 | return null; 17 | } 18 | 19 | @Override 20 | public T getBean(BeanDefinition beanDefinition) { 21 | final Class clazz = beanDefinition.getClazz(); 22 | //request 23 | final HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 24 | final String requestBeanKey = AuthHandlerUtil.requestBeanKey(clazz); 25 | final Object attribute = request.getAttribute(requestBeanKey); 26 | if (attribute != null) { 27 | return (T) attribute; 28 | } 29 | synchronized (request){ 30 | final Object syncAttribute = request.getAttribute(requestBeanKey); 31 | if (syncAttribute != null) { 32 | return (T) syncAttribute; 33 | } 34 | 35 | final Object objInstance = ReflectUtils.newInstance(clazz); 36 | request.setAttribute(requestBeanKey, objInstance); 37 | return (T) objInstance; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/autoconfig/FilterLimitWebAutoConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.autoconfig; 2 | 3 | import com.codingcube.simpleauth.auth.autoconfig.AutoConfigAuthInterceptor; 4 | import com.codingcube.simpleauth.logging.LogFactory; 5 | import com.codingcube.simpleauth.properties.Bean2Static; 6 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 8 | import org.springframework.context.ApplicationContext; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 12 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 13 | 14 | import javax.annotation.Resource; 15 | 16 | @Configuration 17 | public class FilterLimitWebAutoConfig implements WebMvcConfigurer { 18 | @Resource 19 | private ApplicationContext applicationContext; 20 | @Resource 21 | private LogFactory logFactory; 22 | @Resource 23 | private Bean2Static bean2Static; 24 | 25 | @Override 26 | public void addInterceptors(InterceptorRegistry registry) { 27 | if (AuthHandlerUtil.simpleAuthConfig != null){ 28 | if (AuthHandlerUtil.simpleAuthConfig.getLimitMap().size() != 0){ 29 | registry.addInterceptor(new AutoConfigLimitInterceptor(applicationContext, logFactory)).addPathPatterns("/*").order(Integer.MAX_VALUE); 30 | 31 | } 32 | } 33 | } 34 | 35 | @Bean 36 | @ConditionalOnMissingBean(AutoConfigLimitAdvice.class) 37 | public AutoConfigLimitAdvice autoConfigLimitAdvice(LogFactory logFactory){ 38 | return new AutoConfigLimitAdvice(logFactory, bean2Static); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/jdk/Jdk14LoggingImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009-2012 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.codingcube.simpleauth.logging.jdk; 17 | 18 | import com.codingcube.simpleauth.logging.Log; 19 | 20 | import java.util.logging.Level; 21 | import java.util.logging.Logger; 22 | 23 | 24 | public class Jdk14LoggingImpl implements Log { 25 | 26 | private final Logger log; 27 | 28 | public Jdk14LoggingImpl(String clazz) { 29 | log = Logger.getLogger(clazz); 30 | } 31 | 32 | @Override 33 | public boolean isDebugEnabled() { 34 | return log.isLoggable(Level.FINE); 35 | } 36 | 37 | @Override 38 | public boolean isTraceEnabled() { 39 | return log.isLoggable(Level.FINER); 40 | } 41 | 42 | @Override 43 | public void error(String s, Throwable e) { 44 | log.log(Level.SEVERE, s, e); 45 | } 46 | 47 | @Override 48 | public void error(String s) { 49 | log.log(Level.SEVERE, s); 50 | } 51 | 52 | @Override 53 | public void debug(String s) { 54 | log.log(Level.FINE, s); 55 | } 56 | 57 | @Override 58 | public void trace(String s) { 59 | log.log(Level.FINER, s); 60 | } 61 | 62 | @Override 63 | public void warn(String s) { 64 | log.log(Level.WARNING, s); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/DynamicLimitInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic; 2 | 3 | import com.codingcube.simpleauth.limit.util.LimitHandlerUtil; 4 | import com.codingcube.simpleauth.logging.Log; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.util.AntPathMatcher; 8 | import org.springframework.web.servlet.HandlerInterceptor; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.util.List; 13 | 14 | /** 15 | * @author CodingCube
16 | * The Dynamic HandlerChain Interceptor of SimpleAuth
17 | * Implementing Dynamic Permission Configuration Functionality* 18 | */ 19 | public class DynamicLimitInterceptor implements HandlerInterceptor { 20 | private final RequestLimitItemProvider requestLimitItemProvider; 21 | private final ApplicationContext applicationContext; 22 | private final Log log; 23 | 24 | AntPathMatcher antPathMatcher = new AntPathMatcher(); 25 | 26 | public DynamicLimitInterceptor(RequestLimitItemProvider requestLimitItemProvider, ApplicationContext applicationContext, LogFactory logFactory) { 27 | this.requestLimitItemProvider = requestLimitItemProvider; 28 | this.applicationContext = applicationContext; 29 | this.log = logFactory.getLimitLog(this.getClass()); 30 | } 31 | 32 | @Override 33 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 34 | final List requestLimitItem = requestLimitItemProvider.getRequestLimitItem(); 35 | LimitHandlerUtil.preHandlerRequestLimitItem(requestLimitItem, antPathMatcher, request, applicationContext, log, "dynamic limit"); 36 | return HandlerInterceptor.super.preHandle(request, response, handler); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/annotation/IsLimit.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.annotation; 2 | 3 | import com.codingcube.simpleauth.limit.strategic.DefaultEffectiveStrategic; 4 | import com.codingcube.simpleauth.auth.strategic.DefaultSignStrategic; 5 | import com.codingcube.simpleauth.limit.strategic.DefaultLimitRejectedStratagem; 6 | import com.codingcube.simpleauth.limit.strategic.EffectiveStrategic; 7 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 8 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 9 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 10 | import com.codingcube.simpleauth.limit.util.TokenLimit; 11 | import com.codingcube.simpleauth.util.NullTarget; 12 | 13 | import java.lang.annotation.ElementType; 14 | import java.lang.annotation.Retention; 15 | import java.lang.annotation.RetentionPolicy; 16 | import java.lang.annotation.Target; 17 | 18 | /** 19 | * @author CodingCube
20 | * Access restriction * 21 | */ 22 | @Retention(RetentionPolicy.RUNTIME) 23 | @Target({ElementType.METHOD, ElementType.TYPE}) 24 | public @interface IsLimit { 25 | //Limit the number of times 26 | int value() default 100; 27 | //Record operation time(Limited Time) 28 | int seconds() default 300; 29 | //ban time 30 | int ban() default 0; 31 | //user Sign generation strategy 32 | Class signStrategic() default DefaultSignStrategic.class; 33 | //Sign of Controller 34 | String item() default ""; 35 | //Verify that this request is recorded. 36 | Class effectiveStrategic() default DefaultEffectiveStrategic.class; 37 | //Whether effectiveStrategic judges after returning. 38 | boolean judgeAfterReturn() default true; 39 | //Current limiting algorithm 40 | Class tokenLimit() default CompleteLimit.class; 41 | //rejectedStratagem 42 | Class rejected() default NullTarget.class; 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/annotation/SimpleLimit.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.annotation; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.DefaultSignStrategic; 4 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 5 | import com.codingcube.simpleauth.limit.strategic.DefaultEffectiveStrategic; 6 | import com.codingcube.simpleauth.limit.strategic.DefaultLimitRejectedStratagem; 7 | import com.codingcube.simpleauth.limit.strategic.EffectiveStrategic; 8 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 9 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 10 | import com.codingcube.simpleauth.limit.util.TokenLimit; 11 | import com.codingcube.simpleauth.util.NullTarget; 12 | 13 | import java.lang.annotation.ElementType; 14 | import java.lang.annotation.Retention; 15 | import java.lang.annotation.RetentionPolicy; 16 | import java.lang.annotation.Target; 17 | 18 | /** 19 | * @author CodingCube
20 | * Access restriction * 21 | */ 22 | @Retention(RetentionPolicy.RUNTIME) 23 | @Target({ElementType.METHOD, ElementType.TYPE}) 24 | public @interface SimpleLimit { 25 | //Limit the number of times 26 | int value() default 100; 27 | //Record operation time(Limited Time) 28 | int seconds() default 300; 29 | //ban time 30 | int ban() default 0; 31 | //user Sign generation strategy 32 | Class signStrategic() default DefaultSignStrategic.class; 33 | //Sign of Controller 34 | String item() default ""; 35 | //Verify that this request is recorded. 36 | Class effectiveStrategic() default DefaultEffectiveStrategic.class; 37 | //Whether effectiveStrategic judges after returning. 38 | boolean judgeAfterReturn() default true; 39 | //Current limiting algorithm 40 | Class tokenLimit() default CompleteLimit.class; 41 | //rejectedStratagem 42 | Class rejected() default NullTarget.class; 43 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/interceptor/DynamicAuthInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.interceptor; 2 | 3 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItem; 4 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItemProvider; 5 | import com.codingcube.simpleauth.logging.Log; 6 | import com.codingcube.simpleauth.logging.LogFactory; 7 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 8 | import org.springframework.context.ApplicationContext; 9 | import org.springframework.util.AntPathMatcher; 10 | import org.springframework.web.servlet.HandlerInterceptor; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import java.util.List; 15 | 16 | /** 17 | * @author CodingCube
18 | * The Dynamic HandlerChain Interceptor of SimpleAuth
19 | * Implementing Dynamic Permission Configuration Functionality* 20 | */ 21 | public class DynamicAuthInterceptor implements HandlerInterceptor { 22 | private final RequestAuthItemProvider requestAuthItemProvider; 23 | private final ApplicationContext applicationContext; 24 | private final Log log; 25 | 26 | AntPathMatcher antPathMatcher = new AntPathMatcher(); 27 | 28 | public DynamicAuthInterceptor(RequestAuthItemProvider requestAuthItemProvider, ApplicationContext applicationContext, LogFactory logFactory) { 29 | this.requestAuthItemProvider = requestAuthItemProvider; 30 | this.applicationContext = applicationContext; 31 | this.log = logFactory.getLog(this.getClass()); 32 | } 33 | 34 | @Override 35 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 36 | final List requestAuthItem = requestAuthItemProvider.getRequestAuthItem(); 37 | AuthHandlerUtil.doRequestAuthItemList(requestAuthItem, antPathMatcher, request, applicationContext, log, "Dynamic Permission Configuration"); 38 | return HandlerInterceptor.super.preHandle(request, response, handler); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/handler/session/SessionMigratorHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.handler.session; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.logging.Log; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpSession; 10 | import java.util.*; 11 | 12 | @Component 13 | public class SessionMigratorHandler extends AutoAuthHandler { 14 | private final Log log; 15 | 16 | public SessionMigratorHandler(LogFactory logFactory) { 17 | this.log = logFactory.getLog(this.getClass()); 18 | } 19 | 20 | @Override 21 | public boolean isAuthor(HttpServletRequest request, String permission) { 22 | HttpSession originalSession = request.getSession(false); 23 | 24 | if (originalSession != null) { 25 | final String originalSessionId = originalSession.getId(); 26 | Enumeration attributeNames = originalSession.getAttributeNames(); 27 | List> entryList = new ArrayList<>(); 28 | 29 | // copy attribute to entrySet 30 | while (attributeNames.hasMoreElements()) { 31 | String attributeName = attributeNames.nextElement(); 32 | Object attributeValue = originalSession.getAttribute(attributeName); 33 | 34 | entryList.add(new AbstractMap.SimpleEntry<>(attributeName, attributeValue)); 35 | } 36 | 37 | // destroy original Session 38 | originalSession.invalidate(); 39 | HttpSession newSession = request.getSession(true); 40 | for (Map.Entry entry : entryList) { 41 | newSession.setAttribute(entry.getKey(), entry.getValue()); 42 | } 43 | log.debug("Changed session id from "+originalSessionId + " to " + newSession.getId()); 44 | } 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/interceptor/AutoAuthChainInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.interceptor; 2 | 3 | 4 | import com.codingcube.simpleauth.auth.PermissionOperate; 5 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandlerChain; 6 | import com.codingcube.simpleauth.logging.Log; 7 | import com.codingcube.simpleauth.logging.LogFactory; 8 | import com.codingcube.simpleauth.properties.AuthProper; 9 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 10 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 11 | import org.springframework.context.ApplicationContext; 12 | import org.springframework.web.servlet.HandlerInterceptor; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.lang.reflect.InvocationTargetException; 16 | 17 | /** 18 | * @author CodingCube
19 | * The HandlerChain Interceptor of SimpleAuth
20 | * Implementing Rapid Interceptor Configuration Functionality* 21 | 22 | */ 23 | public class AutoAuthChainInterceptor implements HandlerInterceptor { 24 | private final Class handlerChainClass; 25 | private final ApplicationContext applicationContext; 26 | private final Log log; 27 | 28 | public AutoAuthChainInterceptor(Class handlerChainClass, ApplicationContext applicationContext, LogFactory logFactory) { 29 | this.handlerChainClass = handlerChainClass; 30 | this.applicationContext = applicationContext; 31 | this.log = logFactory.getLog(this.getClass()); 32 | } 33 | 34 | @Override 35 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { 36 | AutoAuthHandlerChain autoAuthHandlerChain = AuthHandlerUtil.getBean(applicationContext, handlerChainClass); 37 | final String permissions = (String) request.getAttribute(PermissionOperate.PERMISSIONS); 38 | AuthHandlerUtil.handlerChain(autoAuthHandlerChain, applicationContext, request, permissions, AuthProper.getDefaultRejectedClazz(), log, "SimpleAuth Interceptor"); 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/ValidateProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 4 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 5 | import com.codingcube.simpleauth.validated.strategic.DefaultValidateRejectedStratagem; 6 | import com.codingcube.simpleauth.validated.strategic.ValidateRejectedStratagem; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | 9 | @ConfigurationProperties(prefix = "simple-auth.validate") 10 | public class ValidateProper { 11 | 12 | private String defaultRejected = "com.codingcube.simpleauth.validated.strategic.DefaultValidateRejectedStratagem"; 13 | private static Class defaultRejectedClazz = DefaultValidateRejectedStratagem.class; 14 | 15 | private String defaultValidateObject = "java.lang.Object"; 16 | private static Class defaultValidateObjectClazz = Object.class; 17 | 18 | public String getDefaultRejected() { 19 | return defaultRejected; 20 | } 21 | 22 | public void setDefaultRejected(String defaultRejected) { 23 | this.defaultRejected = defaultRejected; 24 | } 25 | 26 | public static Class getDefaultRejectedClazz() { 27 | return defaultRejectedClazz; 28 | } 29 | 30 | public static void setDefaultRejectedClazz(Class defaultRejectedClazz) { 31 | ValidateProper.defaultRejectedClazz = defaultRejectedClazz; 32 | } 33 | 34 | public String getDefaultValidateObject() { 35 | return defaultValidateObject; 36 | } 37 | 38 | public void setDefaultValidateObject(String defaultValidateObject) { 39 | this.defaultValidateObject = defaultValidateObject; 40 | } 41 | 42 | public static Class getDefaultValidateObjectClazz() { 43 | return defaultValidateObjectClazz; 44 | } 45 | 46 | public static void setDefaultValidateObjectClazz(Class defaultValidateObjectClazz) { 47 | ValidateProper.defaultValidateObjectClazz = defaultValidateObjectClazz; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/logformat/LogAuthFormat.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.logging.logformat; 2 | 3 | import com.codingcube.simpleauth.auth.PermissionOperate; 4 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 5 | import com.codingcube.simpleauth.properties.LogProper; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import java.time.LocalDateTime; 9 | import java.time.format.DateTimeFormatter; 10 | 11 | /** 12 | * @author CodingCube
13 | * Format Auth Log 14 | */ 15 | public class LogAuthFormat { 16 | private final HttpServletRequest request; 17 | private final String source; 18 | private final boolean pass; 19 | private final String handlerName; 20 | private final String permission; 21 | private final Class rejectedClass; 22 | private final DateTimeFormatter dateFormatter; 23 | 24 | public LogAuthFormat(HttpServletRequest request, String source, boolean pass, String handlerName, String permission, Class rejectedClass) { 25 | this.request = request; 26 | this.source = source; 27 | this.pass = pass; 28 | this.handlerName = handlerName; 29 | this.permission = permission; 30 | this.rejectedClass = rejectedClass; 31 | this.dateFormatter = DateTimeFormatter.ofPattern(LogProper.getDateFormatStatic()); 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "SimpleAuth auth => \r\n\turi: "+request.getRequestURI() +"\r\n"+ 37 | "\trequest hash: "+request.hashCode()+"\r\n"+ 38 | "\ttime: "+dateFormatter.format(LocalDateTime.now())+"\r\n"+ 39 | "\thandlerName: "+handlerName+"\r\n"+ 40 | "\tsource: "+source+"\r\n"+ 41 | "\tRequired permission: "+permission+"\r\n"+ 42 | "\tPermissions to carry: "+ request.getAttribute(PermissionOperate.PERMISSIONS) +"\r\n"+ 43 | "\tPrincipal to carry: "+ request.getAttribute(PermissionOperate.PRINCIPAL) +"\r\n"+ 44 | "\tRejected Class: "+ rejectedClass +"\r\n"+ 45 | "\tPass or not: "+pass+""; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/LogProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties(prefix = "simple-auth.log") 6 | public class LogProper { 7 | private String logImpl = "NoLogging"; 8 | private String limitLogImpl = "NoLogging"; 9 | private String validatedLogImpl = "NoLogging"; 10 | private Boolean showOptList = false; 11 | private static Boolean staticShowOptList = false; 12 | private String dateFormat = "yyyy-MM-dd HH:mm:ss"; 13 | private static String dateFormatStatic = "yyyy-MM-dd HH:mm:ss"; 14 | 15 | public String getLogImpl() { 16 | return logImpl; 17 | } 18 | 19 | public void setLogImpl(String logImpl) { 20 | this.logImpl = logImpl; 21 | } 22 | 23 | public String getLimitLogImpl() { 24 | return limitLogImpl; 25 | } 26 | 27 | public void setLimitLogImpl(String limitLogImpl) { 28 | this.limitLogImpl = limitLogImpl; 29 | } 30 | 31 | public Boolean getShowOptList() { 32 | return showOptList; 33 | } 34 | 35 | public void setShowOptList(Boolean showOptList) { 36 | this.showOptList = showOptList; 37 | } 38 | 39 | public static Boolean getStaticShowOptList() { 40 | return staticShowOptList; 41 | } 42 | 43 | public static void setStaticShowOptList(Boolean staticShowOptList) { 44 | LogProper.staticShowOptList = staticShowOptList; 45 | } 46 | 47 | public String getDateFormat() { 48 | return dateFormat; 49 | } 50 | 51 | public void setDateFormat(String dateFormat) { 52 | this.dateFormat = dateFormat; 53 | } 54 | 55 | public static String getDateFormatStatic() { 56 | return dateFormatStatic; 57 | } 58 | 59 | public static void setDateFormatStatic(String dateFormatStatic) { 60 | LogProper.dateFormatStatic = dateFormatStatic; 61 | } 62 | 63 | public String getValidatedLogImpl() { 64 | return validatedLogImpl; 65 | } 66 | 67 | public void setValidatedLogImpl(String validatedLogImpl) { 68 | this.validatedLogImpl = validatedLogImpl; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/PermissionOperate.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth; 2 | 3 | import org.springframework.web.context.request.RequestContextHolder; 4 | import org.springframework.web.context.request.ServletRequestAttributes; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Objects; 10 | 11 | /** 12 | * @author CodingCube
13 | * PermissionOperate* 14 | */ 15 | public interface PermissionOperate { 16 | String PRINCIPAL = "$PRINCIPAL$"; 17 | String PERMISSIONS = "$PERMISSIONS$"; 18 | 19 | default T getPrincipal(){ 20 | HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 21 | return (T) request.getAttribute(PRINCIPAL); 22 | } 23 | 24 | default void setPrincipal(Object target){ 25 | HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 26 | request.setAttribute(PRINCIPAL, target); 27 | } 28 | 29 | default List getPermissions(){ 30 | HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 31 | final List attribute = (List) request.getAttribute(PERMISSIONS); 32 | if (attribute == null){ 33 | return new ArrayList<>(); 34 | } 35 | return attribute; 36 | } 37 | 38 | default void setPermissions(List target){ 39 | HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 40 | request.setAttribute(PERMISSIONS, target); 41 | } 42 | 43 | default void setPermissions(String permission){ 44 | final List permissions = getPermissions(); 45 | permissions.add(permission); 46 | setPermissions(permissions); 47 | } 48 | 49 | static T principal(){ 50 | HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); 51 | return (T) request.getAttribute(PRINCIPAL); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/advice/DynamicLimitAdvice.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic.advice; 2 | 3 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 4 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItemProvider; 5 | import com.codingcube.simpleauth.limit.util.LimitHandlerUtil; 6 | import com.codingcube.simpleauth.logging.Log; 7 | import com.codingcube.simpleauth.logging.LogFactory; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.core.MethodParameter; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.http.server.ServerHttpRequest; 13 | import org.springframework.http.server.ServerHttpResponse; 14 | import org.springframework.http.server.ServletServerHttpRequest; 15 | import org.springframework.util.AntPathMatcher; 16 | import org.springframework.web.bind.annotation.ControllerAdvice; 17 | import org.springframework.web.context.request.RequestContextHolder; 18 | import org.springframework.web.context.request.ServletRequestAttributes; 19 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 20 | 21 | import javax.annotation.Resource; 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.util.List; 24 | 25 | @ControllerAdvice 26 | @ConditionalOnProperty("simple-auth.func.dynamic-limit") 27 | public class DynamicLimitAdvice implements ResponseBodyAdvice { 28 | @Resource 29 | private ApplicationContext applicationContext; 30 | private final Log log; 31 | 32 | @Override 33 | public boolean supports(MethodParameter methodParameter, Class aClass) { 34 | return true; 35 | } 36 | 37 | public DynamicLimitAdvice(LogFactory logFactory) { 38 | this.log = logFactory.getLimitLog(this.getClass()); 39 | } 40 | 41 | @Override 42 | public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { 43 | final HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest(); 44 | LimitHandlerUtil.postHandlerRequestLimitItem(request, 45 | applicationContext, log, o, "dynamic limit"); 46 | return o; 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/util/support/scope/SingletonScope.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.util.support.scope; 2 | 3 | import com.codingcube.simpleauth.autoconfig.execption.ConfigurationParseException; 4 | import com.codingcube.simpleauth.util.support.BeanDefinition; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | 9 | /** 10 | * @author dhc 11 | */ 12 | @SuppressWarnings("unchecked") 13 | public class SingletonScope extends Scope{ 14 | public static final ConcurrentHashMap beanMap = new ConcurrentHashMap<>(16); 15 | 16 | @Override 17 | public T initBean(BeanDefinition beanDefinition) { 18 | final Class clazz = beanDefinition.getClazz(); 19 | final Object obj; 20 | try { 21 | obj = beanMap.get(clazz.getName()); 22 | if (obj == null){ 23 | final Object objInstance = clazz.getConstructor().newInstance(); 24 | beanMap.put(clazz.getName(), objInstance); 25 | } 26 | } catch ( NoSuchMethodException e) { 27 | throw new ConfigurationParseException(clazz.getName() + " Requires a parameterless constructor, or remove the related configuration."); 28 | } catch (InstantiationException 29 | | IllegalAccessException 30 | | InvocationTargetException e){ 31 | throw new ConfigurationParseException(e); 32 | } 33 | return (T) obj; 34 | } 35 | 36 | @Override 37 | public T getBean(BeanDefinition beanDefinition) { 38 | final Class clazz = (Class) beanDefinition.getClazz(); 39 | final String beanName = beanDefinition.getBeanName(); 40 | final Object obj = beanMap.get(beanName); 41 | if (obj != null){ 42 | return clazz.cast(obj); 43 | } 44 | synchronized (beanMap){ 45 | T objInstance = null; 46 | try { 47 | objInstance = clazz.getConstructor().newInstance(); 48 | } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { 49 | e.printStackTrace(); 50 | } 51 | if(objInstance != null){ 52 | beanMap.put(clazz.getName(), objInstance); 53 | } 54 | return objInstance; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/SecurityProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | @ConfigurationProperties(prefix = "simple-auth.security") 9 | public class SecurityProper { 10 | 11 | private List XFrameOptionsPath = new ArrayList<>(); 12 | private List XFrameOptionsExcludePath = new ArrayList<>(); 13 | private String XFrameOptions = "SAMEORIGIN"; 14 | 15 | private List contentSecurityPolicyPath = new ArrayList<>(); 16 | private List contentSecurityPolicyExcludePath = new ArrayList<>(); 17 | private String ContentSecurityPolicy = "default-src 'self'"; 18 | 19 | public List getXFrameOptionsPath() { 20 | return XFrameOptionsPath; 21 | } 22 | 23 | public List getContentSecurityPolicyExcludePath() { 24 | return contentSecurityPolicyExcludePath; 25 | } 26 | 27 | public void setContentSecurityPolicyExcludePath(List contentSecurityPolicyExcludePath) { 28 | this.contentSecurityPolicyExcludePath = contentSecurityPolicyExcludePath; 29 | } 30 | 31 | public List getXFrameOptionsExcludePath() { 32 | return XFrameOptionsExcludePath; 33 | } 34 | 35 | public void setXFrameOptionsExcludePath(List XFrameOptionsExcludePath) { 36 | this.XFrameOptionsExcludePath = XFrameOptionsExcludePath; 37 | } 38 | 39 | public void setXFrameOptionsPath(List XFrameOptionsPath) { 40 | this.XFrameOptionsPath = XFrameOptionsPath; 41 | } 42 | 43 | public String getXFrameOptions() { 44 | return XFrameOptions; 45 | } 46 | 47 | public void setXFrameOptions(String XFrameOptions) { 48 | this.XFrameOptions = XFrameOptions; 49 | } 50 | 51 | public List getContentSecurityPolicyPath() { 52 | return contentSecurityPolicyPath; 53 | } 54 | 55 | public void setContentSecurityPolicyPath(List contentSecurityPolicyPath) { 56 | this.contentSecurityPolicyPath = contentSecurityPolicyPath; 57 | } 58 | 59 | public String getContentSecurityPolicy() { 60 | return ContentSecurityPolicy; 61 | } 62 | 63 | public void setContentSecurityPolicy(String contentSecurityPolicy) { 64 | ContentSecurityPolicy = contentSecurityPolicy; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/FunctionProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 4 | import com.codingcube.simpleauth.limit.util.TokenLimit; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | 7 | @ConfigurationProperties(prefix = "simple-auth.func") 8 | public class FunctionProper { 9 | private boolean dynamicAuth = false; 10 | private boolean autoClearExpiredRecord = false; 11 | private boolean dynamicLimit = false; 12 | 13 | private boolean handlerCache = true; 14 | private static boolean handlerCacheStatic = true; 15 | 16 | private String limitPlan = "default"; 17 | private static Class tokenLimitClass = CompleteLimit.class; 18 | 19 | public String getLimitPlan() { 20 | return limitPlan; 21 | } 22 | 23 | public void setLimitPlan(String limitPlan) { 24 | this.limitPlan = limitPlan; 25 | } 26 | 27 | public static Class getTokenLimitClass() { 28 | return tokenLimitClass; 29 | } 30 | 31 | public static void setTokenLimitClass(Class tokenLimitClass) { 32 | FunctionProper.tokenLimitClass = tokenLimitClass; 33 | } 34 | 35 | public boolean isHandlerCache() { 36 | return handlerCache; 37 | } 38 | 39 | public void setHandlerCache(boolean handlerCache) { 40 | this.handlerCache = handlerCache; 41 | } 42 | 43 | public static boolean isHandlerCacheStatic() { 44 | return handlerCacheStatic; 45 | } 46 | 47 | public static void setHandlerCacheStatic(boolean handlerCacheStatic) { 48 | FunctionProper.handlerCacheStatic = handlerCacheStatic; 49 | } 50 | 51 | public boolean isDynamicAuth() { 52 | return dynamicAuth; 53 | } 54 | 55 | public void setDynamicAuth(boolean dynamicAuth) { 56 | this.dynamicAuth = dynamicAuth; 57 | } 58 | 59 | public boolean isAutoClearExpiredRecord() { 60 | return autoClearExpiredRecord; 61 | } 62 | 63 | public void setAutoClearExpiredRecord(boolean autoClearExpiredRecord) { 64 | this.autoClearExpiredRecord = autoClearExpiredRecord; 65 | } 66 | 67 | public boolean isDynamicLimit() { 68 | return dynamicLimit; 69 | } 70 | 71 | public void setDynamicLimit(boolean dynamicLimit) { 72 | this.dynamicLimit = dynamicLimit; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/EvaluationEnvironmentContext.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import org.springframework.core.env.ConfigurableEnvironment; 4 | import org.springframework.core.env.Environment; 5 | import org.springframework.expression.*; 6 | import org.springframework.expression.spel.support.StandardEvaluationContext; 7 | 8 | import java.util.List; 9 | 10 | public class EvaluationEnvironmentContext implements EvaluationContext { 11 | 12 | final private Environment environment; 13 | final private EvaluationContext evaluationContext = new StandardEvaluationContext(); 14 | 15 | 16 | public EvaluationEnvironmentContext(Environment environment) { 17 | this.environment = environment; 18 | } 19 | 20 | @Override 21 | public TypedValue getRootObject() { 22 | return evaluationContext.getRootObject(); 23 | } 24 | 25 | @Override 26 | public List getPropertyAccessors() { 27 | return evaluationContext.getPropertyAccessors(); 28 | } 29 | 30 | @Override 31 | public List getConstructorResolvers() { 32 | return evaluationContext.getConstructorResolvers(); 33 | } 34 | 35 | @Override 36 | public List getMethodResolvers() { 37 | return evaluationContext.getMethodResolvers(); 38 | } 39 | 40 | @Override 41 | public BeanResolver getBeanResolver() { 42 | return evaluationContext.getBeanResolver(); 43 | } 44 | 45 | @Override 46 | public TypeLocator getTypeLocator() { 47 | return evaluationContext.getTypeLocator(); 48 | } 49 | 50 | @Override 51 | public TypeConverter getTypeConverter() { 52 | return evaluationContext.getTypeConverter(); 53 | } 54 | 55 | @Override 56 | public TypeComparator getTypeComparator() { 57 | return evaluationContext.getTypeComparator(); 58 | } 59 | 60 | @Override 61 | public OperatorOverloader getOperatorOverloader() { 62 | return evaluationContext.getOperatorOverloader(); 63 | } 64 | 65 | @Override 66 | public void setVariable(String s, Object o) { 67 | evaluationContext.setVariable(s, o); 68 | } 69 | 70 | @Override 71 | public Object lookupVariable(String s) { 72 | final Object o = evaluationContext.lookupVariable(s); 73 | if (o != null){ 74 | return o; 75 | } 76 | return environment.getProperty(s); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/handler/session/ChangeSessionIdHandler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.handler.session; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.logging.Log; 5 | import com.codingcube.simpleauth.logging.LogFactory; 6 | import org.apache.tomcat.util.net.openssl.ciphers.Authentication; 7 | import org.springframework.context.ApplicationEvent; 8 | import org.springframework.context.ApplicationEventPublisher; 9 | import org.springframework.core.log.LogMessage; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.util.WebUtils; 12 | 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpSession; 15 | import java.util.Enumeration; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | import java.util.logging.Handler; 19 | 20 | @Component 21 | public class ChangeSessionIdHandler extends AutoAuthHandler { 22 | private final Log log; 23 | 24 | public ChangeSessionIdHandler(LogFactory logFactory) { 25 | this.log = logFactory.getLog(this.getClass()); 26 | } 27 | 28 | @Override 29 | public boolean isAuthor(HttpServletRequest request, String permission) { 30 | boolean hadSessionAlready = request.getSession(false) != null; 31 | if (hadSessionAlready) { 32 | HttpSession session = request.getSession(); 33 | if (request.isRequestedSessionIdValid()) { 34 | String originalSessionId; 35 | String newSessionId; 36 | synchronized(WebUtils.getSessionMutex(session)) { 37 | originalSessionId = session.getId(); 38 | session = this.applySessionFixation(request); 39 | newSessionId = session.getId(); 40 | } 41 | 42 | if (originalSessionId.equals(newSessionId)) { 43 | log.warn("Your servlet container did not change the session ID when a new session was created. You will not be adequately protected against session-fixation attacks"); 44 | } else { 45 | log.debug("Changed session id from "+originalSessionId + " to " +newSessionId); 46 | } 47 | 48 | } 49 | 50 | } 51 | return true; 52 | } 53 | 54 | HttpSession applySessionFixation(HttpServletRequest request) { 55 | request.changeSessionId(); 56 | return request.getSession(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/config/SecurityWebConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.config; 2 | 3 | import com.codingcube.simpleauth.properties.SecurityProper; 4 | import com.codingcube.simpleauth.security.interceptor.AddXFrameOptionsInterceptor; 5 | import com.codingcube.simpleauth.security.interceptor.ContentSecurityPolicyInterceptor; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.web.servlet.config.annotation.InterceptorRegistration; 8 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 10 | 11 | import javax.annotation.Resource; 12 | import java.util.List; 13 | 14 | @Configuration 15 | public class SecurityWebConfigurer implements WebMvcConfigurer { 16 | @Resource 17 | private SecurityProper securityProper; 18 | @Override 19 | public void addInterceptors(InterceptorRegistry registry) { 20 | //set Header 'X-Frame-Options' 21 | final List clickjackingPath = securityProper.getXFrameOptionsPath(); 22 | if (clickjackingPath.size() != 0){ 23 | final String xFrameOptions = securityProper.getXFrameOptions(); 24 | final InterceptorRegistration interceptorRegistration = registry.addInterceptor(new AddXFrameOptionsInterceptor(xFrameOptions)); 25 | clickjackingPath.forEach(interceptorRegistration::addPathPatterns); 26 | 27 | final List xFrameOptionsExcludePath = securityProper.getXFrameOptionsExcludePath(); 28 | xFrameOptionsExcludePath.forEach(interceptorRegistration::excludePathPatterns); 29 | 30 | } 31 | 32 | //set Header 'Content-Security-Policy' 33 | final List contentSecurityPolicyPath = securityProper.getContentSecurityPolicyPath(); 34 | if (contentSecurityPolicyPath.size() != 0){ 35 | final String contentSecurityPolicy = securityProper.getContentSecurityPolicy(); 36 | final InterceptorRegistration interceptorRegistration = registry.addInterceptor(new ContentSecurityPolicyInterceptor(contentSecurityPolicy)); 37 | contentSecurityPolicyPath.forEach(interceptorRegistration::addPathPatterns); 38 | 39 | final List contentSecurityPolicyExcludePath = securityProper.getContentSecurityPolicyExcludePath(); 40 | contentSecurityPolicyExcludePath.forEach(interceptorRegistration::excludePathPatterns); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/domain/HandlerChain.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.domain; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 5 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 6 | 7 | import java.util.List; 8 | 9 | public class HandlerChain { 10 | @JSONField(name = "tokenLimit") 11 | String id; 12 | @JSONField(name = "list") 13 | List handlerList; 14 | @JSONField(name = "rejected") 15 | private String rejected; 16 | private Class rejectedClass; 17 | @JSONField(name = "pathsId") 18 | String pathId; 19 | @JSONField(name = "paths") 20 | Paths paths; 21 | 22 | public HandlerChain(String id) { 23 | this.id = id; 24 | } 25 | 26 | public HandlerChain(String id, List handlerList) { 27 | this.id = id; 28 | this.handlerList = handlerList; 29 | } 30 | 31 | public HandlerChain(String id, List handlerList, Paths paths) { 32 | this.id = id; 33 | this.handlerList = handlerList; 34 | this.paths = paths; 35 | } 36 | 37 | public String getId() { 38 | return id; 39 | } 40 | 41 | public void setId(String id) { 42 | this.id = id; 43 | } 44 | 45 | public List getHandlerList() { 46 | return handlerList; 47 | } 48 | 49 | public void setHandlerList(List handlerList) { 50 | this.handlerList = handlerList; 51 | } 52 | 53 | public Paths getPaths() { 54 | return paths; 55 | } 56 | 57 | public void setPaths(Paths paths) { 58 | this.paths = paths; 59 | } 60 | 61 | 62 | public String getPathId() { 63 | return pathId; 64 | } 65 | 66 | public void setPathId(String pathId) { 67 | this.pathId = pathId; 68 | } 69 | 70 | public String getRejected() { 71 | return rejected; 72 | } 73 | 74 | public void setRejected(String rejected) { 75 | if (rejected == null){ 76 | this.rejectedClass = DefaultAuthRejectedStratagem.class; 77 | } 78 | this.rejected = rejected; 79 | } 80 | 81 | public Class getRejectedClass() { 82 | return rejectedClass; 83 | } 84 | 85 | public void setRejectedClass(Class rejectedClass) { 86 | this.rejectedClass = rejectedClass ==null ? DefaultAuthRejectedStratagem.class:rejectedClass; 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/autoconfig/AutoConfigLimitInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.autoconfig; 2 | 3 | import com.codingcube.simpleauth.autoconfig.domain.Limit; 4 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 5 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItemProvider; 6 | import com.codingcube.simpleauth.limit.util.LimitHandlerUtil; 7 | import com.codingcube.simpleauth.logging.Log; 8 | import com.codingcube.simpleauth.logging.LogFactory; 9 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.util.AntPathMatcher; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.servlet.HandlerInterceptor; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | 22 | public class AutoConfigLimitInterceptor implements HandlerInterceptor { 23 | final List requestLimitItem = new ArrayList<>(); 24 | private final ApplicationContext applicationContext; 25 | private final Log log; 26 | 27 | AntPathMatcher antPathMatcher = new AntPathMatcher(); 28 | 29 | public AutoConfigLimitInterceptor(ApplicationContext applicationContext, LogFactory logFactory) { 30 | this.applicationContext = applicationContext; 31 | this.log = logFactory.getLimitLog(this.getClass()); 32 | final Map limitMap = AuthHandlerUtil.simpleAuthConfig.getLimitMap(); 33 | limitMap.forEach( 34 | (key, value)-> requestLimitItem.add( 35 | new RequestLimitItem(value.getPaths().getPath(), 36 | value.getTimes(), 37 | value.getSeconds(), 38 | value.getBan(), 39 | value.getItemStrategicClass(), 40 | value.getSignStrategicClass(), 41 | value.getEffectiveStrategicClass(), 42 | value.getTokenLimitClass(), 43 | value.getRejectedClass() 44 | ) 45 | ) 46 | ); 47 | } 48 | 49 | @Override 50 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 51 | LimitHandlerUtil.preHandlerRequestLimitItem(requestLimitItem,antPathMatcher, request, applicationContext, log, "Profile configuration limit"); 52 | return HandlerInterceptor.super.preHandle(request, response, handler); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/config/SimpleAuthWebConfig.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.config; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandlerChain; 5 | import com.codingcube.simpleauth.auth.interceptor.AutoAuthChainInterceptor; 6 | import com.codingcube.simpleauth.auth.interceptor.AutoAuthInterceptor; 7 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 8 | import com.codingcube.simpleauth.logging.LogFactory; 9 | import com.codingcube.simpleauth.properties.AuthProper; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.web.servlet.config.annotation.InterceptorRegistration; 13 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 14 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 15 | import javax.annotation.Resource; 16 | 17 | /** 18 | * @author CodingCube
19 | * SimpleAuth Interceptor Configuration Class* 20 | */ 21 | @Configuration 22 | public abstract class SimpleAuthWebConfig implements WebMvcConfigurer { 23 | @Resource 24 | private ApplicationContext applicationContext; 25 | @Resource 26 | private LogFactory logFactory; 27 | InterceptorRegistry registry; 28 | 29 | @Override 30 | public void addInterceptors(InterceptorRegistry registry) { 31 | this.registry = registry; 32 | addAuthHandlers(); 33 | } 34 | 35 | /** 36 | * add AuthHandler Class as Interceptor* 37 | * @param autoAuthHandler autoAuthHandler Class 38 | * @return InterceptorRegistration 39 | */ 40 | public InterceptorRegistration addAuthHandler(Class autoAuthHandler){ 41 | return registry.addInterceptor(new AutoAuthInterceptor(autoAuthHandler, 42 | applicationContext, 43 | logFactory, 44 | AuthProper.getDefaultRejectedClazz())); 45 | } 46 | 47 | /** 48 | * add AuthHandler BeanName as Interceptor* 49 | * @param handlerBeanName handler BeanName 50 | * @return InterceptorRegistration 51 | */ 52 | public InterceptorRegistration addAuthHandler(String handlerBeanName){ 53 | return registry.addInterceptor(new AutoAuthInterceptor(handlerBeanName, 54 | applicationContext, 55 | logFactory, 56 | AuthProper.getDefaultRejectedClazz())); 57 | } 58 | 59 | /** 60 | * add AuthHandlerChain Class as Interceptor* 61 | * @param autoAuthHandlerChain AutoAuthHandlerChain class 62 | * @return InterceptorRegistration 63 | */ 64 | public InterceptorRegistration addAuthHandlerChain(Class autoAuthHandlerChain){ 65 | return registry.addInterceptor(new AutoAuthChainInterceptor(autoAuthHandlerChain, applicationContext, logFactory)); 66 | } 67 | 68 | public abstract void addAuthHandlers(); 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/autoconfig/AutoConfigAuthInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.autoconfig; 2 | 3 | import com.codingcube.simpleauth.auth.dynamic.RequestAuthItem; 4 | import com.codingcube.simpleauth.auth.handler.ProfileConfigurationHandlerChain; 5 | import com.codingcube.simpleauth.autoconfig.domain.Handler; 6 | import com.codingcube.simpleauth.logging.Log; 7 | import com.codingcube.simpleauth.logging.LogFactory; 8 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.util.AntPathMatcher; 11 | import org.springframework.web.servlet.HandlerInterceptor; 12 | 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | public class AutoConfigAuthInterceptor implements HandlerInterceptor{ 19 | private final ApplicationContext applicationContext; 20 | private final Log log; 21 | private final List requestAuthItem = new ArrayList<>(); 22 | AntPathMatcher antPathMatcher = new AntPathMatcher(); 23 | 24 | public AutoConfigAuthInterceptor(ApplicationContext applicationContext, LogFactory logFactory) { 25 | this.applicationContext = applicationContext; 26 | this.log = logFactory.getLog(this.getClass()); 27 | AuthHandlerUtil.simpleAuthConfig.getHandlerMap().forEach( 28 | (key, value)-> { 29 | if (value.getPaths() != null){ 30 | requestAuthItem.add(new RequestAuthItem(value.getPaths().getPath(), 31 | value.getPaths().getPermission(), 32 | value.getHandlerClass(), 33 | value.getRejectedClass() 34 | )); 35 | } 36 | } 37 | ); 38 | //handlerChain 39 | AuthHandlerUtil.simpleAuthConfig.getHandlerChainMap().forEach( 40 | (key, value) -> { 41 | List handlerClassList = new ArrayList<>(); 42 | final List handlerList = value.getHandlerList(); 43 | handlerList.forEach(item -> handlerClassList.add(item.getHandlerClass())); 44 | requestAuthItem.add(new RequestAuthItem(value.getPaths().getPath(), 45 | value.getPaths().getPermission(), 46 | new ProfileConfigurationHandlerChain(handlerClassList), 47 | value.getRejectedClass()) 48 | ); 49 | } 50 | ); 51 | } 52 | 53 | @Override 54 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 55 | AuthHandlerUtil.doRequestAuthItemList(requestAuthItem, antPathMatcher, request, applicationContext, log, "Profile configuration"); 56 | 57 | return HandlerInterceptor.super.preHandle(request, response, handler); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/autoconfig/domain/Handler.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.autoconfig.domain; 2 | 3 | 4 | import com.alibaba.fastjson.annotation.JSONField; 5 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 6 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 7 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 8 | import com.codingcube.simpleauth.limit.strategic.DefaultEffectiveStrategic; 9 | 10 | public class Handler { 11 | @JSONField(name = "id") 12 | private String id; 13 | @JSONField(name = "class") 14 | private String clazz; 15 | private Class handlerClass; 16 | @JSONField(name = "rejected") 17 | private String rejected; 18 | private Class rejectedClass; 19 | @JSONField(name = "scope") 20 | private String scope; 21 | @JSONField(name = "pathsId") 22 | private String pathId; 23 | @JSONField(name = "paths") 24 | private Paths paths; 25 | 26 | public Handler(String id, String clazz, String scope, String pathId) { 27 | this.id = id; 28 | this.clazz = clazz; 29 | this.scope = scope; 30 | this.pathId = pathId; 31 | } 32 | 33 | public Class getHandlerClass() { 34 | return handlerClass; 35 | } 36 | 37 | public void setHandlerClass(Class handlerClass) { 38 | this.handlerClass = handlerClass; 39 | } 40 | 41 | public Handler(String id, String pathId) { 42 | this.id = id; 43 | this.pathId = pathId; 44 | } 45 | 46 | public Handler(String id) { 47 | this.id = id; 48 | } 49 | 50 | public void setId(String id) { 51 | this.id = id; 52 | } 53 | 54 | public String getClazz() { 55 | return clazz; 56 | } 57 | 58 | public void setClazz(String clazz) { 59 | this.clazz = clazz; 60 | } 61 | 62 | public String getScope() { 63 | return scope; 64 | } 65 | 66 | public void setScope(String scope) { 67 | this.scope = scope; 68 | } 69 | 70 | public String getPathId() { 71 | return pathId; 72 | } 73 | 74 | public void setPathId(String pathId) { 75 | this.pathId = pathId; 76 | } 77 | 78 | public Paths getPaths() { 79 | return paths; 80 | } 81 | 82 | public void setPaths(Paths paths) { 83 | this.paths = paths; 84 | } 85 | 86 | public String getId() { 87 | return id; 88 | } 89 | 90 | public String getRejected() { 91 | return rejected; 92 | } 93 | 94 | public void setRejected(String rejected) { 95 | if (rejected == null){ 96 | this.rejectedClass = DefaultAuthRejectedStratagem.class; 97 | } 98 | this.rejected = rejected; 99 | } 100 | 101 | public Class getRejectedClass() { 102 | return rejectedClass; 103 | } 104 | 105 | public void setRejectedClass(Class rejectedClass) { 106 | this.rejectedClass = rejectedClass ==null ? DefaultAuthRejectedStratagem.class:rejectedClass; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/AuthProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.handler.DefaultAuthHandler; 5 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 6 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | 9 | @ConfigurationProperties(prefix = "simple-auth.auth") 10 | public class AuthProper { 11 | private String verifyKey = "simple_auth_verify_key"; 12 | private static String verifyKeyStatic = "simple_auth_verify_key"; 13 | private String verifyValue = "8552D986272D4ACFAD5933D76262212B"; 14 | private static String verifyValueStatic = "8552D986272D4ACFAD5933D76262212B"; 15 | 16 | private String defaultHandler = "com.codingcube.simpleauth.auth.handler.DefaultAuthHandler"; 17 | private static Class defaultHandlerClazz = DefaultAuthHandler.class; 18 | 19 | private String defaultRejected = "com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem"; 20 | private static Class defaultRejectedClazz = DefaultAuthRejectedStratagem.class; 21 | 22 | public String getVerifyKey() { 23 | return verifyKey; 24 | } 25 | 26 | public void setVerifyKey(String verifyKey) { 27 | this.verifyKey = verifyKey; 28 | } 29 | 30 | public static String getVerifyKeyStatic() { 31 | return verifyKeyStatic; 32 | } 33 | 34 | public static void setVerifyKeyStatic(String verifyKeyStatic) { 35 | AuthProper.verifyKeyStatic = verifyKeyStatic; 36 | } 37 | 38 | public String getVerifyValue() { 39 | return verifyValue; 40 | } 41 | 42 | public void setVerifyValue(String verifyValue) { 43 | this.verifyValue = verifyValue; 44 | } 45 | 46 | public static String getVerifyValueStatic() { 47 | return verifyValueStatic; 48 | } 49 | 50 | public static void setVerifyValueStatic(String verifyValueStatic) { 51 | AuthProper.verifyValueStatic = verifyValueStatic; 52 | } 53 | 54 | public String getDefaultHandler() { 55 | return defaultHandler; 56 | } 57 | 58 | public void setDefaultHandler(String defaultHandler) { 59 | this.defaultHandler = defaultHandler; 60 | } 61 | 62 | public static Class getDefaultHandlerClazz() { 63 | return defaultHandlerClazz; 64 | } 65 | 66 | public static void setDefaultHandlerClazz(Class defaultHandlerClazz) { 67 | AuthProper.defaultHandlerClazz = defaultHandlerClazz; 68 | } 69 | 70 | public String getDefaultRejected() { 71 | return defaultRejected; 72 | } 73 | 74 | public void setDefaultRejected(String defaultRejected) { 75 | this.defaultRejected = defaultRejected; 76 | } 77 | 78 | public static Class getDefaultRejectedClazz() { 79 | return defaultRejectedClazz; 80 | } 81 | 82 | public static void setDefaultRejectedClazz(Class defaultRejectedClazz) { 83 | AuthProper.defaultRejectedClazz = defaultRejectedClazz; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/util/TokenBucket.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.util; 2 | 3 | import java.util.concurrent.Semaphore; 4 | 5 | public class TokenBucket implements TokenLimit{ 6 | private int capacity; // 令牌桶容量 7 | private double fillRate; // 令牌生成速率 (令牌/秒) 8 | private long lastRefillTimestamp; // 上次令牌生成时间戳 9 | private double tokens; // 当前令牌数量 10 | private final Semaphore semaphore; // 信号量用于控制令牌的发放 11 | 12 | public TokenBucket(int capacity, double fillRate) { 13 | this.capacity = capacity; 14 | this.fillRate = fillRate; 15 | this.tokens = capacity; 16 | this.lastRefillTimestamp = System.currentTimeMillis(); 17 | this.semaphore = new Semaphore(1); 18 | } 19 | 20 | public TokenBucket(int seconds, int limit) { 21 | this.capacity = limit; 22 | this.fillRate = (double) seconds/limit; 23 | this.tokens = limit; 24 | this.semaphore = new Semaphore(1); 25 | this.lastRefillTimestamp = System.currentTimeMillis(); 26 | } 27 | 28 | public TokenBucket() { 29 | this.semaphore = new Semaphore(1); 30 | } 31 | 32 | public TokenBucket(Semaphore semaphore) { 33 | this.semaphore = semaphore; 34 | } 35 | 36 | @Override 37 | public void init(Integer limit, Integer seconds) { 38 | this.capacity = limit; 39 | this.fillRate = (double) limit/seconds; 40 | this.tokens = limit; 41 | this.lastRefillTimestamp = System.currentTimeMillis(); 42 | } 43 | 44 | @Override 45 | public void init(int capacity, double fillRate) { 46 | this.capacity = capacity; 47 | this.fillRate = fillRate; 48 | this.tokens = capacity; 49 | this.lastRefillTimestamp = System.currentTimeMillis(); 50 | } 51 | 52 | @Override 53 | public void removeFirst() { 54 | synchronized (semaphore){ 55 | tokens++; 56 | } 57 | } 58 | 59 | @Override 60 | public int size() { 61 | return (int) Math.round(capacity - tokens); 62 | } 63 | 64 | @Override 65 | public int optSize() { 66 | return (int)tokens; 67 | } 68 | 69 | @Override 70 | public int maxOptSize() { 71 | return capacity; 72 | } 73 | 74 | @Override 75 | public void sync() { 76 | refill(); 77 | } 78 | 79 | @Override 80 | public Object getSyncMutex() { 81 | return semaphore; 82 | } 83 | 84 | private void refill() { 85 | long currentTime = System.currentTimeMillis(); 86 | double elapsedTime = (double) (currentTime - lastRefillTimestamp)/1000; 87 | double newTokens = elapsedTime * fillRate; 88 | 89 | if (newTokens > 0) { 90 | tokens = Math.min(capacity, tokens + newTokens); 91 | lastRefillTimestamp = currentTime; 92 | } 93 | } 94 | 95 | @Override 96 | public String toString() { 97 | return "TokenBucket{" + "tokens=" + tokens + 98 | '}'; 99 | } 100 | 101 | @Override 102 | public boolean tryAcquire() { 103 | refill(); 104 | synchronized (semaphore){ 105 | // 获取许可证,互斥访问 106 | if (tokens >= 1) { 107 | tokens--; 108 | return true; // 有足够的令牌,允许处理请求 109 | } else { 110 | return false; // 令牌不足,拒绝请求 111 | } 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/handler/AutoAuthHandlerChain.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.handler; 2 | 3 | import com.codingcube.simpleauth.exception.TargetNotFoundException; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author CodingCube
10 | * Authentication Handler Chain 11 | */ 12 | public abstract class AutoAuthHandlerChain { 13 | protected List autoAuthServiceList = new ArrayList<>(); 14 | 15 | public AutoAuthHandlerChain() { 16 | addChain(); 17 | } 18 | 19 | public abstract void addChain(); 20 | 21 | final public AutoAuthHandlerChain add(String beanName){ 22 | return addLast(beanName); 23 | } 24 | 25 | final public AutoAuthHandlerChain add(Class auto){ 26 | autoAuthServiceList.add(auto); 27 | return this; 28 | } 29 | 30 | final public AutoAuthHandlerChain addLast(Class auto){ 31 | autoAuthServiceList.add(auto); 32 | return this; 33 | } 34 | 35 | final public AutoAuthHandlerChain addLast(String beanName){ 36 | autoAuthServiceList.add(beanName); 37 | return this; 38 | } 39 | 40 | final public AutoAuthHandlerChain addFirst(Class auto){ 41 | autoAuthServiceList.add(0, auto); 42 | return this; 43 | } 44 | 45 | final public AutoAuthHandlerChain addFirst(String beanName){ 46 | autoAuthServiceList.add(0, beanName); 47 | return this; 48 | } 49 | 50 | final public AutoAuthHandlerChain addAfter(Class auto, Object target){ 51 | addAfterObject(auto, target); 52 | return this; 53 | } 54 | 55 | final public AutoAuthHandlerChain addAfter(String beanName, Object target){ 56 | addAfterObject(beanName, target); 57 | return this; 58 | } 59 | 60 | final public AutoAuthHandlerChain addBefore(Class auto, Object target){ 61 | addBeforeObject(auto, target); 62 | return this; 63 | } 64 | 65 | final public AutoAuthHandlerChain addBefore(String beanName, Object target){ 66 | addBeforeObject(beanName, target); 67 | return this; 68 | } 69 | 70 | private AutoAuthHandlerChain addAfterObject(Object obj, Object target){ 71 | boolean isFind = false; 72 | for (int i = 0; i < autoAuthServiceList.size(); i++) { 73 | final Object item = autoAuthServiceList.get(i); 74 | if (item.equals(target)){ 75 | autoAuthServiceList.add(i+1, obj); 76 | i++; 77 | isFind = true; 78 | } 79 | } 80 | if (!isFind){ 81 | throw new TargetNotFoundException("Target not found"); 82 | } 83 | return this; 84 | } 85 | 86 | private AutoAuthHandlerChain addBeforeObject(Object obj, Object target){ 87 | boolean isFind = false; 88 | for (int i = 0; i < autoAuthServiceList.size(); i++) { 89 | final Object item = autoAuthServiceList.get(i); 90 | if (item.equals(target)){ 91 | autoAuthServiceList.add(i, obj); 92 | i++; 93 | isFind = true; 94 | } 95 | } 96 | if (!isFind){ 97 | throw new TargetNotFoundException("Target not found"); 98 | } 99 | return this; 100 | } 101 | 102 | 103 | final public List getAutoAuthServiceList() { 104 | return autoAuthServiceList; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/LimitProper.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import com.codingcube.simpleauth.limit.cache.KeyCache; 4 | import com.codingcube.simpleauth.limit.cache.impl.DefaultCache; 5 | import com.codingcube.simpleauth.limit.strategic.DefaultLimitRejectedStratagem; 6 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | 9 | import java.util.Date; 10 | 11 | @ConfigurationProperties(prefix = "simple-auth.limit") 12 | public class LimitProper { 13 | 14 | private String defaultRejected = "com.codingcube.simpleauth.limit.strategic.DefaultLimitRejectedStratagem"; 15 | private static Class defaultRejectedClazz = DefaultLimitRejectedStratagem.class; 16 | 17 | private String defaultBanCache = "com.codingcube.simpleauth.limit.cache.impl.DefaultCache"; 18 | private static Class defaultBanCacheClazz = DefaultCache.class; 19 | 20 | private String defaultLimitCache = "com.codingcube.simpleauth.limit.cache.impl.DefaultCache"; 21 | private static Class defaultLimitCacheClazz = DefaultCache.class; 22 | 23 | private String defaultSecondsCache = "com.codingcube.simpleauth.limit.cache.impl.DefaultCache"; 24 | private static Class defaultSecondsCacheClazz = DefaultCache.class; 25 | 26 | 27 | 28 | public String getDefaultRejected() { 29 | return defaultRejected; 30 | } 31 | 32 | public void setDefaultRejected(String defaultRejected) { 33 | this.defaultRejected = defaultRejected; 34 | 35 | } 36 | 37 | public static Class getDefaultRejectedClazz() { 38 | return defaultRejectedClazz; 39 | } 40 | 41 | public static void setDefaultRejectedClazz(Class defaultRejectedClazz) { 42 | LimitProper.defaultRejectedClazz = defaultRejectedClazz; 43 | } 44 | 45 | public String getDefaultBanCache() { 46 | return defaultBanCache; 47 | } 48 | 49 | public void setDefaultBanCache(String defaultBanCache) { 50 | this.defaultBanCache = defaultBanCache; 51 | } 52 | 53 | public static Class getDefaultBanCacheClazz() { 54 | return defaultBanCacheClazz; 55 | } 56 | 57 | public static void setDefaultBanCacheClazz(Class defaultBanCacheClazz) { 58 | LimitProper.defaultBanCacheClazz = defaultBanCacheClazz; 59 | } 60 | 61 | public String getDefaultLimitCache() { 62 | return defaultLimitCache; 63 | } 64 | 65 | public void setDefaultLimitCache(String defaultLimitCache) { 66 | this.defaultLimitCache = defaultLimitCache; 67 | } 68 | 69 | public static Class getDefaultLimitCacheClazz() { 70 | return defaultLimitCacheClazz; 71 | } 72 | 73 | public static void setDefaultLimitCacheClazz(Class defaultLimitCacheClazz) { 74 | LimitProper.defaultLimitCacheClazz = defaultLimitCacheClazz; 75 | } 76 | 77 | public String getDefaultSecondsCache() { 78 | return defaultSecondsCache; 79 | } 80 | 81 | public void setDefaultSecondsCache(String defaultSecondsCache) { 82 | this.defaultSecondsCache = defaultSecondsCache; 83 | } 84 | 85 | public static Class getDefaultSecondsCacheClazz() { 86 | return defaultSecondsCacheClazz; 87 | } 88 | 89 | public static void setDefaultSecondsCacheClazz(Class defaultSecondsCacheClazz) { 90 | LimitProper.defaultSecondsCacheClazz = defaultSecondsCacheClazz; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/autoconfig/AutoConfigLimitAdvice.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.autoconfig; 2 | 3 | import com.codingcube.simpleauth.autoconfig.domain.Limit; 4 | import com.codingcube.simpleauth.autoconfig.domain.SimpleAuthConfig; 5 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 6 | import com.codingcube.simpleauth.limit.util.LimitHandlerUtil; 7 | import com.codingcube.simpleauth.logging.Log; 8 | import com.codingcube.simpleauth.logging.LogFactory; 9 | import com.codingcube.simpleauth.properties.Bean2Static; 10 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 11 | import org.springframework.context.ApplicationContext; 12 | import org.springframework.core.MethodParameter; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.http.converter.HttpMessageConverter; 15 | import org.springframework.http.server.ServerHttpRequest; 16 | import org.springframework.http.server.ServerHttpResponse; 17 | import org.springframework.http.server.ServletServerHttpRequest; 18 | import org.springframework.util.AntPathMatcher; 19 | import org.springframework.web.bind.annotation.ControllerAdvice; 20 | import org.springframework.web.context.request.RequestContextHolder; 21 | import org.springframework.web.context.request.ServletRequestAttributes; 22 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 23 | 24 | import javax.annotation.Resource; 25 | import javax.servlet.http.HttpServletRequest; 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.Objects; 30 | 31 | @ControllerAdvice 32 | public class AutoConfigLimitAdvice implements ResponseBodyAdvice { 33 | private final List requestLimitItem = new ArrayList<>(); 34 | private final AntPathMatcher antPathMatcher = new AntPathMatcher(); 35 | @Resource 36 | private ApplicationContext applicationContext; 37 | private final Log log; 38 | 39 | @Override 40 | public boolean supports(MethodParameter methodParameter, Class> aClass) { 41 | return true; 42 | } 43 | 44 | public AutoConfigLimitAdvice(LogFactory logFactory, Bean2Static bean2Static) { 45 | final SimpleAuthConfig simpleAuthConfig = AuthHandlerUtil.simpleAuthConfig; 46 | if (simpleAuthConfig != null && simpleAuthConfig.getLimitMap().size()!=0){ 47 | final Map limitMap = simpleAuthConfig.getLimitMap(); 48 | limitMap.forEach( 49 | (key, value)-> requestLimitItem.add( 50 | new RequestLimitItem(value.getPaths().getPath(), 51 | value.getTimes(), 52 | value.getSeconds(), 53 | value.getBan(), 54 | value.getItemStrategicClass(), 55 | value.getSignStrategicClass(), 56 | value.getEffectiveStrategicClass(), 57 | value.getTokenLimitClass(), 58 | value.getRejectedClass() 59 | ) 60 | ) 61 | ); 62 | } 63 | this.log = logFactory.getLimitLog(this.getClass()); 64 | } 65 | 66 | @Override 67 | public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { 68 | final HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest(); 69 | 70 | LimitHandlerUtil.postHandlerRequestLimitItem(request, 71 | applicationContext, log, o, "Profile configuration limit"); 72 | return o; 73 | } 74 | 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/util/CompleteLimit.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.util; 2 | 3 | import com.codingcube.simpleauth.limit.LimitInfoUtil; 4 | 5 | import java.util.Date; 6 | import java.util.Deque; 7 | import java.util.LinkedList; 8 | import java.util.Map; 9 | import java.util.concurrent.Semaphore; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | public class CompleteLimit implements TokenLimit{ 13 | Deque optList = new LinkedList<>(); 14 | /** 15 | * 信号量用于控制令牌的发放 16 | */ 17 | private final Semaphore semaphore; 18 | /** 19 | * 限制次数 20 | */ 21 | private Integer limit; 22 | /** 23 | * 限制时间seconds 24 | */ 25 | private Integer seconds; 26 | /** 27 | * SECOND_SCALE 28 | */ 29 | private final static Long SECOND_SCALE = 1000L; 30 | 31 | public CompleteLimit() { 32 | this.semaphore = new Semaphore(1); 33 | } 34 | 35 | public CompleteLimit(Integer limit, Integer seconds) { 36 | this.semaphore = new Semaphore(1); 37 | this.seconds = seconds; 38 | this.limit = limit; 39 | } 40 | 41 | @Override 42 | public void init(Integer limit, Integer seconds) { 43 | this.seconds = seconds; 44 | this.limit = limit; 45 | } 46 | 47 | @Override 48 | public void init(int capacity, double fillRate) { 49 | this.seconds = Math.toIntExact(Math.round(capacity / fillRate)); 50 | this.limit = capacity; 51 | } 52 | 53 | @Override 54 | public void removeFirst() { 55 | synchronized (semaphore){ 56 | optList.removeFirst(); 57 | } 58 | } 59 | 60 | @Override 61 | public int size() { 62 | return optList.size(); 63 | } 64 | 65 | @Override 66 | public int optSize() { 67 | return this.limit - size(); 68 | } 69 | 70 | @Override 71 | public int maxOptSize() { 72 | return this.limit; 73 | } 74 | 75 | @Override 76 | public void sync() { 77 | Date currentDate = new Date(); 78 | while (optList.size()>0 &&(currentDate.getTime() - optList.getLast().getTime())/1000 > seconds){ 79 | optList.removeLast(); 80 | } 81 | } 82 | 83 | @Override 84 | public Object getSyncMutex() { 85 | return semaphore; 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return optList.toString(); 91 | } 92 | 93 | @Override 94 | public boolean tryAcquire() { 95 | synchronized (semaphore){ 96 | if (optList.size()>=limit){ 97 | //Remove expired data before judging, and return false if it still overflows. 98 | while (optList.size() > 0){ 99 | final Date last = optList.getLast(); 100 | final Date current = new Date(); 101 | if ((current.getTime() - last.getTime()) > seconds*SECOND_SCALE){ 102 | //expired 103 | optList.removeLast(); 104 | }else { 105 | break; 106 | } 107 | } 108 | //After deleting expired records, the number of times the limit is met. 109 | if (optList.size() seconds*SECOND_SCALE){ 123 | //expired 124 | optList.removeLast(); 125 | }else { 126 | optList.addFirst(new Date()); 127 | 128 | } 129 | return true; 130 | } 131 | 132 | } 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/interceptor/AutoAuthInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.interceptor; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 4 | import com.codingcube.simpleauth.exception.PermissionsException; 5 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 6 | import com.codingcube.simpleauth.exception.TargetNotFoundException; 7 | import com.codingcube.simpleauth.logging.Log; 8 | import com.codingcube.simpleauth.logging.LogFactory; 9 | import com.codingcube.simpleauth.logging.logformat.LogAuthFormat; 10 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 11 | import com.fasterxml.jackson.databind.exc.InvalidNullException; 12 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 13 | import org.springframework.context.ApplicationContext; 14 | import org.springframework.web.context.request.RequestContextHolder; 15 | import org.springframework.web.context.request.ServletRequestAttributes; 16 | import org.springframework.web.servlet.HandlerInterceptor; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import java.lang.reflect.InvocationTargetException; 21 | import java.util.List; 22 | import java.util.Objects; 23 | 24 | /** 25 | * @author CodingCube
26 | * The Handler Interceptor of SimpleAuth
27 | * Implementing Rapid Interceptor Configuration Functionality* 28 | */ 29 | public class AutoAuthInterceptor implements HandlerInterceptor { 30 | private Class handlerClass; 31 | private String handlerBeanName; 32 | private AutoAuthHandler handler; 33 | private final ApplicationContext applicationContext; 34 | private final Class rejectedStratagem; 35 | private final Log log; 36 | 37 | public AutoAuthInterceptor(Class handlerClass, 38 | ApplicationContext applicationContext, 39 | LogFactory logFactory, 40 | Class rejectedStratagem) { 41 | this.handlerClass = handlerClass; 42 | this.applicationContext = applicationContext; 43 | this.log = logFactory.getLog(this.getClass()); 44 | this.rejectedStratagem = rejectedStratagem; 45 | } 46 | 47 | public AutoAuthInterceptor(String handlerBeanName, 48 | ApplicationContext applicationContext, 49 | LogFactory logFactory, 50 | Class rejectedStratagem) { 51 | this.handlerBeanName = handlerBeanName; 52 | this.applicationContext = applicationContext; 53 | this.log = logFactory.getLog(this.getClass()); 54 | this.rejectedStratagem = rejectedStratagem; 55 | } 56 | 57 | @Override 58 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ 59 | if (this.handler == null){ 60 | AutoAuthHandler autoAuthHandler; 61 | if (handlerClass != null){ 62 | autoAuthHandler = AuthHandlerUtil.getBean(applicationContext, handlerClass); 63 | }else if (handlerBeanName != null){ 64 | autoAuthHandler = (AutoAuthHandler) applicationContext.getBean(handlerBeanName); 65 | }else { 66 | throw new TargetNotFoundException("Requires either handlerClass or handlerBeanName"); 67 | } 68 | this.handler = autoAuthHandler; 69 | } 70 | 71 | final List permissions = this.handler.getPermissions(); 72 | String permissionString = permissions==null?"":permissions.toString(); 73 | 74 | final boolean author = this.handler.isAuthor(request, permissionString); 75 | LogAuthFormat logAuthFormat = new LogAuthFormat(request, "SimpleAuth Interceptor", author, this.handlerClass.getName(), permissionString, this.rejectedStratagem); 76 | log.debug(logAuthFormat.toString()); 77 | if (!author){ 78 | final AuthRejectedStratagem rejectedStratagem = AuthHandlerUtil.getBean(applicationContext, this.rejectedStratagem); 79 | rejectedStratagem.doRejected(request, 80 | ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(), 81 | logAuthFormat); 82 | } 83 | return true; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/LogFactory.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.logging; 2 | 3 | import com.codingcube.simpleauth.exception.LogException; 4 | import com.codingcube.simpleauth.logging.jdk.Jdk14LoggingImpl; 5 | import com.codingcube.simpleauth.logging.nologging.NoLoggingImpl; 6 | import com.codingcube.simpleauth.logging.stdout.StdOutImpl; 7 | import com.codingcube.simpleauth.properties.LogProper; 8 | import org.springframework.stereotype.Component; 9 | import java.lang.reflect.Constructor; 10 | 11 | /** 12 | * @author CodingCube
13 | * logFactory 14 | */ 15 | @Component 16 | public class LogFactory { 17 | 18 | private Constructor logConstructor; 19 | private Constructor limitLogConstructor; 20 | private Constructor validateLogConstructor; 21 | 22 | 23 | public LogFactory(LogProper logProper) { 24 | final String log = logProper.getLogImpl(); 25 | logConstructor = getLogImpl(log); 26 | 27 | final String limitLogImpl = logProper.getLimitLogImpl(); 28 | limitLogConstructor = getLogImpl(limitLogImpl); 29 | 30 | final String validatedLogImpl = logProper.getValidatedLogImpl(); 31 | validateLogConstructor = getLogImpl(validatedLogImpl); 32 | 33 | getLog(this.getClass()).debug("Auth Logging initialized using "+logConstructor.getDeclaringClass()+" adapter."); 34 | getLimitLog(this.getClass()).debug("Limit Logging initialized using "+limitLogConstructor.getDeclaringClass()+" adapter."); 35 | getValidateLog(this.getClass()).debug("Validate Logging initialized using "+validateLogConstructor.getDeclaringClass()+" adapter."); 36 | 37 | } 38 | 39 | public Constructor getLogImpl(String logImplString){ 40 | if ("NoLogging".equalsIgnoreCase(logImplString)){ 41 | return getImplementation(NoLoggingImpl.class); 42 | }else if ("StdOut".equalsIgnoreCase(logImplString)){ 43 | return getImplementation(StdOutImpl.class); 44 | }else if ("jdk".equalsIgnoreCase(logImplString)){ 45 | return getImplementation(Jdk14LoggingImpl.class); 46 | }else { 47 | try { 48 | final Class aClass = (Class) Class.forName(logImplString); 49 | return getImplementation(aClass); 50 | } catch (ClassNotFoundException e) { 51 | e.printStackTrace(); 52 | return getImplementation(StdOutImpl.class); 53 | } 54 | } 55 | } 56 | 57 | public Log getLog(Class aClass) { 58 | return getLog(aClass.getName()); 59 | } 60 | 61 | public Log getLimitLog(Class aClass) { 62 | try { 63 | return limitLogConstructor.newInstance(aClass.getName()); 64 | } catch (Throwable t) { 65 | throw new LogException("Error creating logger for limit function " + aClass.getName() + ". Cause: " + t, t); 66 | } 67 | } 68 | 69 | public Log getValidateLog(Class aClass) { 70 | try { 71 | return validateLogConstructor.newInstance(aClass.getName()); 72 | } catch (Throwable t) { 73 | throw new LogException("Error creating logger for validate function " + aClass.getName() + ". Cause: " + t, t); 74 | } 75 | } 76 | 77 | public Log getLog(String logger) { 78 | try { 79 | return logConstructor.newInstance(logger); 80 | } catch (Throwable t) { 81 | throw new LogException("Error creating logger for logger " + logger + ". Cause: " + t, t); 82 | } 83 | } 84 | 85 | private Constructor getImplementation(Class implClass) { 86 | try { 87 | return implClass.getConstructor(String.class); 88 | } catch (Throwable t) { 89 | throw new LogException("Error setting Log implementation. Needs to have a constructor that takes a String as a parameter."); 90 | } 91 | } 92 | 93 | public void setLogConstructor(Constructor logConstructor) { 94 | this.logConstructor = logConstructor; 95 | } 96 | 97 | public void setLimitLogConstructor(Constructor limitLogConstructor) { 98 | this.limitLogConstructor = limitLogConstructor; 99 | } 100 | 101 | public void setValidateLogConstructor(Constructor validateLogConstructor) { 102 | this.validateLogConstructor = validateLogConstructor; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/postprocessor/CacheAutoValidatedBeanPostProcessor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.postprocessor; 2 | 3 | import com.codingcube.simpleauth.properties.ValidateProper; 4 | import com.codingcube.simpleauth.validated.annotation.SimpleValidate; 5 | import com.codingcube.simpleauth.validated.aspect.AutoValidated; 6 | import org.springframework.beans.BeansException; 7 | import org.springframework.beans.factory.config.BeanPostProcessor; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.annotation.Resource; 11 | import java.lang.annotation.Annotation; 12 | import java.lang.reflect.Method; 13 | 14 | /** 15 | * 在使用前缓存信息的工具 * 16 | * @author CodingCube* 17 | */ 18 | @Component 19 | public class CacheAutoValidatedBeanPostProcessor implements BeanPostProcessor { 20 | @Resource 21 | private AutoValidated autoValidated; 22 | @Resource 23 | private ValidateProper validateProper; 24 | 25 | @Override 26 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 27 | final SimpleValidate classAnnotation = bean.getClass().getAnnotation(SimpleValidate.class); 28 | final Class classValidateObj = classAnnotation==null ? Object.class:classAnnotation.value(); 29 | 30 | final Method[] methods = bean.getClass().getMethods(); 31 | for (Method method : methods) { 32 | final Class[] parameterTypes = method.getParameterTypes(); 33 | final SimpleValidate methodAnnotation = method.getAnnotation(SimpleValidate.class); 34 | 35 | final Class methodValidateObj = methodAnnotation==null ? Object.class:methodAnnotation.value(); 36 | 37 | final Annotation[][] allAnnotation = method.getParameterAnnotations(); 38 | for (int i = 0; i < allAnnotation.length; i++) { 39 | Annotation[] allParamAnnotation = allAnnotation[i]; 40 | for (Annotation paramAnnotation : allParamAnnotation) { 41 | if (paramAnnotation.annotationType() == SimpleValidate.class){ 42 | final SimpleValidate paramValidateAnnotation = (SimpleValidate) paramAnnotation; 43 | final Class paramValidateObj = paramValidateAnnotation.value(); 44 | final String[] methodsString = paramValidateAnnotation.methods(); 45 | 46 | final Class validateObj = getValidateObj( 47 | ValidateProper.getDefaultValidateObjectClazz(), 48 | paramValidateObj, 49 | methodValidateObj, 50 | classValidateObj); 51 | if (methodsString.length == 0){ 52 | final String key = autoValidated.parameterKey(validateObj, parameterTypes[i]); 53 | autoValidated.initReflectParameterCache(key, validateObj, parameterTypes[i]); 54 | }else { 55 | for (String methodName : methodsString) { 56 | autoValidated.initReflectMethodCache(autoValidated.key(validateObj, methodName), 57 | validateObj, methodName); 58 | } 59 | } 60 | 61 | } 62 | } 63 | } 64 | if (methodAnnotation != null){ 65 | String[] methodsString = methodAnnotation.methods(); 66 | if (methodsString.length == 0){ 67 | methodsString = new String[1]; 68 | methodsString[0] = "validate"; 69 | } 70 | final Class validateObj = getValidateObj( 71 | ValidateProper.getDefaultValidateObjectClazz(), 72 | methodValidateObj, 73 | classValidateObj); 74 | 75 | for (String methodName : methodsString) { 76 | autoValidated.initReflectMethodCache(autoValidated.key(validateObj, methodName), 77 | validateObj, methodName); 78 | } 79 | } 80 | } 81 | return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName); 82 | } 83 | 84 | private Class getValidateObj(Class defaultValue, Class... valueList){ 85 | for (Class value : valueList) { 86 | if (value != Object.class){ 87 | return value; 88 | } 89 | } 90 | return defaultValue; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/password/BCryptPasswordEncoder.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.password; 2 | 3 | import java.security.SecureRandom; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | import com.codingcube.simpleauth.security.crypto.encryptor.impl.BCrypt; 8 | import org.apache.commons.logging.Log; 9 | import org.apache.commons.logging.LogFactory; 10 | 11 | public class BCryptPasswordEncoder implements PasswordEncoder { 12 | private Pattern BCRYPT_PATTERN; 13 | private final Log logger; 14 | private final int strength; 15 | private final BCryptPasswordEncoder.BCryptVersion version; 16 | private final SecureRandom random; 17 | 18 | public BCryptPasswordEncoder() { 19 | this(-1); 20 | } 21 | 22 | public BCryptPasswordEncoder(int strength) { 23 | this(strength, (SecureRandom)null); 24 | } 25 | 26 | public BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version) { 27 | this(version, (SecureRandom)null); 28 | } 29 | 30 | public BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version, SecureRandom random) { 31 | this(version, -1, random); 32 | } 33 | 34 | public BCryptPasswordEncoder(int strength, SecureRandom random) { 35 | this(BCryptPasswordEncoder.BCryptVersion.$2A, strength, random); 36 | } 37 | 38 | public BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version, int strength) { 39 | this(version, strength, (SecureRandom)null); 40 | } 41 | 42 | public BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version, int strength, SecureRandom random) { 43 | this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2(a|y|b)?\\$(\\d\\d)\\$[./0-9A-Za-z]{53}"); 44 | this.logger = LogFactory.getLog(this.getClass()); 45 | if (strength == -1 || strength >= 4 && strength <= 31) { 46 | this.version = version; 47 | this.strength = strength == -1 ? 10 : strength; 48 | this.random = random; 49 | } else { 50 | throw new IllegalArgumentException("Bad strength"); 51 | } 52 | } 53 | 54 | public String encode(CharSequence rawPassword) { 55 | if (rawPassword == null) { 56 | throw new IllegalArgumentException("rawPassword cannot be null"); 57 | } else { 58 | String salt = this.getSalt(); 59 | return BCrypt.hashpw(rawPassword.toString(), salt); 60 | } 61 | } 62 | 63 | private String getSalt() { 64 | return this.random != null ? BCrypt.gensalt(this.version.getVersion(), this.strength, this.random) : BCrypt.gensalt(this.version.getVersion(), this.strength); 65 | } 66 | 67 | public boolean matches(CharSequence rawPassword, String encodedPassword) { 68 | if (rawPassword == null) { 69 | throw new IllegalArgumentException("rawPassword cannot be null"); 70 | } else if (encodedPassword != null && encodedPassword.length() != 0) { 71 | if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) { 72 | this.logger.warn("Encoded password does not look like BCrypt"); 73 | return false; 74 | } else { 75 | return BCrypt.checkpw(rawPassword.toString(), encodedPassword); 76 | } 77 | } else { 78 | this.logger.warn("Empty encoded password"); 79 | return false; 80 | } 81 | } 82 | 83 | public boolean upgradeEncoding(String encodedPassword) { 84 | if (encodedPassword != null && encodedPassword.length() != 0) { 85 | Matcher matcher = this.BCRYPT_PATTERN.matcher(encodedPassword); 86 | if (!matcher.matches()) { 87 | throw new IllegalArgumentException("Encoded password does not look like BCrypt: " + encodedPassword); 88 | } else { 89 | int strength = Integer.parseInt(matcher.group(2)); 90 | return strength < this.strength; 91 | } 92 | } else { 93 | this.logger.warn("Empty encoded password"); 94 | return false; 95 | } 96 | } 97 | 98 | public static enum BCryptVersion { 99 | $2A("$2a"), 100 | $2Y("$2y"), 101 | $2B("$2b"); 102 | 103 | private final String version; 104 | 105 | private BCryptVersion(String version) { 106 | this.version = version; 107 | } 108 | 109 | public String getVersion() { 110 | return this.version; 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/properties/Bean2Static.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.properties; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 5 | import com.codingcube.simpleauth.autoconfig.execption.ConfigurationParseException; 6 | import com.codingcube.simpleauth.exception.TargetNotFoundException; 7 | import com.codingcube.simpleauth.limit.cache.KeyCache; 8 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 9 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 10 | import com.codingcube.simpleauth.limit.util.TokenBucket; 11 | import com.codingcube.simpleauth.limit.util.TokenLimit; 12 | import com.codingcube.simpleauth.validated.strategic.ValidateRejectedStratagem; 13 | import org.springframework.stereotype.Component; 14 | 15 | @Component 16 | public class Bean2Static { 17 | 18 | public Bean2Static(LogProper logProper, FunctionProper functionProper, AuthProper authProper, LimitProper limitProper, ValidateProper validateProper) { 19 | LogProper.setStaticShowOptList(logProper.getShowOptList()); 20 | 21 | FunctionProper.setHandlerCacheStatic(functionProper.isHandlerCache()); 22 | 23 | //初始化全局限流策略 24 | final String limitPlan = functionProper.getLimitPlan().toLowerCase(); 25 | switch (limitPlan){ 26 | case "default": 27 | FunctionProper.setTokenLimitClass(CompleteLimit.class); 28 | break; 29 | case "tokenbucket": 30 | FunctionProper.setTokenLimitClass(TokenBucket.class); 31 | break; 32 | default: 33 | try { 34 | FunctionProper.setTokenLimitClass((Class) Class.forName(limitPlan)); 35 | } catch (ClassNotFoundException e) { 36 | FunctionProper.setTokenLimitClass(CompleteLimit.class); 37 | throw new TargetNotFoundException("Initialization error, CompleteLimit has been assembled.", e); 38 | } 39 | } 40 | 41 | AuthProper.setVerifyKeyStatic(authProper.getVerifyKey()); 42 | AuthProper.setVerifyValueStatic(authProper.getVerifyValue()); 43 | 44 | LogProper.setDateFormatStatic(logProper.getDateFormat()); 45 | 46 | //AuthProper 47 | try { 48 | final Class defaultHandlerClazz = (Class) Class.forName(authProper.getDefaultHandler()); 49 | AuthProper.setDefaultHandlerClazz(defaultHandlerClazz); 50 | 51 | final Class defaultRejectedClazz = (Class) Class.forName(authProper.getDefaultRejected()); 52 | AuthProper.setDefaultRejectedClazz(defaultRejectedClazz); 53 | } catch (ClassNotFoundException e) { 54 | throw new ConfigurationParseException(authProper.getDefaultRejected()+" not found"); 55 | } 56 | 57 | //LimitProper 58 | try { 59 | final Class defaultRejectedClazz = (Class) Class.forName(limitProper.getDefaultRejected()); 60 | LimitProper.setDefaultRejectedClazz(defaultRejectedClazz); 61 | 62 | final Class defaultBanCacheClazz = (Class) Class.forName(limitProper.getDefaultBanCache()); 63 | LimitProper.setDefaultBanCacheClazz(defaultBanCacheClazz); 64 | 65 | final Class defaultLimitCacheClazz = (Class) Class.forName(limitProper.getDefaultLimitCache()); 66 | LimitProper.setDefaultLimitCacheClazz(defaultLimitCacheClazz); 67 | 68 | final Class defaultSecondsCacheClazz = (Class) Class.forName(limitProper.getDefaultSecondsCache()); 69 | LimitProper.setDefaultSecondsCacheClazz(defaultSecondsCacheClazz); 70 | 71 | } catch (ClassNotFoundException e) { 72 | throw new ConfigurationParseException(authProper.getDefaultRejected()+" not found"); 73 | } 74 | 75 | //ValidateProper 76 | try { 77 | final Class defaultRejectedClazz = (Class) Class.forName(validateProper.getDefaultRejected()); 78 | ValidateProper.setDefaultRejectedClazz(defaultRejectedClazz); 79 | 80 | final Class defaultValidateObjectClazz = Class.forName(validateProper.getDefaultValidateObject()); 81 | ValidateProper.setDefaultValidateObjectClazz(defaultValidateObjectClazz); 82 | } catch (ClassNotFoundException e) { 83 | throw new ConfigurationParseException(authProper.getDefaultRejected()+" not found"); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/security/crypto/encryptor/impl/AesByteEncryptor.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.security.crypto.encryptor.impl; 2 | 3 | import com.codingcube.simpleauth.security.crypto.encryptor.ByteEncryptor; 4 | 5 | import javax.crypto.*; 6 | import javax.crypto.spec.GCMParameterSpec; 7 | import javax.crypto.spec.PBEKeySpec; 8 | import javax.crypto.spec.SecretKeySpec; 9 | import java.nio.charset.StandardCharsets; 10 | import java.security.InvalidAlgorithmParameterException; 11 | import java.security.InvalidKeyException; 12 | import java.security.NoSuchAlgorithmException; 13 | import java.security.SecureRandom; 14 | import java.security.spec.KeySpec; 15 | 16 | public class AesByteEncryptor implements ByteEncryptor { 17 | private static final int GCM_NONCE_LENGTH = 12; 18 | private static final int GCM_TAG_LENGTH = 16; // 128 bits 19 | private final String password; 20 | private final String salt; 21 | 22 | public AesByteEncryptor(String password, String salt){ 23 | this.password = password; 24 | this.salt = salt; 25 | } 26 | 27 | @Override 28 | public byte[] encrypt(byte[] byteArray) { 29 | // Generate a random 12-byte nonce (IV) 30 | SecureRandom secureRandom = new SecureRandom(); 31 | byte[] iv = new byte[GCM_NONCE_LENGTH]; 32 | secureRandom.nextBytes(iv); 33 | 34 | // Derive a 256-bit AES key from the password and salt using PBKDF2 35 | SecretKey key = null; 36 | try { 37 | key = deriveKey(password, salt); 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | 42 | // Create GCM parameter specification 43 | GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); 44 | 45 | // Initialize the cipher for encryption 46 | Cipher encryptCipher = null; 47 | try { 48 | encryptCipher = Cipher.getInstance("AES/GCM/NoPadding"); 49 | } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { 50 | e.printStackTrace(); 51 | } 52 | try { 53 | assert encryptCipher != null; 54 | encryptCipher.init(Cipher.ENCRYPT_MODE, key, gcmParameterSpec); 55 | } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { 56 | e.printStackTrace(); 57 | } 58 | 59 | // Encrypt the plaintext 60 | byte[] cipherText = new byte[0]; 61 | try { 62 | cipherText = encryptCipher.doFinal(byteArray); 63 | } catch (IllegalBlockSizeException | BadPaddingException e) { 64 | e.printStackTrace(); 65 | } 66 | // Combine the IV and ciphertext 67 | byte[] encryptedData = new byte[iv.length + cipherText.length]; 68 | System.arraycopy(iv, 0, encryptedData, 0, iv.length); 69 | System.arraycopy(cipherText, 0, encryptedData, iv.length, cipherText.length); 70 | 71 | // Encode the encrypted data in Base64 72 | return encryptedData; 73 | } 74 | 75 | @Override 76 | public byte[] decrypt(byte[] encryptedByteArray) { 77 | try { 78 | // Extract the IV and ciphertext 79 | byte[] iv = new byte[GCM_NONCE_LENGTH]; 80 | byte[] cipherText = new byte[encryptedByteArray.length - GCM_NONCE_LENGTH]; 81 | System.arraycopy(encryptedByteArray, 0, iv, 0, GCM_NONCE_LENGTH); 82 | System.arraycopy(encryptedByteArray, GCM_NONCE_LENGTH, cipherText, 0, cipherText.length); 83 | 84 | // Derive a 256-bit AES key from the password and salt using PBKDF2 85 | SecretKey key = deriveKey(password, salt); 86 | 87 | // Create GCM parameter specification 88 | GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); 89 | 90 | // Initialize the cipher for decryption 91 | Cipher decryptCipher = Cipher.getInstance("AES/GCM/NoPadding"); 92 | decryptCipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec); 93 | 94 | // Decrypt the ciphertext 95 | return decryptCipher.doFinal(cipherText); 96 | }catch (Exception e){ 97 | e.printStackTrace(); 98 | 99 | } 100 | return new byte[0]; 101 | } 102 | 103 | // Derive a 256-bit AES key from the password and salt using PBKDF2 104 | private static SecretKey deriveKey(String password, String salt) throws Exception { 105 | int iterationCount = 10000; 106 | int keyLength = 256; // 256 bits 107 | KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(StandardCharsets.UTF_8), iterationCount, keyLength); 108 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); 109 | byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); 110 | return new SecretKeySpec(keyBytes, "AES"); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/logging/logformat/LogLimitFormat.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.logging.logformat; 2 | 3 | import com.codingcube.simpleauth.limit.LimitInfoUtil; 4 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 5 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 6 | import com.codingcube.simpleauth.limit.util.TokenLimit; 7 | import com.codingcube.simpleauth.properties.LogProper; 8 | import com.codingcube.simpleauth.limit.strategic.EffectiveStrategic; 9 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 10 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 11 | 12 | import java.time.LocalDateTime; 13 | import java.time.format.DateTimeFormatter; 14 | import java.util.Date; 15 | import java.util.Deque; 16 | 17 | public class LogLimitFormat { 18 | private final int times; 19 | private final int seconds; 20 | private final int ban; 21 | private final String item; 22 | private final Class signStrategic; 23 | private final String sign; 24 | private final String source; 25 | private final boolean judgeAfterReturn; 26 | private final Class effectiveStrategic; 27 | private final boolean effective; 28 | private final boolean result; 29 | private final Class rejectedClass; 30 | private final DateTimeFormatter dateFormatter; 31 | 32 | 33 | public LogLimitFormat(int times, 34 | int seconds, 35 | int ban, 36 | String item, 37 | Class signStrategic, 38 | String sign, 39 | String source, 40 | boolean judgeAfterReturn, 41 | Class effectiveStrategic, 42 | boolean effective, boolean result, 43 | Class rejectedClass) { 44 | this.times = times; 45 | this.seconds = seconds; 46 | this.ban = ban; 47 | this.item = item; 48 | this.signStrategic = signStrategic; 49 | this.sign = sign; 50 | this.source = source; 51 | this.judgeAfterReturn = judgeAfterReturn; 52 | this.effectiveStrategic = effectiveStrategic; 53 | this.effective = effective; 54 | this.result = result; 55 | this.rejectedClass = rejectedClass; 56 | 57 | this.dateFormatter = DateTimeFormatter.ofPattern(LogProper.getDateFormatStatic()); 58 | } 59 | 60 | @Override 61 | public String toString() { 62 | TokenLimit optionList = LimitInfoUtil.getSignOptionList(item, sign); 63 | if (optionList == null){ 64 | optionList = new CompleteLimit(); 65 | } 66 | StringBuilder sb = new StringBuilder("SimpleAuth limit => \r\n" + "\tmax-times: " + times + "\r\n" + 67 | "\ttime: "+dateFormatter.format(LocalDateTime.now())+"\r\n"+ 68 | "\tnumber of times: " + optionList.size() + "\r\n" + 69 | "\tseconds: " + seconds + "\r\n" + 70 | "\tban: " + ban + "\r\n" + 71 | "\titem: " + item + "\r\n" + 72 | "\tsignStrategic: " + signStrategic + "\r\n" + 73 | "\tsign: " + sign + "\r\n" + 74 | "\tsource: " + source + "\r\n" + 75 | "\tjudgeAfterReturn: "+ judgeAfterReturn +"\r\n" + 76 | "\teffectiveStrategic: " + effectiveStrategic + "\r\n" + 77 | "\teffective: " + effective + "\r\n" + 78 | "\trejected Class: " + rejectedClass + "\r\n"); 79 | if (LogProper.getStaticShowOptList()){ 80 | sb.append("\toptionList: ").append(optionList).append("\r\n"); 81 | } 82 | sb.append("\tPass or not: ").append(result); 83 | return sb.toString(); 84 | } 85 | 86 | public int getTimes() { 87 | return times; 88 | } 89 | 90 | public int getSeconds() { 91 | return seconds; 92 | } 93 | 94 | public int getBan() { 95 | return ban; 96 | } 97 | 98 | public String getItem() { 99 | return item; 100 | } 101 | 102 | public Class getSignStrategic() { 103 | return signStrategic; 104 | } 105 | 106 | public String getSign() { 107 | return sign; 108 | } 109 | 110 | public String getSource() { 111 | return source; 112 | } 113 | 114 | public boolean isJudgeAfterReturn() { 115 | return judgeAfterReturn; 116 | } 117 | 118 | public Class getEffectiveStrategic() { 119 | return effectiveStrategic; 120 | } 121 | 122 | public boolean isEffective() { 123 | return effective; 124 | } 125 | 126 | public boolean isResult() { 127 | return result; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/util/LimitHandlerUtil.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.util; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 4 | import com.codingcube.simpleauth.limit.LimitInfoUtil; 5 | import com.codingcube.simpleauth.limit.dynamic.RequestLimitItem; 6 | import com.codingcube.simpleauth.limit.strategic.EffectiveStrategic; 7 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 8 | import com.codingcube.simpleauth.logging.Log; 9 | import com.codingcube.simpleauth.logging.logformat.LogLimitFormat; 10 | import com.codingcube.simpleauth.util.AuthHandlerUtil; 11 | import org.springframework.context.ApplicationContext; 12 | import org.springframework.util.AntPathMatcher; 13 | import org.springframework.web.context.request.RequestContextHolder; 14 | import org.springframework.web.context.request.ServletRequestAttributes; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | import java.util.List; 18 | import java.util.Objects; 19 | 20 | public class LimitHandlerUtil { 21 | private final static String ACCORD_SIGN = "SIMPLEAUTH_VERIFY_SIGN"; 22 | public static void preHandlerRequestLimitItem(List requestLimitItem, 23 | AntPathMatcher antPathMatcher, 24 | HttpServletRequest request, 25 | ApplicationContext applicationContext, 26 | Log log, 27 | String source){ 28 | final String requestURI = request.getRequestURI(); 29 | for (RequestLimitItem limitItem : requestLimitItem) { 30 | final List pathList = limitItem.getPath(); 31 | for (String path : pathList) { 32 | if (antPathMatcher.match(path, requestURI)) { 33 | //Create sign 34 | SignStrategic signStrategic = AuthHandlerUtil.getBean(applicationContext, limitItem.getSignStrategic()); 35 | final String sign = signStrategic.sign(request, null); 36 | 37 | //Verify that this request is recorded. 38 | final SignStrategic itemStrategic = AuthHandlerUtil.getBean(applicationContext, limitItem.getItemStrategic()); 39 | final String item = itemStrategic.sign(request, null); 40 | 41 | request.setAttribute(ACCORD_SIGN + source, new AttributeItem(limitItem, sign, item)); 42 | 43 | final Boolean addRecord = LimitInfoUtil.addRecord(item, sign, limitItem.getTimes(), 44 | limitItem.getSeconds(), limitItem.getBan(), limitItem.getTokenLimit()); 45 | if (!addRecord) { 46 | final Class reject = limitItem.getReject(); 47 | LogLimitFormat limitFormat = new LogLimitFormat(limitItem.getTimes(), limitItem.getSeconds(), limitItem.getBan(), item, limitItem.getSignStrategic(), sign, 48 | source, true, limitItem.getEffectiveStrategic(), true, false, reject); 49 | log.debug(limitFormat.toString()); 50 | final RejectedStratagem bean = AuthHandlerUtil.getBean(applicationContext, reject); 51 | bean.doRejected(request, 52 | ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(), 53 | limitFormat); 54 | return; 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | public static void postHandlerRequestLimitItem(HttpServletRequest request, 62 | ApplicationContext applicationContext, 63 | Log log, 64 | Object result, 65 | String source){ 66 | final AttributeItem attributeItem = (AttributeItem) request.getAttribute(ACCORD_SIGN + source); 67 | if (attributeItem == null){ 68 | return; 69 | } 70 | RequestLimitItem limitItem = attributeItem.getLimitItem(); 71 | if (limitItem == null){ 72 | return; 73 | } 74 | final String sign = attributeItem.getSign(); 75 | final String item = attributeItem.getItem(); 76 | 77 | EffectiveStrategic effectiveStrategicInstance = AuthHandlerUtil.getBean(applicationContext, limitItem.getEffectiveStrategic()); 78 | final Boolean isEffective = effectiveStrategicInstance.effective(request,null, result); 79 | LogLimitFormat limitFormat = new LogLimitFormat(limitItem.getTimes(), limitItem.getSeconds(), limitItem.getBan(), item, limitItem.getSignStrategic(), sign, 80 | source, true, limitItem.getEffectiveStrategic(), isEffective, true, limitItem.getReject()); 81 | log.debug(limitFormat.toString()); 82 | if (!isEffective){ 83 | LimitInfoUtil.delRecord(item, sign); 84 | } 85 | } 86 | private static class AttributeItem{ 87 | final private RequestLimitItem limitItem; 88 | final private String sign; 89 | final private String item; 90 | 91 | public AttributeItem(RequestLimitItem limitItem, String sign, String item) { 92 | this.limitItem = limitItem; 93 | this.sign = sign; 94 | this.item = item; 95 | } 96 | 97 | public RequestLimitItem getLimitItem() { 98 | return limitItem; 99 | } 100 | 101 | public String getSign() { 102 | return sign; 103 | } 104 | 105 | public String getItem() { 106 | return item; 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/validated/util/Regex.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.validated.util; 2 | 3 | public class Regex { 4 | /** 5 | * 邮箱 6 | */ 7 | public final static String EMAIL = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"; 8 | 9 | /** 10 | * URL 11 | */ 12 | public final static String URL = "^(https?:\\/\\/)?(([0-9a-z.]+\\.[a-z]+)|(([0-9]{1,3}\\.){3}[0-9]{1,3}))(:[0-9]+)?(\\/[0-9a-z%/.\\-_]*)?(\\?[0-9a-z=&%_\\-]*)?(\\#[0-9a-z=&%_\\-]*)?$"; 13 | 14 | /** 15 | * 提取超链接 16 | */ 17 | public final static String EXTRACT_HYPERLINK = "(]*)(href=”https?:\\\\/\\\\/)((?!(?:(?:www\\\\.)?’.implode(‘|(?:www\\\\.)?’, $follow_list).’))[^” rel=”external nofollow” ]+)”((?!.*\\\\brel=)[^>]*)(?:[^>]*)>"; 18 | 19 | /** 20 | * 域名 21 | */ 22 | public final static String DOMAIN_NAME = "^[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,}$"; 23 | 24 | /** 25 | * 长度在6~18之间,只能包含字母、数字和下划线 26 | * The length should be between 6 and 18, and can only contain letters, numbers, and underscores. 27 | */ 28 | public final static String PASSWORD = "^[a-zA-Z]\\w{5,17}$"; 29 | 30 | /** 31 | * 必须包含大小写字母和数字的组合,可以使用特殊字符,长度在8-16之间 32 | * It must contain a combination of uppercase and lowercase letters, as well as numbers. Special characters are allowed, and the length should be between 8 and 16. 33 | */ 34 | public final static String STRONG_PASSWORD = "^(?=.\\d)(?=.[a-z])(?=.*[A-Z]).{8,16}$"; 35 | 36 | /** 37 | * 必须包含大小写字母、数字、特殊字符的组合,长度在8-16之间 38 | * 39 | * It must contain a combination of uppercase and lowercase letters, numbers, and special characters. The length should be between 8 and 16. 40 | */ 41 | public final static String COMPLEX_PASSWORD = "^(?=(.*[0-9]))(?=.*[\\!@#$%^&*()\\\\[\\]{}\\-_+=~`|:;\"'<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,16}$"; 42 | 43 | /** 44 | * 整数 45 | */ 46 | public final static String WHOLE_NUMBERS = "^[0-9]*$"; 47 | 48 | 49 | /** 50 | * 汉字 51 | */ 52 | public final static String CHINESE_CHARACTER = "^[\\u4e00-\\u9fa5]{0,}$"; 53 | 54 | /** 55 | * 日语字符 56 | */ 57 | public final static String JAPANESE_CHARACTER = "^[\\u3040-\\u309F\\u30A0-\\u30FF\\u31F0-\\u31FF]+$"; 58 | 59 | /** 60 | * 校验日期格式(yyyy-mm-dd) 61 | */ 62 | public final static String DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$"; 63 | 64 | /** 65 | * 必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-16之间 66 | */ 67 | public final static String STRONG_PASSWORD_WITHOUT_SPECIAL_CHARACTER = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,16}$"; 68 | 69 | /** 70 | * 允许5-16字节,允许字母数字下划线 71 | */ 72 | public final static String UNIVERSAL_IDENTITY = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$"; 73 | 74 | /** 75 | * 中国移动电话号码 76 | */ 77 | public final static String CHINESE_MOBIL_PHONE_NUMBER = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$"; 78 | 79 | /** 80 | * 中国固定电话号码 81 | */ 82 | public final static String CHINESE_LANDLINE_NUMBER = "^0\\d{2}(?:-?\\d{8}|-?\\d{7})$"; 83 | 84 | /** 85 | * 国际固定电话号码 86 | */ 87 | public final static String INTERNATIONAL_PHONE_NUMBERS = "^(?:(?:\\(?(?:00|\\+)([1-4]\\d\\d|[1-9]\\d?)\\)?)?[\\-\\.\\ \\\\\\/]?)?((?:\\(?\\d{1,}\\)?[\\-\\.\\ \\\\\\/]?){0,})(?:[\\-\\.\\ \\\\\\/]?(?:#|ext\\.?|extension|x)[\\-\\.\\ \\\\\\/]?(\\d+))?$"; 88 | 89 | /** 90 | * 中国身份证号 91 | */ 92 | public final static String CHINESE_ID_NUMBER = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$"; 93 | 94 | /** 95 | * xml文件名 96 | */ 97 | public final static String XML_FILE_NAME = "^([^\\\\/]+)+\\.[x|X][m|M][l|L]$"; 98 | 99 | /** 100 | * HTML 101 | */ 102 | public final static String HTML = "<(\\S*?)[^>]*>.*?|<.*? />"; 103 | 104 | /** 105 | * 中国邮政编码 106 | */ 107 | public final static String CHINA_POSTAL_CODE = "\\d{6}"; 108 | 109 | /** 110 | * 子网掩码 111 | */ 112 | public final static String SUBNET_MASK = "^((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))$"; 113 | 114 | /** 115 | * 腾讯QQ 116 | */ 117 | public final static String TENCENT_QQ = "^[1-9][0-9]{4,}$"; 118 | 119 | /** 120 | * 带后缀的网络文件路径 121 | */ 122 | public final static String FILE_PATH = "^((\\/|\\\\|\\/\\/|https?:\\\\\\\\|https?:\\/\\/)[a-z0-9 _@\\-^!#$%&+={}.\\/\\\\\\[\\]]+)+\\.[a-z]+$"; 123 | /** 124 | * 中国车牌号 125 | */ 126 | public final static String CHINESE_LICENSE_PLATE_NUMBER = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$"; 127 | 128 | /** 129 | * MAC 130 | */ 131 | public final static String MAC = "^([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})|([0-9A-Fa-f]{2}[-]){5}([0-9A-Fa-f]{2})$"; 132 | 133 | /** 134 | * ipv4 135 | */ 136 | public final static String IPv4 = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$"; 137 | 138 | /** 139 | * 提取ipv4 140 | */ 141 | public final static String EXTRACT_IPv4 = "\\d+\\.\\d+\\.\\d+\\.\\d+"; 142 | 143 | /** 144 | * ipv6 145 | */ 146 | public final static String IPv6 = "^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$"; 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/limit/dynamic/RequestLimitItem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.limit.dynamic; 2 | 3 | import com.codingcube.simpleauth.auth.strategic.DefaultItemStrategic; 4 | import com.codingcube.simpleauth.auth.strategic.DefaultSignStrategic; 5 | import com.codingcube.simpleauth.auth.strategic.SignStrategic; 6 | import com.codingcube.simpleauth.limit.strategic.DefaultEffectiveStrategic; 7 | import com.codingcube.simpleauth.limit.strategic.DefaultLimitRejectedStratagem; 8 | import com.codingcube.simpleauth.limit.strategic.EffectiveStrategic; 9 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 10 | import com.codingcube.simpleauth.limit.util.CompleteLimit; 11 | import com.codingcube.simpleauth.limit.util.TokenLimit; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | public class RequestLimitItem { 17 | private List path; 18 | private Integer times; 19 | private Integer seconds; 20 | private Integer ban; 21 | private Class itemStrategic = DefaultItemStrategic.class; 22 | private Class signStrategic = DefaultSignStrategic.class; 23 | private Class effectiveStrategic = DefaultEffectiveStrategic.class; 24 | private Class tokenLimit = CompleteLimit.class; 25 | private Class reject = DefaultLimitRejectedStratagem.class; 26 | 27 | public RequestLimitItem(List path, Integer times, Integer seconds, Integer ban, Class itemStrategic, Class signStrategic, Class effectiveStrategic) { 28 | this.path = path; 29 | this.times = times; 30 | this.seconds = seconds; 31 | this.ban = ban; 32 | this.itemStrategic = itemStrategic; 33 | this.signStrategic = signStrategic; 34 | this.effectiveStrategic = effectiveStrategic; 35 | } 36 | 37 | public RequestLimitItem(String path, Integer times, Integer seconds, Integer ban, Class itemStrategic, Class signStrategic) { 38 | List paths = new ArrayList<>(1); 39 | paths.add(path); 40 | this.path = paths; 41 | this.times = times; 42 | this.seconds = seconds; 43 | this.ban = ban; 44 | this.itemStrategic = itemStrategic; 45 | this.signStrategic = signStrategic; 46 | } 47 | 48 | public RequestLimitItem(List path, Integer times, Integer seconds, Integer ban) { 49 | this.path = path; 50 | this.times = times; 51 | this.seconds = seconds; 52 | this.ban = ban; 53 | } 54 | 55 | public RequestLimitItem(String path, Integer times, Integer seconds, Integer ban) { 56 | List paths = new ArrayList<>(1); 57 | paths.add(path); 58 | this.path = paths; 59 | this.times = times; 60 | this.seconds = seconds; 61 | this.ban = ban; 62 | } 63 | 64 | public RequestLimitItem(List path, Integer times, Integer seconds, Integer ban, Class itemStrategic, Class signStrategic, Class effectiveStrategic, Class tokenLimit) { 65 | this.path = path; 66 | this.times = times; 67 | this.seconds = seconds; 68 | this.ban = ban; 69 | this.itemStrategic = itemStrategic; 70 | this.signStrategic = signStrategic; 71 | this.effectiveStrategic = effectiveStrategic; 72 | this.tokenLimit = tokenLimit; 73 | } 74 | 75 | public RequestLimitItem(List path, Integer times, Integer seconds, Integer ban, Class itemStrategic, Class signStrategic, Class effectiveStrategic, Class tokenLimit, Class reject) { 76 | this.path = path; 77 | this.times = times; 78 | this.seconds = seconds; 79 | this.ban = ban; 80 | this.itemStrategic = itemStrategic; 81 | this.signStrategic = signStrategic; 82 | this.effectiveStrategic = effectiveStrategic; 83 | this.tokenLimit = tokenLimit; 84 | this.reject = reject; 85 | } 86 | 87 | public Class getTokenLimit() { 88 | return tokenLimit; 89 | } 90 | 91 | public void setTokenLimit(Class tokenLimit) { 92 | this.tokenLimit = tokenLimit; 93 | } 94 | 95 | public List getPath() { 96 | return path; 97 | } 98 | 99 | public void setPath(List path) { 100 | this.path = path; 101 | } 102 | 103 | public Integer getTimes() { 104 | return times; 105 | } 106 | 107 | public void setTimes(Integer times) { 108 | this.times = times; 109 | } 110 | 111 | public Integer getSeconds() { 112 | return seconds; 113 | } 114 | 115 | public void setSeconds(Integer seconds) { 116 | this.seconds = seconds; 117 | } 118 | 119 | public Integer getBan() { 120 | return ban; 121 | } 122 | 123 | public void setBan(Integer ban) { 124 | this.ban = ban; 125 | } 126 | 127 | public Class getItemStrategic() { 128 | return itemStrategic; 129 | } 130 | 131 | public void setItemStrategic(Class itemStrategic) { 132 | this.itemStrategic = itemStrategic; 133 | } 134 | 135 | public Class getSignStrategic() { 136 | return signStrategic; 137 | } 138 | 139 | public void setSignStrategic(Class signStrategic) { 140 | this.signStrategic = signStrategic; 141 | } 142 | 143 | public Class getEffectiveStrategic() { 144 | return effectiveStrategic; 145 | } 146 | 147 | public void setEffectiveStrategic(Class effectiveStrategic) { 148 | this.effectiveStrategic = effectiveStrategic; 149 | } 150 | 151 | public Class getReject() { 152 | return reject; 153 | } 154 | 155 | public void setReject(Class reject) { 156 | this.reject = reject; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/com/codingcube/simpleauth/auth/dynamic/RequestAuthItem.java: -------------------------------------------------------------------------------- 1 | package com.codingcube.simpleauth.auth.dynamic; 2 | 3 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandler; 4 | import com.codingcube.simpleauth.auth.handler.AutoAuthHandlerChain; 5 | import com.codingcube.simpleauth.auth.strategic.AuthRejectedStratagem; 6 | import com.codingcube.simpleauth.auth.strategic.DefaultAuthRejectedStratagem; 7 | import com.codingcube.simpleauth.limit.strategic.RejectedStratagem; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * @author CodingCube
14 | * SimpleAuth Authentication Configuration item* 15 | */ 16 | public class RequestAuthItem { 17 | private List path; 18 | private String permission; 19 | private Class handlerClass; 20 | private Class handlerChainClass; 21 | private AutoAuthHandlerChain handlerChain; 22 | private AutoAuthHandler handler; 23 | private Class rejected = DefaultAuthRejectedStratagem.class; 24 | 25 | public RequestAuthItem(List path, String permission) { 26 | this.path = path; 27 | this.permission = permission; 28 | } 29 | 30 | public RequestAuthItem(String path, String permission) { 31 | List list = new ArrayList<>(1); 32 | list.add(path); 33 | this.path = list; 34 | this.permission = permission; 35 | } 36 | 37 | public RequestAuthItem(List path, String permission, Class handlerClass, Class handlerChainClass, AutoAuthHandlerChain handlerChain, AutoAuthHandler handler, Class rejected) { 38 | this.path = path; 39 | this.permission = permission; 40 | this.handlerClass = handlerClass; 41 | this.handlerChainClass = handlerChainClass; 42 | this.handlerChain = handlerChain; 43 | this.handler = handler; 44 | this.rejected = rejected; 45 | } 46 | 47 | public RequestAuthItem(Class handlerChainClass, List path, String permission) { 48 | this.path = path; 49 | this.permission = permission; 50 | this.handlerChainClass = handlerChainClass; 51 | } 52 | 53 | public RequestAuthItem(Class handlerChainClass, String path, String permission) { 54 | List list = new ArrayList<>(1); 55 | list.add(path); 56 | this.path = list; 57 | this.permission = permission; 58 | this.handlerChainClass = handlerChainClass; 59 | } 60 | 61 | 62 | public RequestAuthItem(List path, String permission, Class handlerClass) { 63 | this.path = path; 64 | this.permission = permission; 65 | this.handlerClass = handlerClass; 66 | } 67 | 68 | public RequestAuthItem(String path, String permission, Class handlerClass) { 69 | List list = new ArrayList<>(1); 70 | list.add(path); 71 | this.path = list; 72 | this.permission = permission; 73 | this.handlerClass = handlerClass; 74 | } 75 | 76 | public RequestAuthItem(List path, String permission, AutoAuthHandlerChain handlerChain) { 77 | this.path = path; 78 | this.permission = permission; 79 | this.handlerChain = handlerChain; 80 | } 81 | 82 | public RequestAuthItem(List path, String permission, AutoAuthHandler handler) { 83 | this.path = path; 84 | this.permission = permission; 85 | this.handler = handler; 86 | } 87 | 88 | public RequestAuthItem(List path, String permission, Class handlerClass, Class rejectedClass) { 89 | this.path = path; 90 | this.permission = permission; 91 | this.handlerClass = handlerClass; 92 | this.rejected = rejectedClass; 93 | } 94 | public RequestAuthItem(List path, String permission, AutoAuthHandlerChain handlerChain, Class rejectedClass) { 95 | this.path = path; 96 | this.permission = permission; 97 | this.handlerChain = handlerChain; 98 | this.rejected = rejectedClass; 99 | } 100 | 101 | public String getPermission() { 102 | return permission; 103 | } 104 | 105 | public void setPermission(String permission) { 106 | this.permission = permission; 107 | } 108 | 109 | public Class getHandlerClass() { 110 | return handlerClass; 111 | } 112 | 113 | public void setHandlerClass(Class handlerClass) { 114 | this.handlerClass = handlerClass; 115 | } 116 | 117 | public Class getHandlerChainClass() { 118 | return handlerChainClass; 119 | } 120 | 121 | public void setHandlerChainClass(Class handlerChainClass) { 122 | this.handlerChainClass = handlerChainClass; 123 | } 124 | 125 | public List getPath() { 126 | return path; 127 | } 128 | 129 | public void setPath(List path) { 130 | this.path = path; 131 | } 132 | 133 | public AutoAuthHandlerChain getHandlerChain() { 134 | return handlerChain; 135 | } 136 | 137 | public void setHandlerChain(AutoAuthHandlerChain handlerChain) { 138 | this.handlerChain = handlerChain; 139 | } 140 | 141 | public AutoAuthHandler getHandler() { 142 | return handler; 143 | } 144 | 145 | public void setHandler(AutoAuthHandler handler) { 146 | this.handler = handler; 147 | } 148 | 149 | public Class getRejected() { 150 | return rejected; 151 | } 152 | 153 | public void setRejected(Class rejected) { 154 | this.rejected = rejected; 155 | } 156 | 157 | @Override 158 | public String toString() { 159 | return "RequestAuthItem{" + "path=" + path + 160 | ", permission='" + permission + '\'' + 161 | ", handlerClass=" + handlerClass + 162 | ", handlerChainClass=" + handlerChainClass + 163 | ", handlerChain=" + handlerChain + 164 | ", handler=" + handler + 165 | '}'; 166 | } 167 | } 168 | --------------------------------------------------------------------------------