当前位置: 首页 > 编程语言 > C#

ServiceStackAPI和ASPMVCAuthentication有两种方式分享

时间:2023-04-10 22:21:58 C#

ServiceStackAPI和ASPMVCAuthentication有两种方式遇到麻烦了。应用程序存在于“http://myapplication.com”之类的基本URL中,而SS存在于“http://myapplication.com/api”中,因为这是配置两者的最简单方法。通常一切正常,但是当我进入授权和身份验证部分时,我被卡住了。首先,我需要应用程序处理cookie,因为ASP通常执行FormsAuthentication,当使用属性“Authorize”时,用户将通过登录屏幕并使用操作和控制器。这是典型的ASP,所以我对“http://myapplication.com/PurchaseOrders”之类的东西没有问题。另一方面,我的应用程序的客户端将从javascript使用我的Web服务API。在某些情况下,这些Web服务还标有ServiceStack的“Authenticate”属性。例如,“http://myapplication.com/api/purchaseorders/25”必须验证用户是否可以查看该特定采购订单,否则发送401Unauthorized以便javascript可以处理这些情况并显示错误消息。最后但同样重要的是,另一组用户将使用任何外部应用程序(可以是Java或.NET)通过令牌使用我的API。所以,我需要解决两种类型的身份验证,一种使用用户名和密码,另一种使用令牌并使其持久化,所以一旦第一次进行身份验证,下一次调用从解析的API中更快。这是我的代码到目前为止,我已经非常简单地说明了这个例子。[HttpPost]publicActionResultLogon(LogOnModelmodel,stringreturnUrl){if(ModelState.IsValid){JsonServiceClientclient=newJsonServiceClient("http://myapplication.com/api/");varauthRequest=newAuth{provider=CredentialsAuthProvider.Name,UserName=model.UserName,Password=model.Password,RememberMe=model.RememberMe};尝试{varloginResponse=client.Send(authRequest);FormsAuthenticationTicketticket=newFormsAuthenticationTicket(loginResponse.UserName,false,60);varcookie=newHttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));Response.Cookies.Add(cookie);如果(Url.IsLocalUrl(returnUrl)&&returnUrl.Length>1&&returnUrl.StartsWith("/")&&!returnUrl.StartsWith("//")&&!returnUrl.StartsWith("/\")){返回重定向(返回网址);}else{returnRedirectToAction("Index","Test");}}catch(Exception){ModelState.AddModelError("","无效的用户名orpassword");}}returnView();}至于身份验证提供程序,我正在使用这种类,stringuserName,stringpassword){//在此处添加您的自定义身份验证逻辑(数据库调用等)//如果凭据有效,则返回true,否则返回falseif(userName=="testuser"&&password=="nevermind"){returntrue;}else{returnfalse;}}publicoverridevoidOnAuthenticated(IServiceBaseauthService,IAuthSessionsession,IOAuthTokenstokens,DictionaryauthInfo){//用您想要在应用程序中检索的数据填充IAuthSession例如:session.FirstName="some_firstname_from_db";//...session.CreatedAt=DateTime.Now;session.DisplayName="MauricioLeyzaola";session.Email="mauricio.leyzaola@gmail.com";session.FirstName="Mauricio";session.IsAuthenticated=真;session.LastName="Leyzaola";session.UserName="mauricio.leyzaola";session.UserAuthName=session.UserName;变种角色=新列表();roles.AddRange(new[]{"admin","reader"});session.Roles=角色;session.UserAuthId="uniqueid-from-database";//base.OnAuthenticated(authService,session,tokens,authInfo);authService.SaveSession(session,SessionExpiry);在AppHost的配置函数中,我将自定义身份验证类设置为默认使用它我想我应该创建另一个类并将其添加到此处以处理令牌场景。Plugins.Add(newAuthFeature(()=>newCustomUserSession(),newIAuthProvider[]{newMyCredentialsAuthProvider(appSettings)},htmlRedirect:"~/Account/Logon"));到目前为止,ServiceStack正在按预期工作。我可以使用用户名和密码向/auth/credentials提交帖子并存储该信息,因此下一次调用该服务的请求已经获得授权,到目前为止非常棒!我需要知道的问题是如何从我的帐户控制器调用(可能在SS中的某个地方)登录用户。如果您看到我尝试调用Web服务的第一段代码(看起来我做错了)并且它有效,但对任何Web服务的下一次调用看起来未经身份验证。ServiceStack的教程请不要指指点点,我这两天都在看,还是搞不懂。非常感谢。这是我通常使用的:您可以用以下代码替换“登录”操作方法:publicActionResultLogin(LogOnModelmodel,stringreturnUrl){if(ModelState.IsValid){授权服务。RequestContext=System.Web.HttpContext.Current.ToRequestContext();varresponse=authService.Authenticate(newAuth{UserName=model.UserName,Password=model.Password,RememberMe=model.RememberMe});//添加ASP.NET身份验证cookieFormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);返回RedirectToLocal(returnUrl);}catch(HttpError){}}//如果我们走到这一步,有些东西失败了,重新显示表单ModelState.AddModelError("","提供的用户名或密码不正确。");返回视图(模型);}...和插件://默认路由:/auth/{provider}Plugins.Add(newAuthFeature(()=>newCustomUserSession(),newIAuthProvider[]{newCustomCredentialsAuthProvider(),newCustomBasicAuthProvider()}));....授权提供者类:公共类CustomCredentialsAuthProvider:CredentialsAuthProvider{publicoverrideboolTryAuthenticate(IServiceBaseauthService,stringuserName,stringpassword){returnUserLogUtil.LogUser(authService,userName,password);}}公共类CustomBasicAuthProvider:BasicAuthProvider{publicoverrideboolTryAuthenticate(IServiceBaseauthService,stringuserName,stringpassword){returnUserLogUtil.LogUser(authService,userName,password);}}...最后是日志实用类以上就是C#学习教程的全部内容:ServiceStackAPI和ASPMVCauthentication有两种方式分享,如果你有用需要进一步了解C#学习教程,希望大家多多关注—internalstaticclassUserLogUtil{publicstaticboolLogUser(IServiceBaseauthService,stringuserName,stringpassword){varuserService=newUserService();//这可以是一个网络服务;或者,您可以从这里调用您的存储库varloggingResponse=(UserLogResponse)userService.Post(newLoggingUser{UserName=userName,Password=password});如果(loggingResponse.User!=null&&loggingResponse.ResponseStatus==null){varsession=(CustomUserSession)authService.GetSession(false);session.DisplayName=loggingResponse.User.FName.ValOrEmpty()+""+loggingResponse.User.LName.ValOrEmpty();session.UserAuthId=用户名;session.IsAuthenticated=true;session.Id=loggingResponse.User.UserID.ToString();//添加角色和权限//session.Roles=newList();//session.Permissions=newList();//session.Roles.Add("Admin");//session.Permissions.Add("Admin");returntrue;}elsereturnfalse;}}本文收集自网络,不代表立场,如如涉及侵权,请点击右侧联系管理员删除,如需转载请注明出处: