Shiro 無狀態(tài) Web

2020-12-04 09:48 更新

無狀態(tài) Web 應(yīng)用集成

在一些環(huán)境中,可能需要把 Web 應(yīng)用做成無狀態(tài)的,即服務(wù)器端無狀態(tài),就是說服務(wù)器端不會(huì)存儲(chǔ)像會(huì)話這種東西,而是每次請(qǐng)求時(shí)帶上相應(yīng)的用戶名進(jìn)行登錄。如一些 REST 風(fēng)格的 API,如果不使用 OAuth2 協(xié)議,就可以使用如 REST+HMAC 認(rèn)證進(jìn)行訪問。HMAC(Hash-based Message Authentication Code):基于散列的消息認(rèn)證碼,使用一個(gè)密鑰和一個(gè)消息作為輸入,生成它們的消息摘要。注意該密鑰只有客戶端和服務(wù)端知道,其他第三方是不知道的。訪問時(shí)使用該消息摘要進(jìn)行傳播,服務(wù)端然后對(duì)該消息摘要進(jìn)行驗(yàn)證。如果只傳遞用戶名 + 密碼的消息摘要,一旦被別人捕獲可能會(huì)重復(fù)使用該摘要進(jìn)行認(rèn)證。解決辦法如:

  1. 每次客戶端申請(qǐng)一個(gè) Token,然后使用該 Token 進(jìn)行加密,而該 Token 是一次性的,即只能用一次;有點(diǎn)類似于 OAuth2 的 Token 機(jī)制,但是簡(jiǎn)單些;
  2. 客戶端每次生成一個(gè)唯一的 Token,然后使用該 Token 加密,這樣服務(wù)器端記錄下這些 Token,如果之前用過就認(rèn)為是非法請(qǐng)求。

為了簡(jiǎn)單,本文直接對(duì)請(qǐng)求的數(shù)據(jù)(即全部請(qǐng)求的參數(shù))生成消息摘要,即無法篡改數(shù)據(jù),但是可能被別人竊取而能多次調(diào)用。解決辦法如上所示。

服務(wù)器端

對(duì)于服務(wù)器端,不生成會(huì)話,而是每次請(qǐng)求時(shí)帶上用戶身份進(jìn)行認(rèn)證。

服務(wù)控制器

@RestController
public class ServiceController {
    @RequestMapping("/hello")
    public String hello1(String[] param1, String param2) {
        return "hello" + param1[0] + param1[1] + param2;
    }
}

當(dāng)訪問 / hello 服務(wù)時(shí),需要傳入 param1、param2 兩個(gè)請(qǐng)求參數(shù)。

加密工具類

com.github.zhangkaitao.shiro.chapter20.codec.HmacSHA256Utils:

//使用指定的密碼對(duì)內(nèi)容生成消息摘要(散列值)
public static String digest(String key, String content);
//使用指定的密碼對(duì)整個(gè)Map的內(nèi)容生成消息摘要(散列值)
public static String digest(String key, Map<String, ?> map)

對(duì) Map 生成消息摘要主要用于對(duì)客戶端 / 服務(wù)器端來回傳遞的參數(shù)生成消息摘要。

Subject 工廠

public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {
    public Subject createSubject(SubjectContext context) {
        //不創(chuàng)建session
        context.setSessionCreationEnabled(false);
        return super.createSubject(context);
    }
}

通過調(diào)用 context.setSessionCreationEnabled(false) 表示不創(chuàng)建會(huì)話;如果之后調(diào)用 Subject.getSession() 將拋出 DisabledSessionException 異常。

StatelessAuthcFilter

類似于 FormAuthenticationFilter,但是根據(jù)當(dāng)前請(qǐng)求上下文信息每次請(qǐng)求時(shí)都要登錄的認(rèn)證過濾器。

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、客戶端請(qǐng)求的參數(shù)列表
    Map<String, String[]> params = 
      new HashMap<String, String[]>(request.getParameterMap());
    params.remove(Constants.PARAM_DIGEST);
    //4、生成無狀態(tài)Token
    StatelessToken token = new StatelessToken(username, params, clientDigest);
    try {
      //5、委托給Realm進(jìn)行登錄
      getSubject(request, response).login(token);
    } catch (Exception e) {
      e.printStackTrace();
      onLoginFail(response); //6、登錄失敗
      return false;
    }
    return true;
  }
  //登錄失敗時(shí)默認(rèn)返回401狀態(tài)碼
  private void onLoginFail(ServletResponse response) throws IOException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    httpResponse.getWriter().write("login error");
  }
}

獲取客戶端傳入的用戶名、請(qǐng)求參數(shù)、消息摘要,生成 StatelessToken;然后交給相應(yīng)的 Realm 進(jìn)行認(rèn)證。

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;}
}

用戶身份即用戶名;憑證即客戶端傳入的消息摘要。

StatelessRealm

用于認(rèn)證的 Realm。

public class StatelessRealm extends AuthorizingRealm {
    public boolean supports(AuthenticationToken token) {
        //僅支持StatelessToken類型的Token
        return token instanceof StatelessToken;
    }
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //根據(jù)用戶名查找角色,請(qǐng)根據(jù)需求實(shí)現(xiàn)
        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);//根據(jù)用戶名獲取密鑰(和客戶端的一樣)
        //在服務(wù)器端生成客戶端參數(shù)消息摘要
        String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams());
        //然后進(jìn)行客戶端消息摘要和服務(wù)器端消息摘要的匹配
        return new SimpleAuthenticationInfo(
                username,
                serverDigest,
                getName());
    }
    private String getKey(String username) {//得到密鑰,此處硬編碼一個(gè)
        if("admin".equals(username)) {
            return "dadadswdewq2ewdwqdwadsadasd";
        }
        return null;
    }
}

此處首先根據(jù)客戶端傳入的用戶名獲取相應(yīng)的密鑰,然后使用密鑰對(duì)請(qǐng)求參數(shù)生成服務(wù)器端的消息摘要;然后與客戶端的消息摘要進(jìn)行匹配;如果匹配說明是合法客戶端傳入的;否則是非法的。這種方式是有漏洞的,一旦別人獲取到該請(qǐng)求,可以重復(fù)請(qǐng)求;可以考慮之前介紹的解決方案。

Spring 配置——spring-config-shiro.xml

<!-- Realm實(shí)現(xiàn) -->
<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"/>
<!-- 會(huì)話管理器 -->
<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>
<!-- 相當(dāng)于調(diào)用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>

sessionManager 通過 sessionValidationSchedulerEnabled 禁用掉會(huì)話調(diào)度器,因?yàn)槲覀兘玫袅藭?huì)話,所以沒必要再定期過期會(huì)話了。

<bean id="statelessAuthcFilter" 
    class="com.github.zhangkaitao.shiro.chapter20.filter.StatelessAuthcFilter"/>

每次請(qǐng)求進(jìn)行認(rèn)證的攔截器。

<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>

所有請(qǐng)求都將走 statelessAuthc 攔截器進(jìn)行認(rèn)證。

其他配置請(qǐng)參考源代碼。

SpringMVC 學(xué)習(xí)請(qǐng)參考:
5 分鐘構(gòu)建 spring web mvc REST 風(fēng)格 HelloWorld
http://jinnianshilongnian.iteye.com/blog/1996071
跟我學(xué) SpringMVC
http://www.iteye.com/blogs/subjects/kaitao-springmvc

客戶端

此處使用 SpringMVC 提供的 RestTemplate 進(jìn)行測(cè)試。請(qǐng)參考如下文章進(jìn)行學(xué)習(xí):
Spring MVC 測(cè)試框架詳解——客戶端測(cè)試
http://jinnianshilongnian.iteye.com/blog/2007180
Spring MVC 測(cè)試框架詳解——服務(wù)端測(cè)試
http://jinnianshilongnian.iteye.com/blog/2004660

此處為了方便,使用內(nèi)嵌 jetty 服務(wù)器啟動(dòng)服務(wù)端:

public class ClientTest {
    private static Server server;
    private RestTemplate restTemplate = new RestTemplate();
    @BeforeClass
    public static void beforeClass() throws Exception {
        //創(chuàng)建一個(gè)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(); //當(dāng)測(cè)試結(jié)束時(shí)停止服務(wù)器
    }
}

在整個(gè)測(cè)試開始之前開啟服務(wù)器,整個(gè)測(cè)試結(jié)束時(shí)關(guān)閉服務(wù)器。

測(cè)試成功情況

@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());
}

對(duì)請(qǐng)求參數(shù)生成消息摘要后帶到參數(shù)中傳遞給服務(wù)器端,服務(wù)器端驗(yàn)證通過后訪問相應(yīng)服務(wù),然后返回?cái)?shù)據(jù)。

測(cè)試失敗情況

@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());
    }
}

在生成請(qǐng)求參數(shù)消息摘要后,篡改了參數(shù)內(nèi)容,服務(wù)器端接收后進(jìn)行重新生成消息摘要發(fā)現(xiàn)不一樣,報(bào) 401 錯(cuò)誤狀態(tài)碼。

到此,整個(gè)測(cè)試完成了,需要注意的是,為了安全性,請(qǐng)考慮本文開始介紹的相應(yīng)解決方案。

SpringMVC 相關(guān)知識(shí)請(qǐng)參考

5 分鐘構(gòu)建 spring web mvc REST 風(fēng)格 HelloWorld
http://jinnianshilongnian.iteye.com/blog/1996071
跟我學(xué) SpringMVC
http://www.iteye.com/blogs/subjects/kaitao-springmvc
Spring MVC 測(cè)試框架詳解——客戶端測(cè)試
http://jinnianshilongnian.iteye.com/blog/2007180
Spring MVC 測(cè)試框架詳解——服務(wù)端測(cè)試
http://jinnianshilongnian.iteye.com/blog/2004660

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)