<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                在一些環境中,可能需要把 Web 應用做成無狀態的,即服務器端無狀態,就是說服務器端不會存儲像會話這種東西,而是每次請求時帶上相應的用戶名進行登錄。如一些 REST 風格的 API,如果不使用 OAuth2 協議,就可以使用如 REST+HMAC 認證進行訪問。HMAC(Hash-based Message Authentication Code):基于散列的消息認證碼,使用一個密鑰和一個消息作為輸入,生成它們的消息摘要。注意該密鑰只有客戶端和服務端知道,其他第三方是不知道的。訪問時使用該消息摘要進行傳播,服務端然后對該消息摘要進行驗證。如果只傳遞用戶名 + 密碼的消息摘要,一旦被別人捕獲可能會重復使用該摘要進行認證。解決辦法如: 1. 每次客戶端申請一個 Token,然后使用該 Token 進行加密,而該 Token 是一次性的,即只能用一次;有點類似于 OAuth2 的 Token 機制,但是簡單些; 2. 客戶端每次生成一個唯一的 Token,然后使用該 Token 加密,這樣服務器端記錄下這些 Token,如果之前用過就認為是非法請求。 為了簡單,本文直接對請求的數據(即全部請求的參數)生成消息摘要,即無法篡改數據,但是可能被別人竊取而能多次調用。解決辦法如上所示。 ## 20.1 服務器端 對于服務器端,不生成會話,而是每次請求時帶上用戶身份進行認證。 ### 服務控制器 [**]( "復制到剪切板")[**]( "添加到筆記")@RestController public class ServiceController { @RequestMapping("/hello") public String hello1(String[] param1, String param2) { return "hello" + param1[0] + param1[1] + param2; } }&nbsp; 當訪問 / hello 服務時,需要傳入 param1、param2 兩個請求參數。 ### 加密工具類 com.github.zhangkaitao.shiro.chapter20.codec.HmacSHA256Utils: [**]( "復制到剪切板")[**]( "添加到筆記")//使用指定的密碼對內容生成消息摘要(散列值) public static String digest(String key, String content); //使用指定的密碼對整個Map的內容生成消息摘要(散列值) public static String digest(String key, Map<String, ?> map)&nbsp; 對 Map 生成消息摘要主要用于對客戶端 / 服務器端來回傳遞的參數生成消息摘要。 ### Subject 工廠 [**]( "復制到剪切板")[**]( "添加到筆記")public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory { public Subject createSubject(SubjectContext context) { //不創建session context.setSessionCreationEnabled(false); return super.createSubject(context); } }&nbsp; 通過調用 context.setSessionCreationEnabled(false) 表示不創建會話;如果之后調用 Subject.getSession() 將拋出 DisabledSessionException 異常。 ### StatelessAuthcFilter 類似于 FormAuthenticationFilter,但是根據當前請求上下文信息每次請求時都要登錄的認證過濾器。 [**]( "復制到剪切板")[**]( "添加到筆記")public class StatelessAuthcFilter extends AccessControlFilter { protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return false; } protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { //1、客戶端生成的消息摘要 String clientDigest = request.getParameter(Constants.PARAM_DIGEST); //2、客戶端傳入的用戶身份 String username = request.getParameter(Constants.PARAM_USERNAME); //3、客戶端請求的參數列表 Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap()); params.remove(Constants.PARAM_DIGEST); //4、生成無狀態Token StatelessToken token = new StatelessToken(username, params, clientDigest); try { //5、委托給Realm進行登錄 getSubject(request, response).login(token); } catch (Exception e) { e.printStackTrace(); onLoginFail(response); //6、登錄失敗 return false; } return true; } //登錄失敗時默認返回401狀態碼 private void onLoginFail(ServletResponse response) throws IOException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.getWriter().write("login error"); } } &nbsp; 獲取客戶端傳入的用戶名、請求參數、消息摘要,生成 StatelessToken;然后交給相應的 Realm 進行認證。 ### StatelessToken [**]( "復制到剪切板")[**]( "添加到筆記")public class StatelessToken implements AuthenticationToken { private String username; private Map<String, ?> params; private String clientDigest; //省略部分代碼 public Object getPrincipal() { return username;} public Object getCredentials() { return clientDigest;} }&nbsp; 用戶身份即用戶名;憑證即客戶端傳入的消息摘要。 ### StatelessRealm 用于認證的 Realm。 [**]( "復制到剪切板")[**]( "添加到筆記")public class StatelessRealm extends AuthorizingRealm { public boolean supports(AuthenticationToken token) { //僅支持StatelessToken類型的Token return token instanceof StatelessToken; } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //根據用戶名查找角色,請根據需求實現 String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRole("admin"); return authorizationInfo; } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { StatelessToken statelessToken = (StatelessToken) token; String username = statelessToken.getUsername(); String key = getKey(username);//根據用戶名獲取密鑰(和客戶端的一樣) //在服務器端生成客戶端參數消息摘要 String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams()); //然后進行客戶端消息摘要和服務器端消息摘要的匹配 return new SimpleAuthenticationInfo( username, serverDigest, getName()); } private String getKey(String username) {//得到密鑰,此處硬編碼一個 if("admin".equals(username)) { return "dadadswdewq2ewdwqdwadsadasd"; } return null; } }&nbsp; 此處首先根據客戶端傳入的用戶名獲取相應的密鑰,然后使用密鑰對請求參數生成服務器端的消息摘要;然后與客戶端的消息摘要進行匹配;如果匹配說明是合法客戶端傳入的;否則是非法的。這種方式是有漏洞的,一旦別人獲取到該請求,可以重復請求;可以考慮之前介紹的解決方案。 ### Spring 配置——spring-config-shiro.xml [**]( "復制到剪切板")[**]( "添加到筆記")\<!-- Realm實現 --\> \<bean id="statelessRealm" class="com.github.zhangkaitao.shiro.chapter20.realm.StatelessRealm"\> \<property name="cachingEnabled" value="false"/\> \</bean\> \<!-- Subject工廠 --\> \<bean id="subjectFactory" class="com.github.zhangkaitao.shiro.chapter20.mgt.StatelessDefaultSubjectFactory"/\> \<!-- 會話管理器 --\> \<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager"\> \<property name="sessionValidationSchedulerEnabled" value="false"/\> \</bean\> \<!-- 安全管理器 --\> \<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"\> \<property name="realm" ref="statelessRealm"/\> \<property name="subjectDAO.sessionStorageEvaluator.sessionStorageEnabled" value="false"/\> \<property name="subjectFactory" ref="subjectFactory"/\> \<property name="sessionManager" ref="sessionManager"/\> \</bean\> \<!-- 相當于調用SecurityUtils.setSecurityManager(securityManager) --\> \<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"\> \<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/\> \<property name="arguments" ref="securityManager"/\> \</bean\>&nbsp; sessionManager 通過 sessionValidationSchedulerEnabled 禁用掉會話調度器,因為我們禁用掉了會話,所以沒必要再定期過期會話了。 [**]( "復制到剪切板")[**]( "添加到筆記")<bean id="statelessAuthcFilter" class="com.github.zhangkaitao.shiro.chapter20.filter.StatelessAuthcFilter"/>&nbsp; 每次請求進行認證的攔截器。 [**]( "復制到剪切板")[**]( "添加到筆記")\<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"\> \<property name="securityManager" ref="securityManager"/\> \<property name="filters"\> \<util:map\> \<entry key="statelessAuthc" value-ref="statelessAuthcFilter"/\> \</util:map\> \</property\> \<property name="filterChainDefinitions"\> \<value\> /**=statelessAuthc \</value\> \</property\> \</bean\>&nbsp; 所有請求都將走 statelessAuthc 攔截器進行認證。 其他配置請參考源代碼。 SpringMVC 學習請參考: 5 分鐘構建 spring web mvc REST 風格 HelloWorld [](http://jinnianshilongnian.iteye.com/blog/1996071)<http://jinnianshilongnian.iteye.com/blog/1996071> 跟我學 SpringMVC [](http://www.iteye.com/blogs/subjects/kaitao-springmvc)<http://www.iteye.com/blogs/subjects/kaitao-springmvc> ## 20.2 客戶端 此處使用 SpringMVC 提供的 RestTemplate 進行測試。請參考如下文章進行學習: Spring MVC 測試框架詳解——客戶端測試 [](http://jinnianshilongnian.iteye.com/blog/2007180)<http://jinnianshilongnian.iteye.com/blog/2007180> Spring MVC 測試框架詳解——服務端測試 [](http://jinnianshilongnian.iteye.com/blog/2004660)<http://jinnianshilongnian.iteye.com/blog/2004660> 此處為了方便,使用內嵌 jetty 服務器啟動服務端: [**]( "復制到剪切板")[**]( "添加到筆記")public class ClientTest { private static Server server; private RestTemplate restTemplate = new RestTemplate(); @BeforeClass public static void beforeClass() throws Exception { //創建一個server server = new Server(8080); WebAppContext context = new WebAppContext(); String webapp = "shiro-example-chapter20/src/main/webapp"; context.setDescriptor(webapp + "/WEB-INF/web.xml"); //指定web.xml配置文件 context.setResourceBase(webapp); //指定webapp目錄 context.setContextPath("/"); context.setParentLoaderPriority(true); server.setHandler(context); server.start(); } @AfterClass public static void afterClass() throws Exception { server.stop(); //當測試結束時停止服務器 } }&nbsp; 在整個測試開始之前開啟服務器,整個測試結束時關閉服務器。 **測試成功情況** [**]( "復制到剪切板")[**]( "添加到筆記")@Test public void testServiceHelloSuccess() { String username = "admin"; String param11 = "param11"; String param12 = "param12"; String param2 = "param2"; String key = "dadadswdewq2ewdwqdwadsadasd"; MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add(Constants.PARAM_USERNAME, username); params.add("param1", param11); params.add("param1", param12); params.add("param2", param2); params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params)); String url = UriComponentsBuilder .fromHttpUrl("http://localhost:8080/hello") .queryParams(params).build().toUriString(); ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); Assert.assertEquals("hello" + param11 + param12 + param2, responseEntity.getBody()); }&nbsp; 對請求參數生成消息摘要后帶到參數中傳遞給服務器端,服務器端驗證通過后訪問相應服務,然后返回數據。 **測試失敗情況** [**]( "復制到剪切板")[**]( "添加到筆記")@Test public void testServiceHelloFail() { String username = "admin"; String param11 = "param11"; String param12 = "param12"; String param2 = "param2"; String key = "dadadswdewq2ewdwqdwadsadasd"; MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add(Constants.PARAM_USERNAME, username); params.add("param1", param11); params.add("param1", param12); params.add("param2", param2); params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params)); params.set("param2", param2 + "1"); String url = UriComponentsBuilder .fromHttpUrl("http://localhost:8080/hello") .queryParams(params).build().toUriString(); try { ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); } catch (HttpClientErrorException e) { Assert.assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); Assert.assertEquals("login error", e.getResponseBodyAsString()); } }&nbsp; 在生成請求參數消息摘要后,篡改了參數內容,服務器端接收后進行重新生成消息摘要發現不一樣,報 401 錯誤狀態碼。 到此,整個測試完成了,需要注意的是,為了安全性,請考慮本文開始介紹的相應解決方案。 **SpringMVC 相關知識請參考** 5 分鐘構建 spring web mvc REST 風格 HelloWorld [](http://jinnianshilongnian.iteye.com/blog/1996071)<http://jinnianshilongnian.iteye.com/blog/1996071> 跟我學 SpringMVC [](http://www.iteye.com/blogs/subjects/kaitao-springmvc)<http://www.iteye.com/blogs/subjects/kaitao-springmvc> Spring MVC 測試框架詳解——客戶端測試 [](http://jinnianshilongnian.iteye.com/blog/2007180)<http://jinnianshilongnian.iteye.com/blog/2007180> Spring MVC 測試框架詳解——服務端測試 [](http://jinnianshilongnian.iteye.com/blog/2004660)<http://jinnianshilongnian.iteye.com/blog/2004660>
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看