Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

.net - When ServiceStack authentication fails, do not redirect?

We're building a ServiceStack API which will use Basic authentication. I've currently set up the auth in my AppHost as follows:

var authDb = new OrmLiteConnectionFactory("Server=(...);", true, MySqlDialectProvider.Instance);

var authRepo = new OrmLiteAuthRepository(authDb);
authRepo.CreateMissingTables();
container.Register<ICacheClient>(c => new MemoryCacheClient());
container.Register<IUserAuthRepository>(c => authRepo);

Plugins.Add(
    new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() })
);

When doing a request with no Authorization header or the wrong username+pass the response is a redirect to /Account/Login.aspx?ReturnUrl=...

Parital request + response example:

POST http://localhost:60278/reserve HTTP/1.1

HTTP/1.1 302 Found
Location: /Account/Login.aspx?ReturnUrl=%2freserve
X-Powered-By: ServiceStack/3,924 Win32NT/.NET

Is there a way to make it respond with only a HTTP 401 Unauthorized or a HTTP 403 Forbidden ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By default ServiceStack's AuthFeature will only try to redirect you to the default ~/login path for HTML Content-Type requests. You can override this by setting the redirect path in the AuthFeature to null:

Plugins.Add(new AuthFeature(...) { HtmlRedirect = null });

This will fall back to the standard 401 UnAuthorized Response that the other Content-Types get.

After globally setting the HtmlRedirect to null, you can add it back on an adhoc basis, e.g:

[Authenticate(HtmlRedirect="~/path/to/redirect/to")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...