完成JWT模块,部分proxy模块

master
sunzhiqiang23 4 years ago
parent 867d84780d
commit 3cf54ef4c2

@ -30,9 +30,9 @@
<module>shiro-springboot-cas-tmail-9005</module>
<module>shiro-springboot-cas-pac4j-taobao-9006</module>
<module>shiro-springboot-cas-pac4j-tmail-9007</module>
<module>shiro-springboot-jwt-9008</module>
<module>shiro-springboot-cas-pac4j-admin-9008</module>
<module>shiro-springboot-admin-9010</module>
<module>shiro-springboot-admin-jwt-9011</module>
<module>shiro-sprinboot-proxy</module>
</modules>
@ -50,6 +50,7 @@
<java.jwt.version>3.2.0</java.jwt.version>
<joda.time.version>2.9.9</joda.time.version>
<pagehelper.version>1.2.5</pagehelper.version>
<jwt.version>3.10.3</jwt.version>
</properties>
<dependencyManagement>
@ -59,6 +60,11 @@
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@ -180,6 +186,13 @@
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>shiro</artifactId>
<groupId>com.bjmashibing.shiro</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>shiro-sprinboot-proxy</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 跳过单元测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<!-- put your configurations here -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,17 @@
package com.bjmashibing.shiro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class ProxyApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ProxyApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ProxyApplication.class);
}
}

@ -0,0 +1,25 @@
package com.bjmashibing.shiro.proxy;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* <p> </p>
*
* @author sunzhiqiang23
* @date 2019/9/27 13:42
*/
//@Configuration
public class AnnotationProcessorConfiguration {
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
@Bean
public LogAdvisor logAdvisor(){
LogAdvisor logAdvisor = new LogAdvisor();
return logAdvisor;
}
}

@ -0,0 +1,24 @@
package com.bjmashibing.shiro.proxy;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import java.lang.reflect.Method;
/**
* <p> </p>
*
* @author sunzhiqiang23
* @date 2019/9/27 13:43
*/
public class AopLogMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getThis().getClass().getDeclaredMethod(invocation.getMethod().getName(),invocation.getMethod().getParameterTypes());
// SysLog sysLog = method.getAnnotation(SysLog.class);
// System.out.println("log: "+sysLog);
System.out.println("======");
return invocation.proceed();
}
}

@ -0,0 +1,58 @@
package com.bjmashibing.shiro.proxy;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.core.annotation.AnnotationUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* <p> </p>
*
* @author sunzhiqiang23
* @date 2019/9/27 19:33
*/
public class LogAdvisor extends StaticMethodMatcherPointcutAdvisor {
private static final Class<? extends Annotation>[] ANNOTATION_CLASSES = new Class[] {SysLog.class};
public LogAdvisor() {
setAdvice(new AopLogMethodInterceptor());
}
@Override
public boolean matches(Method method, Class targetClass) {
Method m = method;
if ( isAuthzAnnotationPresent(m) ) {
return true;
}
if ( targetClass != null) {
try {
m = targetClass.getMethod(m.getName(), m.getParameterTypes());
return isAuthzAnnotationPresent(m) || isAuthzAnnotationPresent(targetClass);
} catch (NoSuchMethodException ignored) {
}
}
return false;
}
private boolean isAuthzAnnotationPresent(Class<?> targetClazz) {
for( Class<? extends Annotation> annClass : ANNOTATION_CLASSES ) {
Annotation a = AnnotationUtils.findAnnotation(targetClazz, annClass);
if ( a != null ) {
return true;
}
}
return false;
}
private boolean isAuthzAnnotationPresent(Method method) {
for( Class<? extends Annotation> annClass : ANNOTATION_CLASSES ) {
Annotation a = AnnotationUtils.findAnnotation(method, annClass);
if ( a != null ) {
return true;
}
}
return false;
}
}

@ -0,0 +1,14 @@
package com.bjmashibing.shiro.proxy;
import java.lang.annotation.*;
/**
*
* @author sunzhiqiang23
* @date 2020-06-06 17:40
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
}

@ -0,0 +1,52 @@
package com.bjmashibing.shiro.proxy;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.reflect.misc.MethodUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
/**
*
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 201738 11:07:35
*/
@Aspect
@Component
public class SysLogAspect {
@Pointcut("@annotation(com.bjmashibing.shiro.proxy.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
//执行方法
Object result =null ;
try {
result = point.proceed();
System.out.println("=============");
//执行时长(毫秒)
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}

@ -0,0 +1,12 @@
package com.bjmashibing.shiro.service;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 17:40
*/
public interface UserService {
int add();
int select();
}

@ -0,0 +1,27 @@
package com.bjmashibing.shiro.service;
import com.bjmashibing.shiro.proxy.SysLog;
import org.springframework.stereotype.Service;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 17:41
*/
@Service
public class UserServiceImpl implements UserService{
@SysLog
@Override
public int add() {
System.out.println("添加用户");
select();
return 0;
}
@SysLog
@Override
public int select() {
System.out.println("查询用户");
return 0;
}
}

@ -0,0 +1,16 @@
# Tomcat
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 80
spring:
mvc:
static-path-pattern: /static/**
freemarker:
suffix: .html
request-context-attribute: request
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Logback configuration. See http://logback.qos.ch/manual/index.html -->
<configuration scan="true" scanPeriod="10 seconds">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="com.bjmashibing.shiro" level="debug"/>
</configuration>

@ -0,0 +1,14 @@
package com.bjmashibing.shiro;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ApplicationTests {
@Test
void contextLoads() {
}
}

@ -0,0 +1,27 @@
package com.bjmashibing.shiro;
import com.bjmashibing.shiro.service.UserService;
import com.bjmashibing.shiro.service.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 17:43
*/
@Slf4j
public class UserServiceTest extends ApplicationTests {
@Autowired
private UserService userService;
@Test
public void add(){
//userservice 真正运行的时候,是不是代理对象?
userService.add();
}
}

@ -0,0 +1,35 @@
package com.bjmashibing.shiro.proxy;
import org.junit.jupiter.api.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.NoOp;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 17:16
*/
public class Client {
@Test
public void testJdkProxy(){
LogService logService = new LogServiceImpl();
LogInvocationHandler handler = new LogInvocationHandler(logService);
LogService proxy = (LogService)handler.getProxy();
proxy.log();
}
@Test
public void testCglib() {
LogService logService = new LogServiceImpl();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(logService.getClass());
enhancer.setCallback(NoOp.INSTANCE);
//设置类加载器
enhancer.setClassLoader(logService.getClass().getClassLoader());
LogServiceImpl proxy = (LogServiceImpl)enhancer.create();
proxy.log();
}
}

@ -0,0 +1,31 @@
package com.bjmashibing.shiro.proxy;
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 15:57
*/
public class LogInvocationHandler implements InvocationHandler {
private Object target;
public LogInvocationHandler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
public Object getProxy(){
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
}
}

@ -0,0 +1,11 @@
package com.bjmashibing.shiro.proxy;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 15:05
*/
public interface LogService {
void log();
}

@ -0,0 +1,15 @@
package com.bjmashibing.shiro.proxy;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-06 15:05
*/
public class LogServiceImpl implements LogService {
@Override
public void log() {
System.out.println("记录日志");
}
}

@ -0,0 +1,44 @@
package com.bjmashibing.shiro.proxy;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* <br>
* JVM
* -XX:MetaspaceSize=8m -XX:MaxMetaspaceSize=12m
* MetaspaceMetaspace
**/
public class MataspaceOOMTest {
static class OOMTest{
}
public static void main(String[] args) {
int i = 0; //模拟计数多少次以后发生异常
try {
while(true){
i++;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(OOMTest.class);
enhancer.setUseCache(false);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
return methodProxy.invoke(o,args);
}
});
enhancer.create();
}
} catch (Throwable throwable) {
System.out.println("*******多少次后发生了异常:" + i);
throwable.printStackTrace();
}
}
}

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>shiro</artifactId>
<groupId>com.bjmashibing.shiro</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>shiro-springboot-admin-jwt-9011</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 跳过单元测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<!-- put your configurations here -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,32 @@
package com.bjmashibing.shiro.framework.util;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
/**
* Base64
* @author
* @date 2018/11/05 23:10
*/
public class Base64ConvertUtil {
/**
*
* @param str
* @return java.lang.String
*/
public static String encode(String str) throws UnsupportedEncodingException {
byte[] encodeBytes = Base64.getEncoder().encode(str.getBytes("utf-8"));
return new String(encodeBytes);
}
/**
*
* @param str
* @return java.lang.String
*/
public static String decode(String str) throws UnsupportedEncodingException {
byte[] decodeBytes = Base64.getDecoder().decode(str.getBytes("utf-8"));
return new String(decodeBytes);
}
}

@ -0,0 +1,91 @@
package com.bjmashibing.shiro.framework.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.util.Date;
/**
* JWT
* @author sunzhiqiang23
* @date 2020/05/29 21:23
*/
@Slf4j
@Component
public class JwtUtil {
/**
*
*/
private static String accessTokenExpireTime ="300";
/**
* JWT(Base64)
*/
private static String encryptJWTKey="a30ade645272536288ccae58570738ee";
public static final String CLAIM = "account";
/**
* JWT
* @param token Token
* @return boolean
*/
public static boolean verify(String token) {
try {
String secret = getClaim(token, CLAIM) + Base64ConvertUtil.decode(encryptJWTKey);
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("认证解密异常:" + e.getMessage());
}
}
/**
* Token
* @param token
* @param claim
* @return java.lang.String
*/
public static String getClaim(String token, String claim) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim(claim).asString();
} catch (JWTDecodeException e) {
throw new RuntimeException("解密异常:" + e.getMessage());
}
}
/**
*
* @param account
* @return java.lang.String Token
*/
public static String sign(String account) {
try {
// 帐号加JWT私钥加密
String secret = account + Base64ConvertUtil.decode(encryptJWTKey);
// 此处过期时间是以毫秒为单位所以乘以1000
Date date = new Date(System.currentTimeMillis() + Long.parseLong(accessTokenExpireTime) * 1000);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带account帐号信息
return JWT.create()
.withClaim("account", account)
.withClaim("currentTimeMillis", String.valueOf(System.currentTimeMillis()))
.withExpiresAt(date)
.sign(algorithm);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("加密异常:" + e.getMessage());
}
}
}

@ -0,0 +1,47 @@
package com.bjmashibing.shiro.framework.util;
import java.util.HashMap;
/**
*
*
* @author
* @date 20191219 4:59:27
*/
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public R() {
put("code", 0);
}
public static R error() {
return error(500, "未知异常,请联系管理员");
}
public static R error(String info) {
return error(500, info);
}
public static R error(int code, String info) {
R r = new R();
r.put("code", code);
r.put("info", info);
return r;
}
public static R ok(String info) {
R r = new R();
r.put("info", info);
return r;
}
public static R ok() {
return new R();
}
@Override
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}

@ -0,0 +1,39 @@
package com.bjmashibing.shiro.framework.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* <p></p>
*
* @author sunzhiqiang23
* @date 2020-06-01 21:15
*/
class JwtUtilTest {
@Test
void verify() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50VGltZU1pbGxpcyI6IjE1OTE0NDcyOTU4NTMiLCJleHAiOjE1OTE0NDc1OTUsImFjY291bnQiOiJzeXN0ZW0ifQ._y17zAMGtwGNDTmLNMmaEEGP99zMvognQqwla87174s";
String account = JwtUtil.getClaim(token, "account");
boolean system = JwtUtil.verify(token);
System.out.println(system);
}
@Test
void getClaim() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50VGltZU1pbGxpcyI6IjE1OTE0NDcyOTU4NTMiLCJleHAiOjE1OTE0NDc1OTUsImFjY291bnQiOiJzeXN0ZW0ifQ._y17zAMGtwGNDTmLNMmaEEGP99zMvognQqwla87174s";
String claim = "account";
String account = JwtUtil.getClaim(token, claim);
System.out.println(account);
}
@Test
void sign() {
String account = "system";
String sign = JwtUtil.sign(account);
System.out.println(sign);
}
}

Binary file not shown.
Loading…
Cancel
Save