此代码对我有效,基于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
也是这个答案。



