我如何在cookie中保存令牌(how I can save the token in the cookie)
IT问题网 2021-02-20 00:00:00
问 题
嗨,
我正在创建web服务身份验证。当用户使用用户名和密码登录时。 web服务器将令牌提供给客户端以使用该令牌请求web服务。我想使用cookie来保存令牌,以便让web服务验证客户端的令牌是否正确。
以下是我的代码。如果可以,请给我示例代码。
使用系统;
使用 system.collections.generic;
使用 system.linq;
使用 system.web;
使用 system.web.services;
使用 system.web.services.protocols;
使用 system.text;
命名空间 authwebapplication
{
使用系统。 security.cryptography;
/// summary
/// webservice1的摘要说明
/// / summary
[webservice(namespace = " http://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
[system.componentmodel.toolboxitem( false )]
// 允许从脚本调用此web服务,使用asp .net ajax,取消注释以下行。
// [system.web.script.services.scriptservice]
public class webservice1:system.web.services.webservice
{
public webservice1()
{
// 如果使用设计的组件,则取消注释以下行
// 的initializecomponent();
}
// public authheader soapauthentication;
[webmethod(description = " 使用soap标头演示简单web服务身份验证的示例web方法" )]
public string samplewebmethod( string 用户名,字符串密码)
{
if (用户名== " demo"amp;amp; password == " 123")
{
string token = guid.newguid()。tostring();
httpruntime.cache.add(令牌,用户名, null ,
system.web.caching.cache。 noabsoluteexpiration,
timespan.fromminutes( 60 ),
system.web.caching.cacheitempriority.notremovable,
null );
return token + " 是一个访问web方法的经过身份验证的用户";
// 返回用户名+"是经过身份验证的用户访问web方法";
}
其他
{
返回 " 拒绝访问" +用户名;
}
}
}
}
解决方案
您可以使用response对象将内容存储在cookie中。
response.cookies [" userinfo"] [" 用户名"] = " demo";
response.cookies [" userinfo"] [" 密码"] = " 123 "跨度>;
response.cookies [" userinfo"]。expires = datetime.now.adddays( 1 );
string userdata = " 123";
// 创建cookie身份验证票证。
ticket = new formsauthenticationticket(
1 , // 版本
测试, // 用户名
datetime.now, // 发布时间
datetime.now.adddays( 3 ), // 每小时到期
false , / / 不要保留cookie
userdata // 用户数据
);
// 加密票证
string cookiestr = formsauthentication.encrypt(ticket);
// 将cookie发送到客户端
httpcontext。 current.response.cookies [" testdata"]。value = cookiestr;
httpcontext.current.response.cookies [" testdata"]。path = " /";
httpcontext.current.response.cookies [" testdata"]。expires = datetime.now .addmonths( 3 );
分享:
热门推荐