栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Ajax访问ServiceStack身份验证服务

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Ajax访问ServiceStack身份验证服务

此代码对我有效,基于Wiki文档自定义身份验证和授权

代码还基于ServiceStack上具有自定义身份验证的社区资源CORS
BasicAuth
的博客文章中

对于基本身份验证,自定义提供程序

   public class myAuthProvider : BasicAuthProvider    {public myAuthProvider() : base() { }       public override bool TryAuthenticate(IServicebase authService, string userName, string  password)    {        //Add here your custom auth logic (database calls etc)        //Return true if credentials are valid, otherwise false        if (userName == "admin" && password == "test")return true;         else    return false;    }    public override void onAuthenticated(IServicebase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)    {        //Fill the IAuthSession with data which you want to retrieve in the app        //  the base AuthUserSession properties e.g       session.FirstName = "It's me";        //...          //  derived CustomUserSession properties e.g        if(session is CustomUserSession)       ((CustomUserSession) session).MyData = "It's me";        //...        //important: You need to save the session!        authService.SaveSession(session, SessionExpiry);    }}public class CustomUserSession : AuthUserSession{    public string MyData { get; set; }}

在AppHost中

     using System.Web;     using ServiceStack;     // v.3.9.60  httpExtensions methods, before in ServiceStack.WebHost.Endpoints.Extensions;     using ....

AppHost.Configure

     public override void Configure(Container container)      {          SetConfig(new ServiceStack.WebHost.Endpoints.EndpointHostConfig          {    DefaultContentType = ContentType.Json       ..    //   remove GlobalResponseHeaders  because CordFeature adds the CORS headers to  Config.GlobalResponseHeaders });        Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization")); //Registers global CORS Headers        this.RequestFilters.Add((httpReq, httpRes, requestDto) =>        { if (httpReq.HttpMethod == "OPTIONS")       httpRes.EndRequestWithNoContent();   // v 3.9.60 httpExtensions method before httpRes.EndServiceStackRequest();        });          //Register all Authentication methods you want to enable for this web app. Plugins.Add(new AuthFeature(() => new  CustomUserSession(), // OR the AuthUserSession      new IAuthProvider[] {     new  myAuthProvider(),      }) { HtmlRedirect = null }); //  Redirect on fail  Routes.Add<TestRequest>("/TestAPI/{Id}", "POST,GET, OPTIONS");        ....      }

服役中

[Authenticate]          public class TestAPI : Service {          ... }

在Javascript中

     jQuery.support.cors = true;       function make_base_auth(user, password) {          var tok = user + ':' + password;          var hash = btoa(tok);          return "Basic " + hash;      }

先登录

function Authenticate() {   $.ajax({   type: 'Post',   contentType: 'application/json',   url: serverIP + 'Auth',   cache: false,   async: false,   data: {},   dataType: "json",   beforeSend: function (xhr) {       xhr.setRequestHeader("Authorization", make_base_auth(username, password));   },   success: function (response, status, xhr) {       localStorage.sessionId = data.SessionId;       var UserName  = response.userName;   },   error: function (xhr, err) {       alert(err);   }          });      }

并要求

         function DoTest() {   var TestRequest = new Object();   TestRequest.name = "Harry Potter";     TestRequest.Id = 33;  var username = "admin";  var password = "test";  $.ajax({   type: 'Post',   contentType: 'application/json',   cache: false,   async: false,   url: serverIP + '/TestAPI/'+ TestRequest.Id,   data: JSON.stringify(TestRequest),   dataType: "json",          beforeSend: function (xhr) {   xhr.setRequestHeader("Session-Id", localStorage.sessionId);   },success: function (response, status, xhr) {       var s= response.message;         },   error: function (xhr, err) {       alert(xhr.statusText);   }          });      }

这些问题在这里
和这里都是有帮助的。

如果我们可以使用cookie和session,那么对于CredentialsAuthProvider
也是这个答案。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号