shiro,基於springboot,基於前後端分離,從登錄認證到鑒權,從入門到放棄

来源:https://www.cnblogs.com/tinyj/archive/2018/11/08/9926703.html
-Advertisement-
Play Games

這個demo是基於springboot項目的。 名詞介紹: ShiroShiro 主要分為 安全認證 和 介面授權 兩個部分,其中的核心組件為 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已經為我們封裝好了,我們只需要按照一定的規則去編寫響應的代碼即可… ...


這個demo是基於springboot項目的。

名詞介紹:

Shiro
Shiro 主要分為 安全認證 和 介面授權 兩個部分,其中的核心組件為 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已經為我們封裝好了,我們只需要按照一定的規則去編寫響應的代碼即可…

Subject 即表示主體,將用戶的概念理解為當前操作的主體,因為它即可以是一個通過瀏覽器請求的用戶,也可能是一個運行的程式,外部應用與 Subject 進行交互,記錄當前操作用戶。Subject 代表了當前用戶的安全操作,SecurityManager 則管理所有用戶的安全操作。

SecurityManager 即安全管理器,對所有的 Subject 進行安全管理,並通過它來提供安全管理的各種服務(認證、授權等)

Realm 充當了應用與數據安全間的 橋梁 或 連接器。當對用戶執行認證(登錄)和授權(訪問控制)驗證時,Shiro 會從應用配置的 Realm 中查找用戶及其許可權信息。

1.導入shiro依賴

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>2.8.24</version>
        </dependency>
shiro-redis為什麼要導入這個包呢?將用戶信息交給redis管理。

2.shiro配置類

package com.test.cbd.shiro;


import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Value("${spring.redis.shiro.host}")
    private String host;
    @Value("${spring.redis.shiro.port}")
    private int port;
    @Value("${spring.redis.shiro.timeout}")
    private int timeout;
    @Value("${spring.redis.shiro.password}")
    private String password;

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //註意過濾器配置順序 不能顛倒
        //配置退出 過濾器,其中的具體的退出代碼Shiro已經替我們實現了,登出後跳轉配置的loginUrl
        filterChainDefinitionMap.put("/logout", "logout");
        // 配置不會被攔截的鏈接 順序判斷,在 ShiroConfiguration 中的 shiroFilter 處配置了 /ajaxLogin=anon,意味著可以不需要認證也可以訪問
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/*.html", "anon");
        filterChainDefinitionMap.put("/ajaxLogin", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/**", "authc");
        //配置shiro預設登錄界面地址,前後端分離中登錄界面跳轉應由前端路由控制,後臺僅返回json數據
        shiroFilterFactoryBean.setLoginUrl("/unauth");
        // 登錄成功後要跳轉的鏈接
//        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授權界面;
//        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 憑證匹配器
     * (由於我們的密碼校驗交給Shiro的SimpleAuthenticationInfo進行處理了
     * )
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列演算法:這裡使用MD5演算法;
        hashedCredentialsMatcher.setHashIterations(1024);//散列的次數,比如散列兩次,相當於 md5(md5(""));
        return hashedCredentialsMatcher;
    }

    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRealm;
    }


    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        // 自定義session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        // 自定義緩存實現 使用redis
        securityManager.setCacheManager(cacheManager());
        return securityManager;
    }

    //自定義sessionManager
    @Bean
    public SessionManager sessionManager() {
        MySessionManager mySessionManager = new MySessionManager();
        mySessionManager.setSessionDAO(redisSessionDAO());
        return mySessionManager;
    }

    /**
     * 配置shiro redisManager
     * <p>
     * 使用的是shiro-redis開源插件
     *
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        redisManager.setExpire(1800);// 配置緩存過期時間
        redisManager.setTimeout(timeout);
        redisManager.setPassword(password);
        return redisManager;
    }

    /**
     * cacheManager 緩存 redis實現
     * <p>
     * 使用的是shiro-redis開源插件
     *
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao層的實現 通過redis
     * <p>
     * 使用的是shiro-redis開源插件
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * 開啟shiro aop註解支持.
     * 使用代理方式;所以需要開啟代碼支持;
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 註冊全局異常處理
     * @return
     */
    @Bean(name = "exceptionHandler")
    public HandlerExceptionResolver handlerExceptionResolver() {
        return new MyExceptionHandler();
    }

    //自動創建代理,沒有這個鑒權可能會出錯
    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        autoProxyCreator.setProxyTargetClass(true);
        return autoProxyCreator;
    }
}

3.安全認證和許可權驗證的核心,自定義Realm 

package com.test.cbd.shiro;


import com.google.gson.JsonObject;
import com.test.cbd.service.UserService;
import com.test.cbd.vo.SysPermission;
import com.test.cbd.vo.SysRole;
import com.test.cbd.vo.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//        // 許可權信息對象info,用來存放查出的用戶的所有的角色(role)及許可權(permission)
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Session session = SecurityUtils.getSubject().getSession();
        UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
        // 用戶的角色集合
        Set<String> roles = new HashSet<>();
        roles.add(user.getRoleList().get(0).getRole());
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    /*主要是用來進行身份認證的,也就是說驗證用戶輸入的賬號和密碼是否正確。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
//        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //獲取用戶的輸入的賬號.
        String username = (String) token.getPrincipal();
//        System.out.println(token.getCredentials());
        //通過username從資料庫中查找 User對象,如果找到,沒找到.
        //實際項目中,這裡可以根據實際情況做緩存,如果不做,Shiro自己也是有時間間隔機制,2分鐘內不會重覆執行該方法
        UserInfo userInfo = userInfoService.findByUsername(username);
       // Subject subject = SecurityUtils.getSubject();
        //Session session = subject.getSession();
        //session.setAttribute("role",userInfo.getRoleList());
//        System.out.println("----->>userInfo="+userInfo);
        if (userInfo == null) {
            return null;
        }
        if (userInfo.getState() == 1) { //賬戶凍結
            throw new LockedAccountException();
        }
        String credentials = userInfo.getPassword();
        System.out.println("credentials="+credentials);
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo.getUserName(), //用戶名
                credentials, //密碼
                credentialsSalt,
                getName()  //realm name
        );
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("USER_SESSION", userInfo);
        return authenticationInfo;
    }

}

4.全局異常處理器

package com.test.cbd.shiro;


import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/11.
 * 全局異常處理
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest httpServletRequest, 
            HttpServletResponse httpServletResponse, Object o, Exception ex) { ModelAndView mv
= new ModelAndView(); FastJsonJsonView view = new FastJsonJsonView(); Map<String, Object> attributes = new HashMap<String, Object>(); if (ex instanceof UnauthenticatedException) { attributes.put("code", "1000001"); attributes.put("msg", "token錯誤"); } else if (ex instanceof UnauthorizedException) { attributes.put("code", "1000002"); attributes.put("msg", "用戶無許可權"); } else { attributes.put("code", "1000003"); attributes.put("msg", ex.getMessage()); } view.setAttributesMap(attributes); mv.setView(view); return mv; } }

5.因為現在的項目大多都是前後端分離的,所以我們需要實現自己的session管理

package com.test.cbd.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;


public class MySessionManager extends DefaultWebSessionManager {

    private static final String TOKEN = "token";

    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public MySessionManager() {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader(TOKEN);
        //如果請求頭中有 token 則其值為sessionId
        if (!StringUtils.isEmpty(id)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            //否則按預設規則從cookie取sessionId
            return super.getSessionId(request, response);
        }
    }
}

6.控制器

package com.test.cbd.shiro;

import com.alibaba.fastjson.JSONObject;
import com.test.cbd.vo.UserInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

@Slf4j
@Api(value="shiro測試",description="shiro測試")
@RestController
@RequestMapping("/")
public class ShiroLoginController {

    /**
     * 登錄測試
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST)
    @ResponseBody
    public String ajaxLogin(UserInfo userInfo) {
        JSONObject jsonObject = new JSONObject();
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("msg", "登錄成功");
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密碼錯誤");
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登錄失敗,該用戶已被凍結");
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "該用戶不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    /**
     * 鑒權測試
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ResponseBody
    @RequiresRoles("guest")
    public String check() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "鑒權測試");
        return jsonObject.toString();
    }
}

常用註解
@RequiresGuest 代表無需認證即可訪問,同理的就是 /path=anon

@RequiresAuthentication 需要認證,只要登錄成功後就允許你操作

@RequiresPermissions 需要特定的許可權,沒有則拋出 AuthorizationException

@RequiresRoles 需要特定的橘色,沒有則拋出 AuthorizationException


7.以上就是shiro登陸和鑒權的主要配置和類,下麵補充一下其他信息。

①application.properties中shiro-redis相關配置:

spring.redis.shiro.host=127.0.0.1
spring.redis.shiro.port=6379
spring.redis.shiro.timeout=5000
spring.redis.shiro.password=123456

②因為數據是模擬的,所以在登陸認證的時候,並沒有通過資料庫查用戶信息,可以通過以下方式模擬加密後的密碼:

    /**
     * 生成測試用的md5加密的密碼
     * @param args
     */
    public static void main(String[] args) {
        String hashAlgorithmName = "md5";
        String credentials = "123456";//密碼
        int hashIterations = 1024;
        ByteSource credentialsSalt = ByteSource.Util.bytes("root");//賬號
        String  obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
        System.out.println(obj);
    }

上面obj的結果是b1ba853525d0f30afe59d2d005aad96c

③登陸認證的findByUsername方法,模擬到資料庫查詢用戶信息,實際是自己構造的數據,偷偷懶。

    public UserInfo findByUsername(String userName){
        SysRole admin = SysRole.builder().role("admin").build();
        List<SysPermission> list=new ArrayList<SysPermission>();
        SysPermission sysPermission=new SysPermission("read");
        SysPermission sysPermission1=new SysPermission("write");
        list.add(sysPermission);
        list.add(sysPermission1);
        admin.setPermissions(list);
        UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build();
        List<SysRole> roleList=new ArrayList<SysRole>();
        roleList.add(admin);
        root.setRoleList(roleList);
        return root;
    }

8.結果演示

輸入正確的賬號密碼時,返回信息如下:

 

 故意輸錯密碼時,返回信息如下:

 

鑒權時,如果該用戶沒有角色:

完!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 我們都知道企業建網站目的得到更多的潛在用戶,那麼現在建出企業需求的、吸引潛在用戶的網站呢? 下麵搜客建站就來和大家說說:如何製作出吸引潛在用戶的網站? 一、網站頁面的風格設計 設計網站就好比我們平時評論一個女人美不美,我們要從她的衣著打扮來判斷的,那麼同樣的,我們判斷一個網站的設計風格如何,就要從它 ...
  • 官網 http://www.fhadmin.org/D 集成安全許可權框架shiro Shiro 是一個用 Java 語言實現的框架,通過一個簡單易用的 API 提供身份驗證和授權,更安全,更可靠E 集成ehcache分散式緩存 是一個純Java的進程內緩存框架,具有快速、精幹等特點,廣泛使用的開源J ...
  • ASP.net技術支撐,learun工作流開發分享 一、工作流 根據的定義,工作流就是自動運作的業務過程部分或整體,表現為參與者對文件、信息或任務按照規程採取行動,並令其在參與者之間傳遞。簡單地說,工作流就是一系列相互銜接、自動進行的業務活動或任務。 工作流是針對工作中具有固定程式的常規活動而提出的 ...
  • 原創作品,轉載請註明出處:https://www.cnblogs.com/sunshine5683/p/9927186.html 今天在工作中遇到對一個已知的一維數組取出其最大值和最小值,分別用於參與其他運算,廢話不多說,直接上代碼。 package xhq.text; public class M ...
  • 1. 關於精度: 取整 除法取整: (除數為正)被除數為正時系統除法為向下取整,被除數為負時系統除法為向上取整。 向上取整(被除數非負,除數為正): 一般寫法(有bug): 上述寫法只適用於x為正的情況,x為0時有錯誤。 正確寫法: 或 庫函數(cmath庫) : (返回值為double) 向上取整 ...
  • 上午剛到公司,準備開始一天的摸魚之旅時突然收到了一封監控中心的郵件。 心中暗道不好,因為監控系統從來不會告訴我應用完美無 bug,其實系統挺猥瑣。 打開郵件一看,果然告知我有一個應用的線程池隊列達到閾值觸發了報警。 ...
  • 最近看了很多我周圍的同學,也都是剛開始接觸Eclipse,但是都頭疼於eclipse的漢化問題。 好在的是,Eclipse的漢化比較簡單,不用到網上自己下載漢化包,而且關於這個軟體的漢化也非常的多,所以我也就寫一下我這邊的Eclipse版本的漢化。 步驟 版本:Eclipse Photon(2018 ...
  • 恢復內容開始 在Spring IOC模塊中Bean是非常重要的。在這裡我想給大家講講關於Bean對象實例化的三種註入方式: 首先,我先講一下關於Bean對象屬性值的兩種註入方式:set註入 和 構造註入 constructor-arg:通過構造函數註入。 property:通過setter對應的方法 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...