diff --git a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/config/SurenessConfiguration.java b/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/config/SurenessConfiguration.java deleted file mode 100644 index b2a06078aaa..00000000000 --- a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/config/SurenessConfiguration.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hertzbeat.templatehub.sureness.config; - -import com.usthe.sureness.matcher.DefaultPathRoleMatcher; -import com.usthe.sureness.matcher.PathTreeProvider; -import com.usthe.sureness.matcher.TreePathRoleMatcher; -import com.usthe.sureness.mgt.SurenessSecurityManager; -import com.usthe.sureness.processor.DefaultProcessorManager; -import com.usthe.sureness.processor.Processor; -import com.usthe.sureness.processor.ProcessorManager; -import com.usthe.sureness.processor.support.JwtProcessor; -import com.usthe.sureness.processor.support.NoneProcessor; -import com.usthe.sureness.processor.support.PasswordProcessor; -import com.usthe.sureness.provider.SurenessAccountProvider; -import com.usthe.sureness.provider.annotation.AnnotationPathTreeProvider; -import com.usthe.sureness.provider.ducument.DocumentPathTreeProvider; -import com.usthe.sureness.subject.SubjectFactory; -import com.usthe.sureness.subject.SurenessSubjectFactory; -import com.usthe.sureness.subject.creater.BasicSubjectServletCreator; -import com.usthe.sureness.subject.creater.JwtSubjectServletCreator; -import com.usthe.sureness.subject.creater.NoneSubjectServletCreator; -import com.usthe.sureness.util.JsonWebTokenUtil; -import org.apache.hertzbeat.templatehub.sureness.processor.CustomTokenProcessor; -import org.apache.hertzbeat.templatehub.sureness.subject.CustomPasswdSubjectCreator; -import org.apache.hertzbeat.templatehub.sureness.subject.CustomTokenSubjectCreator; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * sureness config - * @author tomsun28 - * @date 22:40 2020-03-02 - */ -@Configuration -public class SurenessConfiguration { - - /** - * jwt secret key - */ - private static final String TOM_SECRET_KEY = "?::4s9ssf2sf4sed45pf):" + - "RnLN7XNn4wARoQXizIv6MHUsIV+EFfiMw/x7R0ntu4aWr/CWuApcFaj" + - "CyaFv0bwq2Eik0jdrKUtsA6bx3sDJeFV643R+YYzGMRIqcBIp6AKA98" + - "GM2RIqcBIp6-?::4390fsf4sdl6opf)4ZI:tdQMtcQQ14pkOAQdQ546"; - - @Bean - ProcessorManager processorManager(SurenessAccountProvider accountProvider) { - // process init - List processorList = new LinkedList<>(); - // use default none processor - NoneProcessor noneProcessor = new NoneProcessor(); - processorList.add(noneProcessor); - // use default jwt processor - JwtProcessor jwtProcessor = new JwtProcessor(); - processorList.add(jwtProcessor); - // use default basic auth processor - PasswordProcessor passwordProcessor = new PasswordProcessor(); - passwordProcessor.setAccountProvider(accountProvider); - processorList.add(passwordProcessor); - - // use custom token processor - CustomTokenProcessor customTokenProcessor = new CustomTokenProcessor(); - customTokenProcessor.setAccountProvider(accountProvider); - processorList.add(customTokenProcessor); - return new DefaultProcessorManager(processorList); - } - - /** - * @param databasePathTreeProvider the path tree resource load from database - */ - @Bean - TreePathRoleMatcher pathRoleMatcher(PathTreeProvider databasePathTreeProvider) { - // the path tree resource load from document - sureness.yml - PathTreeProvider documentPathTreeProvider = new DocumentPathTreeProvider(); - // the path tree resource load form annotation - @RequiresRoles @WithoutAuth - AnnotationPathTreeProvider annotationPathTreeProvider = new AnnotationPathTreeProvider(); - annotationPathTreeProvider.setScanPackages(Collections.singletonList("org.apache.hertzbeat.templatehub.controller")); - // pathRoleMatcher init - DefaultPathRoleMatcher pathRoleMatcher = new DefaultPathRoleMatcher(); - pathRoleMatcher.setPathTreeProviderList(Arrays.asList( - documentPathTreeProvider, - annotationPathTreeProvider, - databasePathTreeProvider)); - pathRoleMatcher.buildTree(); - return pathRoleMatcher; - } - - @Bean - SubjectFactory subjectFactory() { - // SubjectFactory init - SubjectFactory subjectFactory = new SurenessSubjectFactory(); - subjectFactory.registerSubjectCreator(Arrays.asList( - // attention! must add noSubjectCreator first - new NoneSubjectServletCreator(), - // use default basic auth subject creator - new BasicSubjectServletCreator(), - // use default jwt subject creator - new JwtSubjectServletCreator(), - // use custom password creator - new CustomPasswdSubjectCreator(), - // use custom token creator - new CustomTokenSubjectCreator() - )); - return subjectFactory; - } - - @Bean - SurenessSecurityManager securityManager(ProcessorManager processorManager, - TreePathRoleMatcher pathRoleMatcher, SubjectFactory subjectFactory) { - JsonWebTokenUtil.setDefaultSecretKey(TOM_SECRET_KEY); - // surenessSecurityManager init - SurenessSecurityManager securityManager = SurenessSecurityManager.getInstance(); - securityManager.setPathRoleMatcher(pathRoleMatcher); - securityManager.setSubjectFactory(subjectFactory); - securityManager.setProcessorManager(processorManager); - return securityManager; - } - -} diff --git a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/processor/CustomTokenProcessor.java b/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/processor/CustomTokenProcessor.java deleted file mode 100644 index 705e27d85ee..00000000000 --- a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/processor/CustomTokenProcessor.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hertzbeat.templatehub.sureness.processor; - -import com.usthe.sureness.processor.BaseProcessor; -import com.usthe.sureness.processor.exception.IncorrectCredentialsException; -import com.usthe.sureness.processor.exception.SurenessAuthenticationException; -import com.usthe.sureness.processor.exception.SurenessAuthorizationException; -import com.usthe.sureness.processor.exception.UnauthorizedException; -import com.usthe.sureness.provider.SurenessAccount; -import com.usthe.sureness.provider.SurenessAccountProvider; -import com.usthe.sureness.subject.Subject; -import org.apache.hertzbeat.templatehub.controller.TokenStorage; -import org.apache.hertzbeat.templatehub.sureness.subject.CustomTokenSubject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.UUID; - -/** - * custom token processor, support CustomTokenSubject - * when token Expired and can refresh, return refresh token value - * - * @author tomsun28 - * @date 2020-12-03 20:37 - */ -public class CustomTokenProcessor extends BaseProcessor { - - private static final Logger logger = LoggerFactory.getLogger(CustomTokenProcessor.class); - private static final String TOKEN_SPLIT = "--"; - private static final int START_TIME_INDEX = 1; - private static final int PERIOD_TIME_INDEX = 2; - private static final int DOUBLE_TIME = 2; - - private SurenessAccountProvider accountProvider; - - @Override - public boolean canSupportSubjectClass(Class var) { - return var == CustomTokenSubject.class; - } - - @Override - public Class getSupportSubjectClass() { - return CustomTokenSubject.class; - } - - @Override - @SuppressWarnings("unchecked") - public Subject authenticated(Subject var) throws SurenessAuthenticationException { - String token = (String) var.getCredential(); - String[] tokenArr = token.split(TOKEN_SPLIT); - if (TokenStorage.matchToken(tokenArr[0], token)) { - // auth passed - String appId = tokenArr[0]; - SurenessAccount account = accountProvider.loadAccount(appId); - // attention: need to set subject own roles from account - var.setPrincipal(appId); - var.setOwnRoles(account.getOwnRoles()); - return var; - - } else { - // token expired or not exist, if token can refresh, refresh it - // if expired time is not longer than refreshPeriodTime/2 , it can refresh - if (Long.parseLong(tokenArr[START_TIME_INDEX]) + (Long.parseLong(tokenArr[PERIOD_TIME_INDEX]) * DOUBLE_TIME) - >= System.currentTimeMillis()) { - long refreshPeriodTime = 36000L; - String refreshToken = tokenArr[0] + TOKEN_SPLIT + System.currentTimeMillis() - + TOKEN_SPLIT + refreshPeriodTime - + TOKEN_SPLIT + UUID.randomUUID().toString().replace("-", ""); - TokenStorage.addToken(tokenArr[0], refreshToken); - throw new RefreshExpiredTokenException(refreshToken); - } else if (Long.parseLong(tokenArr[START_TIME_INDEX]) + Long.parseLong(tokenArr[PERIOD_TIME_INDEX]) - <= System.currentTimeMillis()) { - if (logger.isDebugEnabled()) { - logger.debug("CustomTokenProcessor authenticated expired"); - } - throw new IncorrectCredentialsException("the token authenticated expired, please get new one"); - } else { - if (logger.isDebugEnabled()) { - logger.debug("CustomTokenProcessor authenticated fail"); - } - throw new IncorrectCredentialsException("the token authenticated error"); - } - } - } - - @SuppressWarnings("unchecked") - @Override - public void authorized(Subject var) throws SurenessAuthorizationException { - List ownRoles = (List) var.getOwnRoles(); - List supportRoles = (List) var.getSupportRoles(); - // if null, note that not config this resource - if (supportRoles == null) { - return; - } - // if config, ownRole must contain the supportRole item - if (ownRoles != null && supportRoles.stream().anyMatch(ownRoles::contains)) { - return; - } - throw new UnauthorizedException("custom authorized: do not have the role to access resource"); - } - - public void setAccountProvider(SurenessAccountProvider accountProvider) { - this.accountProvider = accountProvider; - } -} diff --git a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomPasswdSubjectCreator.java b/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomPasswdSubjectCreator.java deleted file mode 100644 index 8536e1af0a9..00000000000 --- a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomPasswdSubjectCreator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hertzbeat.templatehub.sureness.subject; - -import com.usthe.sureness.subject.Subject; -import com.usthe.sureness.subject.SubjectCreate; -import com.usthe.sureness.subject.support.PasswordSubject; - -import javax.servlet.http.HttpServletRequest; - -/** - * custom subject creator - * A custom creator is demonstrated here - * In addition to the basic auth method, we may obtain our account password from other places for authentication. - * eg: username and password in header - * header { - * "username": "userTom", - * "password": "123456" - * } - * Here we define a creator to create PasswordSubject from this request header like above. - * @author tomsun28 - * @date 22:59 2020-03-02 - */ -public class CustomPasswdSubjectCreator implements SubjectCreate { - - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - - @Override - public boolean canSupportSubject(Object context) { - // define which request can be access - if (context instanceof HttpServletRequest) { - String username = ((HttpServletRequest)context).getHeader(USERNAME); - String password = ((HttpServletRequest)context).getHeader(PASSWORD); - return username != null && password != null; - } else { - return false; - } - } - - @Override - public Subject createSubject(Object context) { - // create PasswordSubject from request - String username = ((HttpServletRequest)context).getHeader(USERNAME); - String password = ((HttpServletRequest)context).getHeader(PASSWORD); - - String remoteHost = ((HttpServletRequest) context).getRemoteHost(); - String requestUri = ((HttpServletRequest) context).getRequestURI(); - String requestType = ((HttpServletRequest) context).getMethod(); - String targetUri = requestUri.concat("===").concat(requestType).toLowerCase(); - return PasswordSubject.builder(username, password) - .setRemoteHost(remoteHost) - .setTargetResource(targetUri) - .build(); - } -} diff --git a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubject.java b/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubject.java deleted file mode 100644 index e0a10a13718..00000000000 --- a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubject.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hertzbeat.templatehub.sureness.subject; - -import com.usthe.sureness.subject.PrincipalMap; -import com.usthe.sureness.subject.Subject; - -import java.util.List; - -/** - * custom define token subject - * @author tomsun28 - * @date 2020-12-03 22:08 - */ -public class CustomTokenSubject implements Subject { - - private static final long serialVersionUID = 1L; - - /** user identifier **/ - private String appId; - - /** token : admin--issueTime--refreshPeriodTime--uuid **/ - private String token; - - /** remote ip **/ - private String remoteHost; - - /** remote device **/ - private String userAgent; - - /** the roles which this user owned **/ - private List ownRoles; - - /** the uri resource which this user want access **/ - private String targetUri; - - /** the Roles which can access this resource above-targetUri **/ - private List supportRoles; - - private CustomTokenSubject(Builder builder) { - this.appId = builder.appId; - this.token = builder.token; - this.remoteHost = builder.remoteHost; - this.userAgent = builder.userAgent; - this.ownRoles = builder.ownRoles; - this.supportRoles = builder.supportRoles; - this.targetUri = builder.targetUri; - } - - @Override - public Object getPrincipal() { - return this.appId; - } - - @Override - public void setPrincipal(Object var1) { - this.appId = (String) appId; - } - - @Override - public PrincipalMap getPrincipalMap() { - return null; - } - - @Override - public void setPrincipalMap(PrincipalMap var1) { - - } - - @Override - public Object getCredential() { - return this.token; - } - - @Override - public void setCredential(Object var1) { - this.token = (String) token; - } - - @Override - public Object getOwnRoles() { - return this.ownRoles; - } - - @SuppressWarnings("unchecked") - @Override - public void setOwnRoles(Object var1) { - this.ownRoles = (List) var1; - } - - @Override - public Object getTargetResource() { - return this.targetUri; - } - - @Override - public void setTargetResource(Object var1) { - this.targetUri = (String) targetUri; - } - - @Override - public Object getSupportRoles() { - return this.supportRoles; - } - - @SuppressWarnings("unchecked") - @Override - public void setSupportRoles(Object var1) { - this.supportRoles = (List) var1; - } - - public String getRemoteHost() { - return remoteHost; - } - - public String getUserAgent() { - return userAgent; - } - - public static Builder builder(String token) { - return new Builder(token); - } - - public static Builder builder(Subject subject) { - return new Builder(subject); - } - - public static class Builder { - - private String appId; - private String token; - private String remoteHost; - private String userAgent; - private List ownRoles; - private String targetUri; - private List supportRoles; - - public Builder(String token) { - this.token = token; - } - - @SuppressWarnings("unchecked") - public Builder(Subject subject) { - this.appId = String.valueOf(subject.getPrincipal()); - this.token = String.valueOf(subject.getCredential()); - this.ownRoles = (List) subject.getOwnRoles(); - this.targetUri = String.valueOf(subject.getTargetResource()); - this.supportRoles = (List) subject.getSupportRoles(); - } - - public Builder setPrincipal(String appId) { - this.appId = appId; - return this; - } - - public Builder setCredentials(String token) { - this.token = token; - return this; - } - - public Builder setTargetResource(String targetUri) { - this.targetUri = targetUri; - return this; - } - - public Builder setOwnRoles(List ownRoles) { - this.ownRoles = ownRoles; - return this; - } - - public Builder setSupportRoles(List supportRoles) { - this.supportRoles = supportRoles; - return this; - } - - public Builder setRemoteHost(String remoteHost) { - this.remoteHost = remoteHost; - return this; - } - - public Builder setUserAgent(String userAgent) { - this.userAgent = userAgent; - return this; - } - - public CustomTokenSubject build() { - return new CustomTokenSubject(this); - } - - } -} diff --git a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubjectCreator.java b/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubjectCreator.java deleted file mode 100644 index a3d43a1bc47..00000000000 --- a/template-marketplace/hertzbeat-template-hub/src/main/java/org/apache/hertzbeat/templatehub/sureness/subject/CustomTokenSubjectCreator.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hertzbeat.templatehub.sureness.subject; - -import com.usthe.sureness.subject.Subject; -import com.usthe.sureness.subject.SubjectCreate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; - -/** - * custom token creator, get token from http request header - {"Token" : "tokenValue"} - * tokenValue is : admin--issueTime--refreshPeriodTime--uuid - * @author tomsun28 - * @date 2020-12-03 22:08 - */ -//SubjectCreat根据request请求体创造Subject,不同的认证鉴权处理器Processor处理其所支持的Subject -public class CustomTokenSubjectCreator implements SubjectCreate { - - private static final Logger logger = LoggerFactory.getLogger(CustomTokenSubjectCreator.class); - - private static final String HEADER_TOKEN = "Token"; - private static final String TOKEN_SPLIT = "--"; - private static final int TOKEN_SPLIT_SIZE = 4; - - @Override - public boolean canSupportSubject(Object context) { - // support token - // {"Token" : "tokenValue"} - if (context instanceof HttpServletRequest) { - String authorization = ((HttpServletRequest)context).getHeader(HEADER_TOKEN); - return authorization != null && authorization.split(TOKEN_SPLIT).length == TOKEN_SPLIT_SIZE; - } - return false; - } - - @Override - public Subject createSubject(Object context) { - String authorization = ((HttpServletRequest)context).getHeader(HEADER_TOKEN); - String remoteHost = ((HttpServletRequest) context).getRemoteHost(); - String requestUri = ((HttpServletRequest) context).getRequestURI(); - String requestType = ((HttpServletRequest) context).getMethod(); - String targetUri = requestUri.concat("===").concat(requestType.toLowerCase()); - return CustomTokenSubject.builder(authorization) - .setRemoteHost(remoteHost) - .setTargetResource(targetUri) - .build(); - } -}