Servicestack.Client Namespace Secured could not be found - servicestack

When I try to make a new request to generate a new access-token I cannot find the type "new Secured".
var authClient = new JsonServiceClient("http://localhost/authentication/")
{
RefreshToken = Request.GetCookieValue("ss-refreshtok"),
RefreshTokenUri = "http://localhost/authentication/access-token"
};
var jwt = authClient.Send(new Secured());
Even thought I have Servicestack.client installed it cannot be found. But using new Authenticate() its ok.

The Secure Request DTO is an example of a Request DTO for a Service that’s protected with the [Authenticate] attribute, it’s not a built in DTO, you should substitute it to use your Request DTO instead.

Related

How to put an Api key in the Authenticate message?

I'm trying to combine the api key auth provider with the encrypted messaging plugin.
var client = new JsonServiceClient(home);
client.BearerToken = "somesecret";
works
but i want my apikey to be in the message so i tried
var authResponse = client.Post(new Authenticate
{
provider = ApiKeyAuthProvider.Name,
UserName = "somesecret"
});
This post fails at runtime with a 401 not authenticated.
How do i get this to work?
IAuthWithRequest Auth Providers like the API Key Auth Provider needs to be sent per request with the Authenticated User Session it establishes only lasts for the lifetime of that request. It can't be used with the Authenticate Service to Authenticate the client as your example tried to do, it must be included in each request to an Authenticated Service.
The normal way to call a protected Service with the API Key is to just populate the BearerToken property:
var client = new JsonServiceClient(baseUrl) {
BearerToken = apiKey
};
Which will then let you call your [Authenticate] Service:
var response = client.Get(new Secure { Name = "World" });
Encrypted Messaging Support
Previously you could only embed the User SessionId within an Encrypted Messaging Request but I've just added support for Authenticating Encrypted Messaging Services with a BearerToken in this commit which works similar to populating a SessionId, where you can now populate a BearerToken as used in API Key and JWT Auth Providers by having your Request DTOs implement IHasBearerToken, e.g:
public class Secure : IHasBearerToken
{
public string BearerToken { get; set; }
public string Name { get; set; }
}
This will let you embed the BearerToken when calling the protected Service, e.g:
IEncryptedClient encryptedClient = client.GetEncryptedClient(publicKey);
var response = encryptedClient.Get(new Secure { BearerToken = apiKey, Name = "World" });
Where it will be embedded and encrypted along with all content in the Request DTO.
Alternatively you can also set the BearerToken property on the IEncryptedClient once and it will automatically populate it on all Request DTOs that implement IHasBearerToken, e.g:
encryptedClient.BearerToken = apiKey;
var response = encryptedClient.Get(new Secure { Name = "World" });
The new BearerToken support in Encrypted Messaging is available from v5.1.1 that's now available on MyGet.

How Owin Works regarding AuthenticationTicket to a authenticated UserPrincipal

So, ive made a simple basic auth middleware for owin. The middleware returns an AuthenticationTicket with the user principal claims, authentication type ("Basic") yada yada.
protected override Task<AuthenticationTicket> AuthenticateCoreAsync()
{
....
var claimsIdentity = TryGetPrincipalFromBasicCredentials(token, Options.CredentialValidationFunction);
....
var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties(){userName = claimsIdentity.name});
return Task.FromResult(ticket);
}
To get the claims, im using a hardcoded value for testing:
var claims = new List<Claim>();
claims.Add(new Claim(KneatClaimTypes.Permission, Permission.UserAdministrationView.ToString()));
var claimsIdentity = new ClaimsIdentity(
new GenericIdentity("Administrator", "Basic"),
claims
);
return claimsIdentity;
I`m hooking into owin using a simple extension using the same architecture IdentityModel has
https://github.com/IdentityModel/IdentityModel.Owin.BasicAuthentication
app.UseBasicAuthentication(new BasicAuthOptions("Realm",
(username, password, context) => BasicAuthCredentialCheck.Authenticate(username, password, context))
{
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = "Basic"
});
Im creating the correct principal for the ticket, but after the owin resolves the authentication the Thread.currentPrincipal is not populated. If i add a simple cookie auth , whenever i call Owin.Authentication.SignIn(...) it creates the Principal for me. If i set manually the Thread.currentPrincipal, something is UNSETTING that.
Im not very deep on how owin works under the hood, and i was tryng to get the source from it and begin reading it maybe ill figure it out. But in case i dont, any ideas on who could be resetting this Thread.currentPrincipal ? (Searched my own app code, no one does that, only reads no setting)
Best Regards.

How to use Basic Auth with libsoup via Gjs

I'm trying to query github's api with a token. Github's api accepts generated tokens provided that they're sent as a basic auth header.
The API do not return HTTP 401 if the call is made without auth which means if one wants to query their api using Basic Auth, one must fill the header pre-emptively rather than doing a round trip.
I'm now trying to query the API using libsoup and Gjs.
I have noticed the SoupAuthManager has a function that seems to match perfectly what I need (soup_auth_manager_use_auth here) but can't find a way to invoke it.
This can be used to "preload" manager 's auth cache, to avoid an extra HTTP round trip in the case where you know ahead of time that a 401 response will be returned
This is what I currently use, but it does not work as the SoupAuthManager is a private object of the session; and has therefore no effect on the actual behaviour of the program
let httpSession = new Soup.Session();
let authUri = new Soup.URI(url);
authUri.set_user(this.handle);
authUri.set_password(this.token);
let message = new Soup.Message({method: 'GET', uri: authUri});
let authManager = new Soup.AuthManager();
let auth = new Soup.AuthBasic({host: 'api.github.com', realm: 'Github Api'});
authManager.use_auth(authUri, auth);
httpSession.queue_message(message, ...);
Are there other methods I could use to force Basic Auth on the first roud trip? or are there other library I could use from gjs to call github's API and force the basic auth?
I found the solution. To link the authorisation to the session, one can use the add_feature function. Now this is defined here but it turns out calling it directly doesn't work
this._httpSession.add_feature(authManager)
instead it seems to work if called like that:
Soup.Session.prototype.add_feature.call(httpSession, authManager);
finally, the github api rejects any call without a user agent, so I added the following:
httpSession.user_agent = 'blah'
the final code looks like:
let httpSession = new Soup.Session();
httpSession.user_agent = 'blah'
let authUri = new Soup.URI(url);
authUri.set_user(this.handle);
authUri.set_password(this.token);
let message = new Soup.Message({method: 'GET', uri: authUri});
let authManager = new Soup.AuthManager();
let auth = new Soup.AuthBasic({host: 'api.github.com', realm: 'Github Api'});
Soup.Session.prototype.add_feature.call(httpSession, authManager);
httpSession.queue_message(message, function() {...});

Can't Resolve a service using AppHostBase.ResolveService<T> API in ServiceStack 4

I'm using ASP.NET MVC 5 and attempting to resolve a few services using the example:
var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var response = authService.Authenticate(new Auth
{
UserName = model.UserName,
Password = model.Password,
RememberMe = model.RememberMe
});
or I've also tried:
using (var helloService = AppHostBase.ResolveService<HelloService>())
{
ViewBag.GreetResult = helloService.Get(name).Result;
return View();
}
In the first case I needed the RequestContext injected so I tried that approach and in the second case I was using the example which I understand has the RequestContext automatically injected through Funq.
ResolveService could not be found when I tried the second approach and in the first approach RequestContext is not a valid property. Am I missing something simple or has there been changes to the API?
The documentation does appear to be wrong for this as there is no longer a ResolveService<T> on AppHostBase. It needs to be updated due to changes in the Api.
You can do this in ServiceStack v4 with MVC:
var authService = HostContext.Resolve<AuthService>();
...

ServiceStack CredentialAuthProvider with more than User/Password

I want to use a custom auth provider, but I don't see how I can make the standard Auth stuff handle more that user and password as parameters.
Can this be done?
Depends what you want to do, if you want to create your own Custom auth provider by inheriting from CredentialsAuthProvider, you can access different request params via the IHttpRequest object:
public virtual bool TryAuthenticate(IServiceBase authService,
string userName, string password)
{
var httpReq = authService.RequestContext.Get<IHttpRequest>();
var fromQueryString = httpRequest.QueryString["CustomField"];
var fromPostData = httpRequest.FormData["CustomField"];
var fromEither = httpRequest.GetParam("CustomField"); //Ext method
}
Here are some other related questions and answers that show different ways to customize ServiceStack's built-in Auth:
How can I extend ServiceStack Authentication
Populating IAuthSession with data from the database

Resources