Browse Source

token登录

Lifan 2 months ago
parent
commit
9d87891893

+ 6 - 5
tofly-zhongming-gas/framework/tofly-auth/src/main/java/com/tofly/auth/controller/OauthController.java

@@ -58,11 +58,12 @@ public class OauthController {
     })
     @ToFlyAppLog(title = "登录", type = CommonConstants.LOG_LOGIN)
     public ResultRespone postAccessToken(@ApiParam(hidden = true) Principal principal, @ApiParam(hidden = true) @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
-
-        String isweb = parameters.get("isweb");
-        String username = parameters.get("username").replaceAll("_ms","");
-        if (StringUtils.isEmpty(isweb)) {
-            parameters.put("username", username+"_ms");
+        if(!"token".equals(parameters.get("loginType"))){
+            String isweb = parameters.get("isweb");
+            String username = parameters.get("username").replaceAll("_ms","");
+            if (StringUtils.isEmpty(isweb)) {
+                parameters.put("username", username+"_ms");
+            }
         }
         return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
     }

+ 26 - 0
tofly-zhongming-gas/framework/tofly-base/base-api/src/main/java/com/tofly/base/api/feign/TokenPermitService.java

@@ -0,0 +1,26 @@
+package com.tofly.base.api.feign;
+
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestParam;
+
+import java.util.Map;
+
+/**
+ * @author Administrator
+ * @date 2019/9/6  15:50
+ */
+@FeignClient(name="tokenPermitService", contextId = "TokenPermitService", url = "http://221.182.8.141:23004")
+public interface TokenPermitService {
+
+    /**
+     *
+     * @param appName
+     * @param token
+     */
+    @GetMapping("/yt/ed/do")
+    Map<String, Object> getInfo(@RequestParam("appName") String appName , @RequestHeader("token") String token);
+
+
+}

+ 156 - 14
tofly-zhongming-gas/framework/tofly-common/common-oauth/src/main/java/com/tofly/common/oauth/config/ToflyAuthenticationProvider.java

@@ -1,8 +1,10 @@
 package com.tofly.common.oauth.config;
 
 import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.tofly.base.api.entity.User;
 import com.tofly.base.api.feign.AuthTokenService;
+import com.tofly.base.api.feign.TokenPermitService;
 import com.tofly.common.core.constant.CommonConstants;
 import com.tofly.common.core.constant.SecurityConstants;
 import com.tofly.common.core.entity.ResultRespone;
@@ -28,6 +30,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
 import springfox.documentation.spring.web.json.Json;
 
 import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Objects;
@@ -42,6 +45,10 @@ public class ToflyAuthenticationProvider implements AuthenticationProvider {
     private final CacheManager cacheManager;
 
     private final AuthTokenService authTokenService;
+
+    private final TokenPermitService tokenPermitService;
+
+//    private final UserService userService;
     /**
      * 进行身份认证
      *
@@ -52,7 +59,156 @@ public class ToflyAuthenticationProvider implements AuthenticationProvider {
     @Override
     public Authentication authenticate(Authentication authentication) throws AuthenticationException {
         log.info("order 身份认证 来了。。。。。。。");
+        if("token".equals(((Map)authentication.getDetails()).get("loginType"))){
+            return authenticateByToken(authentication);
+        }
+        return authenticateByUsernamePassword(authentication);
+
+         //验证失败返回 null
+        //return null;
+
+    }
+
+    /**
+     * 这个方法 确保返回 true 即可,
+     *
+     * @param aClass
+     * @return
+     */
+    @Override
+    public boolean supports(Class<?> aClass) {
+        return true;
+    }
+
+    private Authentication authenticateByToken(Authentication authentication){
+        String token = ((Map) authentication.getDetails()).get("token").toString();
+        Map<String, Object> info = tokenPermitService.getInfo(((Map) authentication.getDetails()).get("appName").toString(), token);
+        Object o = info.get("data");
+        if(o != null){
+            String m2 = (String) o;
+            ObjectMapper mapper = new ObjectMapper();
+            Map<String, Object> map = null;
+            try {
+                map = mapper.readValue(m2, Map.class);
+            } catch (IOException e) {
+                throw new MyAuthenticationException("用户不存在");
+            }
+            String username1 = map.get("outerUsername").toString();
+            String username=username1.replaceAll("_ms","");
+            String password = token;
+            // 获取封装用户信息的对象
+            UserDetails userDetails = userDetailService.loadUserByUsername(username);
+            // 进行密码的比对
+
+            HttpServletRequest request = ((ServletRequestAttributes) Objects
+                    .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
+            log.info("ip:{}",IpUtil.getIpAddr(request));
+
+    //        if(1==1){
+    //           throw new MyAuthenticationException("aaaaaaaaaa");
+    //        }
+
+
+
+            /*log.info("界面传过来的password:{}",password);
+            log.info("数据库查询出来的password:{}",userDetails.getPassword());
+
+            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
+            log.info("用{}加密后的密码为:{}", SecurityConstants.BCRYPT+password,bCryptPasswordEncoder.encode(SecurityConstants.BCRYPT+password));
+            boolean flag = bCryptPasswordEncoder.matches(SecurityConstants.BCRYPT+password, userDetails.getPassword());*/
+
+            //return new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());
+            boolean flag = false;
+            if(userDetails != null){
+                flag = true;
+            }
+
+            if(StringUtil.isEmpty(password) && !flag){
+                flag=true;
+            }
+
+            ToflyUser toflyUser=null;
+            Cache cache = cacheManager.getCache("user_details");
+            if (cache != null && cache.get(username) != null && cache.get(username).get()!=null) {
+                toflyUser= (ToflyUser) cache.get(username).get();
+
+            }
 
+            log.info("从缓存中获取到用户信息"+ JSON.toJSONString(toflyUser));
+
+            User sysUser=new User();
+            sysUser.setId(toflyUser.getUserid());
+            Short pwdt=toflyUser.getPwderrtimes();
+            if(pwdt == null){
+                pwdt=Short.valueOf("0");
+            }
+
+            if(pwdt>=5 && !CommonConstants.SUPER_ADMIN_ULEVEL.equals(toflyUser.getUserLevel())){
+                //未登陆成功,清楚缓存,避免下次已经解锁登录时还是锁定状态
+                cache.put(username,null);
+                throw new MyAuthenticationException("账户已经被锁定,请联系管理人员");
+            }
+
+            // 校验通过
+            if (flag){
+                sysUser.setPwderrtimes(Short.valueOf("0"));
+                sysUser.setLastIp(IpUtil.getIpAddr(request));
+                SpringContextHolder.publishEvent(new UserLoginEvent(sysUser));
+                //删除token
+                Map<String, Object> params=new HashMap();
+                params.put("client_id",(String)((Map) authentication.getDetails()).get("client_id"));
+                params.put("username",authentication.getName());
+
+
+                ResultRespone resultRespone=authTokenService.removeTokenByUser(params,SecurityConstants.FROM_IN);
+                //如果密码错误次数不为0,则将缓存中的次数修改为0
+                /*if(pwdt!=0){
+                    ToflyUser toflyUser1=new ToflyUser(toflyUser.getCompanyId(),toflyUser.getCompanyName(),Short.valueOf("0"),toflyUser.getUserid(),toflyUser.getDepartmentId(),toflyUser.getUserLevel(),
+                            toflyUser.getRealName(),toflyUser.getDepartemntName(),toflyUser.getAvatar(),
+                            toflyUser.getUsername(),*//*SecurityConstants.BCRYPT+*//*toflyUser.getPassword(),
+                            true,true,
+                            true,true,toflyUser.getAuthorities());
+                    cache.put(username,toflyUser1);
+                }*/
+
+                if (username1.contains("_ms")) {
+                    ToflyUser toflyUser2 = new ToflyUser(toflyUser.getCompanyId(),toflyUser.getCompanyName(),Short.valueOf("0"), toflyUser.getUserid(), toflyUser.getDepartmentId(), toflyUser.getUserLevel(),
+                            toflyUser.getRealName(), toflyUser.getDepartemntName(), toflyUser.getAvatar(),
+                            username1,/*SecurityConstants.BCRYPT+*/toflyUser.getPassword(),
+                            true, true,
+                            true, true, toflyUser.getAuthorities());
+                    UserDetails userDetails1 = toflyUser2;
+                    //将权限信息也封装进去
+                    return new UsernamePasswordAuthenticationToken(userDetails1, password, userDetails.getAuthorities());
+                }
+
+                //将权限信息也封装进去
+                return new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());
+            }
+
+
+
+            pwdt++;
+            sysUser.setPwderrtimes(pwdt);
+            if(pwdt>=5){
+                sysUser.setLockFlag(CommonConstants.USER_LOCK_LOCKED);
+            }
+            //toflyUser.setPwderrtimes(pwdt);
+            //cache.put(username,toflyUser);
+
+
+            //cache.put(username,toflyUser1);
+            SpringContextHolder.publishEvent(new UserLoginEvent(sysUser));
+            cache.put(username,null);
+            String message=pwdt<5?"密码错误。当前密码错误次数是:"+pwdt+",密码错误5次账户将会被锁定":
+                    "账户已经被锁定,请联系管理人员";
+            throw new MyAuthenticationException(message);
+        }else{
+            throw new MyAuthenticationException("用户不存在");
+        }
+    }
+
+    private Authentication authenticateByUsernamePassword(Authentication authentication){
         // 获取用户输入的用户名和密码
         String username1 = authentication.getName();
 //        String username = authentication.getName();
@@ -170,20 +326,6 @@ public class ToflyAuthenticationProvider implements AuthenticationProvider {
         String message=pwdt<5?"密码错误。当前密码错误次数是:"+pwdt+",密码错误5次账户将会被锁定":
                 "账户已经被锁定,请联系管理人员";
         throw new MyAuthenticationException(message);
-         //验证失败返回 null
-        //return null;
-
-    }
-
-    /**
-     * 这个方法 确保返回 true 即可,
-     *
-     * @param aClass
-     * @return
-     */
-    @Override
-    public boolean supports(Class<?> aClass) {
-        return true;
     }
 
     class MyAuthenticationException extends AuthenticationException{