ASP.net:是否可以从会话 ID 手动初始化会话
我正在用 C# 构建一个 Web 服务 (ASMX)。我正在考虑使用 ASP.net 会话 ID 作为身份验证的令牌。
我有使用 CreateSessionID 生成的会话 ID。身份验证成功后,该信息将发送给客户端(作为 Web 服务调用“登录”的返回值)。
对于后续请求,客户端会将会话 ID 作为参数发送给 Web 服务调用。是否可以从该会话 ID 字符串重新创建会话?
提前致谢。
I am building a web service (ASMX) in C#. I am thinking of using ASP.net session ID as a token for authentication.
I have session-id generated with CreateSessionID. This will be sent to client after successful authentication (as return value of web-service call 'login').
For subsequent requests, the client will send the session-id as a parameter to the web-service call. Is it possible to recreate the session from this session ID string ?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种方法的问题是 CreateSessionID 实际上并不创建会话。顾名思义,它只创建一个唯一的会话 ID。如果您查看 MSDN 文档 ,它说
如果您阅读更多内容,您会发现该方法将被自定义会话 ID 管理器覆盖,然后可以通过编辑 web.config 将其集成到会话管理系统中。
换句话说,您当前对 CreateSessionID 的使用并未执行您希望它执行的操作。
如果您确实想在 Web 服务中使用会话状态,您应该查看 这篇文章。
简而言之,您需要将
EnableSession=true
参数添加到[WebMethod]
属性中,然后您可以通过Context.Session
自动访问会话>。请注意,这不需要通过服务传递会话 ID,因为 IIS 将为您处理所有事情。您可以使用
CreateSessionID()
方法(尽管最好使用其他方法)来创建用户需要在每个请求中传递的令牌,但这只会用于验证用户;无法基于它重新生成任何会话。如果您确实选择此路线,请确保您的服务是通过 HTTPS 访问的。否则,任何窃听者都会看到纯文本形式的令牌(尽管如果您还检查 IP 地址/用户代理字符串/等,这可以减轻这种情况)希望有所帮助。
The problem with this approach is CreateSessionID doesn't actually create a session. As the name suggests, it creates only a unique session id. If you look at the MSDN documentation, it says
If you read a bit more, you'll see that the method is meant to be overridden by custom session id managers, which can then be integrated into the session management system by editing your web.config.
In other words, your current usage of CreateSessionID is not doing what you want it to do.
If you actually want to use Session state in your web service, you should have a look at this article.
Briefly, you need to add the
EnableSession=true
parameter to your[WebMethod]
attributes, and then you can access the session automatically viaContext.Session
. Note that this does not require passing the session id via the service, as IIS will handle everything for you.You can use the
CreateSessionID()
method (though preferably you'd use something else) to create a token that the users needs to pass with each request, but it would only be used to verify the user; no session could be regenerated based on it. If you do go this route, make sure your service is accessed via HTTPS. Otherwise, any eavesdropper will see the token right there in plain-text (though this can mitigated if you also check against IP address/user-agent string/etc.)Hope that helps.