You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dolphinscheduler.apache.org by GitBox <gi...@apache.org> on 2019/12/20 15:10:25 UTC

[GitHub] [incubator-dolphinscheduler] Technoboy- commented on a change in pull request #1502: Login verification supports jwt mode

Technoboy- commented on a change in pull request #1502: Login verification supports jwt mode
URL: https://github.com/apache/incubator-dolphinscheduler/pull/1502#discussion_r360413345
 
 

 ##########
 File path: dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/JsonWebTokenRSAAuthenticator.java
 ##########
 @@ -0,0 +1,359 @@
+/*
+ * 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.dolphinscheduler.api.security;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jws;
+import io.jsonwebtoken.Jwts;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.dolphinscheduler.api.enums.Status;
+import org.apache.dolphinscheduler.api.service.JsonWebTokenService;
+import org.apache.dolphinscheduler.api.service.TenantService;
+import org.apache.dolphinscheduler.api.service.UsersService;
+import org.apache.dolphinscheduler.api.utils.Result;
+import org.apache.dolphinscheduler.common.Constants;
+import org.apache.dolphinscheduler.dao.entity.Tenant;
+import org.apache.dolphinscheduler.dao.entity.User;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import sun.security.util.DerInputStream;
+import sun.security.util.DerValue;
+import javax.servlet.http.HttpServletRequest;
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.RSAPrivateCrtKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * rsa-based jwt authentication (only support rsa format key)
+ */
+public class JsonWebTokenRSAAuthenticator implements Authenticator, InitializingBean {
+    private static final Logger logger = LoggerFactory.getLogger(JsonWebTokenRSAAuthenticator.class);
+
+    @Value("${security.authentication.jwt.public-key-file}")
+    private String publicKeyFile;
+
+    @Value("${security.authentication.jwt.private-key-file:}")
+    private String privateKeyFile;
+
+    @Value("${security.authentication.jwt.generate-token-mode:local}")
+    private String generateTokenMode;
+
+    @Value("${security.authentication.jwt.expire.minutes:1440}")
+    private int expireTimeOfMinutes;
+
+    @Value("${security.authentication.jwt.remote-token-url:}")
+    private String remoteTokenUrl;
+
+    @Value("${security.authentication.jwt.remote-token-regex:}")
+    private String remoteTokenRegex;
+
+    @Value("${security.authentication.jwt.remote.default.tenant.code:}")
+    private String defaultRemoteTenantCode;
+    private int defaultRemoteTenantId;
+
+    @Value("${security.authentication.jwt.remote.default.queue:}")
+    private String defaultRemoteQueue;
+
+    @Value("${security.authentication.jwt.required-name-claim:name}")
+    private String requiredNameClaim;
+
+    @Value("${security.authentication.jwt.required-email-claim:email}")
+    private String requiredEmailClaim;
+
+    @Autowired
+    private UsersService userService;
+    @Autowired
+    private TenantService tenantService;
+    @Autowired
+    private JsonWebTokenService jwtService;
+
+    private PublicKey publicKey;
+    private PrivateKey privateKey;
+
+    @Override
+    public void afterPropertiesSet() throws Exception {
+        if (StringUtils.isBlank(publicKeyFile)) {
+            throw new FileNotFoundException("Pem file can't empty. path=" + publicKeyFile);
+        }
+
+        String publicKeyContent = readPemKeyContent(publicKeyFile);
+        publicKey = getPublicKey(publicKeyContent);
+
+        if (StringUtils.isNotBlank(privateKeyFile)) {
+            String privateKeyContent = readPemKeyContent(privateKeyFile);
+            privateKey = getPrivateKey(privateKeyContent);
+        }
+
+        if (StringUtils.isNotBlank(defaultRemoteTenantCode)) {
+            Map<String, Object> result = tenantService.queryTenantList(defaultRemoteTenantCode);
+            Status status = (Status) result.get(Constants.STATUS);
+            if (status == Status.SUCCESS) {
+                @SuppressWarnings("unchecked")
+                List<Tenant> datalist = (List<Tenant>) result.get(Constants.DATA_LIST);
+                defaultRemoteTenantId = datalist.get(0).getId();
+            } else {
+                throw new Exception(String.format("tenant %s don't exist. please check #security.authentication.default.tenant.code"
+                        , defaultRemoteTenantCode));
+            }
+        }
+    }
+
+    @Override
+    public Result<Map<String, String>> authenticate(String username, String password, String extra) {
+        Result<Map<String, String>> result = new Result<>();
+        try  {
+            Result<String> tokenResult;
+            switch (generateTokenMode) {
+                case "local":
+                    tokenResult = getTokenFromLocal(username, password);
+                    break;
+                case "remote":
+                    tokenResult = getTokenFromRemote(username, password);
+                    break;
+                default:
+                    throw new Exception("token mode don't exist. check #security.authentication.jwt.generate-token-mode");
+            }
+            if (tokenResult.getCode() != Status.SUCCESS.getCode()) {
+                result.setCode(tokenResult.getCode());
+                result.setMsg(tokenResult.getMsg());
+                return result;
+            }
+
+            User user = getUserByToken(tokenResult.getData(), true);
+            if (user == null) {
+                result.setCode(Status.CREATE_USER_ERROR.getCode());
+                result.setMsg(Status.CREATE_USER_ERROR.getMsg());
+                return result;
+            }
+            result.setData(Collections.singletonMap(Constants.USER_AUTH, tokenResult.getData()));
+            result.setCode(Status.SUCCESS.getCode());
+            result.setMsg(Status.LOGIN_SUCCESS.getMsg());
+        } catch (Exception e) {
+            logger.error(e.toString());
+            e.printStackTrace();
 
 Review comment:
   delete this line

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services