ITeye博客

第二十章 无状态Web应用集成——《跟我学Shiro》

jinnianshilongnian · 2014-04-08 08:39 · 跟我学Shiro · 企业架构 · Markdown

目录贴: 跟我学Shiro目录贴

 

在一些环境中,可能需要把Web应用做成无状态的,即服务器端无状态,就是说服务器端不会存储像会话这种东西,而是每次请求时带上相应的用户名进行登录。如一些REST风格的API,如果不使用OAuth2协议,就可以使用如REST+HMAC认证进行访问。HMAC(Hash-based Message Authentication Code):基于散列的消息认证码,使用一个密钥和一个消息作为输入,生成它们的消息摘要。注意该密钥只有客户端和服务端知道,其他第三方是不知道的。访问时使用该消息摘要进行传播,服务端然后对该消息摘要进行验证。如果只传递用户名+密码的消息摘要,一旦被别人捕获可能会重复使用该摘要进行认证。解决办法如:

1、每次客户端申请一个Token,然后使用该Token进行加密,而该Token是一次性的,即只能用一次;有点类似于OAuth2的Token机制,但是简单些;

2、客户端每次生成一个唯一的Token,然后使用该Token加密,这样服务器端记录下这些Token,如果之前用过就认为是非法请求。

 

为了简单,本文直接对请求的数据(即全部请求的参数)生成消息摘要,即无法篡改数据,但是可能被别人窃取而能多次调用。解决办法如上所示。

  

服务器端

对于服务器端,不生成会话,而是每次请求时带上用户身份进行认证。

  

服务控制器

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

当访问/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) 

对Map生成消息摘要主要用于对客户端/服务器端来回传递的参数生成消息摘要。

  

Subject工厂  

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

通过调用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");
  }
}
 

获取客户端传入的用户名、请求参数、消息摘要,生成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;}
} 

用户身份即用户名;凭证即客户端传入的消息摘要。

 

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

此处首先根据客户端传入的用户名获取相应的密钥,然后使用密钥对请求参数生成服务器端的消息摘要;然后与客户端的消息摘要进行匹配;如果匹配说明是合法客户端传入的;否则是非法的。这种方式是有漏洞的,一旦别人获取到该请求,可以重复请求;可以考虑之前介绍的解决方案。

 

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> 

sessionManager通过sessionValidationSchedulerEnabled禁用掉会话调度器,因为我们禁用掉了会话,所以没必要再定期过期会话了。 

 

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

每次请求进行认证的拦截器。 

 

<!-- Shiro的Web过滤器 -->
<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> 

所有请求都将走statelessAuthc拦截器进行认证。

 

其他配置请参考源代码。

 

SpringMVC学习请参考:

5分钟构建spring web mvc REST风格HelloWorld

  http://jinnianshilongnian.iteye.com/blog/1996071

跟我学SpringMVC

  http://www.iteye.com/blogs/subjects/kaitao-springmvc

 

客户端

此处使用SpringMVC提供的RestTemplate进行测试。请参考如下文章进行学习:

Spring MVC测试框架详解——客户端测试

   http://jinnianshilongnian.iteye.com/blog/2007180

Spring MVC测试框架详解——服务端测试 

   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(); //当测试结束时停止服务器
    }
} 

在整个测试开始之前开启服务器,整个测试结束时关闭服务器。

 

测试成功情况 

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

对请求参数生成消息摘要后带到参数中传递给服务器端,服务器端验证通过后访问相应服务,然后返回数据。

 

测试失败情况 

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

在生成请求参数消息摘要后,篡改了参数内容,服务器端接收后进行重新生成消息摘要发现不一样,报401错误状态码。

 

到此,整个测试完成了,需要注意的是,为了安全性,请考虑本文开始介绍的相应解决方案。

 

 

SpringMVC相关知识请参考

5分钟构建spring web mvc REST风格HelloWorld

  http://jinnianshilongnian.iteye.com/blog/1996071

跟我学SpringMVC

  http://www.iteye.com/blogs/subjects/kaitao-springmvc

Spring MVC测试框架详解——客户端测试

   http://jinnianshilongnian.iteye.com/blog/2007180

Spring MVC测试框架详解——服务端测试 

   http://jinnianshilongnian.iteye.com/blog/2004660

        

 

示例源代码:https://github.com/zhangkaitao/shiro-example;可加群 231889722 探讨Spring/Shiro技术。

评论(25)

  1. #25 楼 · flyfeifei66 · 2019-05-23 16:12

    这种方式登录成功后,下次如何标识身份确保不用再次登录?

  2. #24 楼 · 私奔到冰岛 · 2018-08-27 11:35

    看了项目,没找到验证的逻辑在哪?楼主不是说前端发过来的摘要和服务的的摘要要一样才行吗?这个逻辑应该自己实现吧,是不是要在relrealm里自己判断啊,shiro默认的认证实现应该做不到吧

  3. #23 楼 · zhangcheng125 · 2018-07-17 15:18

    配置中 这个报错。

  4. #22 楼 · lvyuan1234 · 2018-03-07 10:35

    运行demo测试类时,出现两个问题,希望对后来的人有帮助 :D 1.刚开始运行测试类一直报404NOT FOUNDD,把jetty的webapp目录改为String webapp = "./src/main/webapp";即可 2.即使运行success那个测试方法也返回401未授权,原因是测试方法中添加参数的顺序问题,将params.add(Constants.PARAM_USERNAME, username);放到param1和param2之间即可

  5. #21 楼 · jy02149522 · 2018-02-01 09:24

    我想说的是 如果是用客户端进行加密算法 提交服务器 如果这个客户端就是网页呢 js算法都暴露在页面上 不是很容易被破解吗 这个问题 怎么解决啊

  6. #20 楼 · LeanTaoT · 2018-01-09 10:29

    开涛老师你好,我在操作的时候报了以下错误,是在授权完之后,return true SHIRO会自动去创建session,但是session已经disable了,所以请问下是啥问题,具体报错如下:See the org.apache.shiro.subject.support.DisabledSessionException JavaDoc for more

  7. #19 楼 · u014027433 · 2017-12-15 16:24

    有状态和无状态的情况如何共存?

  8. #18 楼 · zhufj0952 · 2016-09-12 16:37

    sbwfgihc writes:

    [quote=newitstar][quote=liuzhifeixff][quote=penwei][quote=liaowu010][quote=xumin_wlt][quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。[/quote] 在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc
    [/quote]

    我也有这需求和疑问,按照你的方式试了一下好像不行。这样在请求成功后还是会创建session,每次次请求都会创建新的session,内存会溢出的。 [/quote]

    [code=java] public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {

    @Override
    public Subject createSubject(SubjectContext context) {
        //不创建session
        context.setSessionCreationEnabled(false);
        return super.createSubject(context);
    }
    

    }[/code] 通过调用context.setSessionCreationEnabled(false)表示不创建会话[/quote]

    我想轻微 调用这个方法之后 对整个程序是不是 都不创建Session 了?如何能动态创建session 移动接口需要无状态的,web 需要session [/quote]

    有大神解决这个问题了吗,留点思路啊

    你的想法实现了吗?我也想实现同样的需求

  9. #17 楼 · loveuserzzz · 2016-05-19 09:17

    楼主,那上面那两问题最后配置文件得配两个realm吧,可是策略如何配置呢,我也遇到这个问题,好着急啊

  10. #16 楼 · sbwfgihc · 2016-05-15 19:44

    newitstar writes:

    [quote=liuzhifeixff][quote=penwei][quote=liaowu010][quote=xumin_wlt][quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。[/quote] 在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc
    [/quote]

    我也有这需求和疑问,按照你的方式试了一下好像不行。这样在请求成功后还是会创建session,每次次请求都会创建新的session,内存会溢出的。 [/quote]

    [code=java] public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {

    @Override
    public Subject createSubject(SubjectContext context) {
        //不创建session
        context.setSessionCreationEnabled(false);
        return super.createSubject(context);
    }
    

    }[/code] 通过调用context.setSessionCreationEnabled(false)表示不创建会话[/quote]

    我想轻微 调用这个方法之后 对整个程序是不是 都不创建Session 了?如何能动态创建session 移动接口需要无状态的,web 需要session

    有大神解决这个问题了吗,留点思路啊

  11. #15 楼 · newitstar · 2016-04-19 14:30

    liuzhifeixff writes:

    [quote=penwei][quote=liaowu010][quote=xumin_wlt][quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。[/quote] 在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc
    [/quote]

    我也有这需求和疑问,按照你的方式试了一下好像不行。这样在请求成功后还是会创建session,每次次请求都会创建新的session,内存会溢出的。 [/quote]

    [code=java] public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {

    @Override
    public Subject createSubject(SubjectContext context) {
        //不创建session
        context.setSessionCreationEnabled(false);
        return super.createSubject(context);
    }
    

    }[/code] 通过调用context.setSessionCreationEnabled(false)表示不创建会话

    我想轻微 调用这个方法之后 对整个程序是不是 都不创建Session 了?如何能动态创建session 移动接口需要无状态的,web 需要session

  12. #14 楼 · mominghuan · 2016-03-17 09:25

    跑了一下代码,并没有调用授权方法doGetAuthorizationInfo

  13. #13 楼 · liuzhifeixff · 2016-01-22 15:46

    penwei writes:

    [quote=liaowu010][quote=xumin_wlt][quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。[/quote] 在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc
    [/quote]

    我也有这需求和疑问,按照你的方式试了一下好像不行。这样在请求成功后还是会创建session,每次次请求都会创建新的session,内存会溢出的。

    
    public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory {
    
        @Override
        public Subject createSubject(SubjectContext context) {
            //不创建session
            context.setSessionCreationEnabled(false);
            return super.createSubject(context);
        }
    }
    

    通过调用context.setSessionCreationEnabled(false)表示不创建会话

  14. #12 楼 · penwei · 2016-01-12 18:40

    liaowu010 writes:

    [quote=xumin_wlt][quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。[/quote] 在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc

    我也有这需求和疑问,按照你的方式试了一下好像不行。这样在请求成功后还是会创建session,每次次请求都会创建新的session,内存会溢出的。

  15. #11 楼 · msdev · 2015-12-16 09:45

    楼主写的测试用例是有问题的?MultiValueMap是无序的,所以客户端和服务端生成的digest会不一样?

  16. #10 楼 · liaowu010 · 2015-11-11 10:46

    xumin_wlt writes:

    [quote=wsrongdi111]大神,我有两个问题有点不明白希望不吝赐教! 1.如果说一个应用既有有状态的web,又有无状态的app那么shiro对这种情况应该怎么控制呢,可不可以定义两个shiroFilter或者是配置多个SecurityManager呢。 2.还有为什么和spring整合的时候直接在spring的配置文件中声明一个id为shiroFilter的bean然后web.xml中配置一个filter-name为shiroFilter的过滤器之后shiro就能工作了呢,是不是可以这样理解,web.xml中配置的过滤器的名字如果改了,那么在spring的配置文件中的那个bean的id也应该响应变化呢[/quote] 我也有同样的问题,不知道您有没有解决方案,目前我也在做这方面的web应用,只是不知道从哪个方面入手。

    在securityManager配置两个Realm分别对web和app进行身份校验;对应配置两个shiroFilter和filterChainDefinitions来对web和app的请求路径进行分管。 /api/=HmacAuthc /login = authc /=authc

  17. #9 楼 · like_dark · 2015-06-14 16:57

    哥们,你上面说的这个安全方案,感觉太麻烦了,每请求一个接口就得生成一个token,有没有有没有个好办法就是在登录的时候通过https请求,然后返回一个token,以后都通过http请求,只要做身份验证即可,麻烦提供个更好的方案啊

    1、每次客户端申请一个Token,然后使用该Token进行加密,而该Token是一次性的,即只能用一次;有点类似于OAuth2的Token机制,但是简单些;

    2、客户端每次生成一个唯一的Token,然后使用该Token加密,这样服务器端记录下这些Token,如果之前用过就认为是非法请求。

  18. #8 楼 · polluxtech · 2015-05-10 20:24

    另外补充一点,在消息摘要中加入时间,其实是有效的抵制了“重放攻击” :)

  19. #7 楼 · polluxtech · 2015-05-10 20:22

    另外关于可能会重复使用该摘要进行认证这个问题,除了楼主的两个方法外,还可以采用在生成消息摘要时加入当前时间,并在请求头中把这个时间一起传给服务器。服务器获得该时间后,采用相同算法算出该消息摘要,然后可以进一步判断该请求是否在有效时间,如果该请求超过一定的时间范围,则视为无效请求。

  20. #6 楼 · chenlin_8898 · 2015-04-29 14:33

    博主牛X,太有用了 :idea: :idea:

评论功能维护中,当前仅展示历史评论。