How do I create an authenticated session in ServiceStack? - servicestack

I have a situation where I'm using Credentials auth successfully, but I sometimes need to be able to simply create an authenticated session from inside a service using nothing but the user's email address. How can I do that? I suppose I'm looking for something similar in intent to FormsAuthentication.SetAuthCookie(), but I haven't found it.
Here's my thinking so far. Assuming I have to construct this myself, I see this inside CredentialsAuthProvider.TryAuthenticate:
if (authRepo.TryAuthenticate(userName, password, out userAuth))
{
session.PopulateWith(userAuth);
session.IsAuthenticated = true;
session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
session.ProviderOAuthAccess = authRepo.GetUserOAuthProviders(session.UserAuthId)
.ConvertAll(x => (IOAuthTokens)x);
return true;
}
That seems to imply that I can do what's inside the block myself via a UserAuth object from IUserAuthRepository.GetUserAuthByUserName(). I don't think this is enough though, since the session isn't saved here. Working backwards, I found that TryAuthenticate is called by Authenticate which then goes on to call OnAuthenticated where other things happen including saving the session. Can I resolve an instance of CredentialsAuthProvider and call OnAuthenticated myself?
Am I on the right track, or is this the completely wrong way of going about this?

sometimes need to be able to simply create an authenticated session from inside a service using nothing but the user's email address. How can I do that? I suppose I'm looking for something similar in intent to FormsAuthentication.SetAuthCookie()
I think the simplest, most FormsAuthentication.SetAuthCookie() way I can think of is to modify the AuthUserSession within in your service. The code below will get the Session, set IsAuthenticated to true, set the email and save the Session.
public class SomeService : Service
{
public String Any(SomeRequest request)
{
//not sure you need it, but you could put some code here to verify the email is allowed to authenticate
//and if true run the code below
var sess = this.SessionAs<AuthUserSession>();
sess.IsAuthenticated = true;
sess.Email = "test#email.com";
this.SaveSession(sess);
return "success";
}
}

Related

Send additional parameters to social login

Is there anyway to save additional data to the session when doing a social login/signup?
I noticed that if I send returnUrl parameter to the SS OAuth endpoint (i.e. /auth/google?retunUrl=...) then this value gets saved to the session as ReferrerUrl so I am using that to embed data as url parameters. I would prefer to be able to write to the Meta collection when directing to the SS Auth endpoint and then later read it from the session.
I tried to follow the exact process of how this was being saved to the session but I found it quite confusing.
What is the best way to add additional meta data to a social login/signup?
Edit:
I am talking about making a GET request to /auth/google, /auth/facebook etc...
I have additional data I want to track with the signup the user has entered in the browser.
If I add code to OnAuthenticated then this doesn't solve problem as the data has gone out of scope of the browser. It has to be passed in the GET request to the auth endpoint or have some reference to match up.
Edit:
public class CustomUserSession : AuthUserSession
{
public override void OnCreated(IRequest httpReq)
{
this.Meta.Add("foo", "bar");
httpReq.SaveSession(this);
}
}
You can handle a callback with the OnAuthenticated() Session or Auth Events.

Logout on ServiceStack v4

I have ServiceStack v4 service but when I call the auth/logout route (using either POST or GET) to logout the currently logged-in user, I get an error:
400 Not Empty
User Name cannot be empty
Password Cannot be empty
As I wouldn't expect users to enter credentials when logging out, I am surely missing something?
I have the AuthFeature registered during host initialisation, and I am using CredentialsAuthProvider. I have taken the code from Github so I can see how it works.
My Client Code:
var rest = Restangular.one('auth/logout').get();
//var result = rest.post({userName: userName});
this.requestTracker.addPromise(rest);
return rest;
After a lot of digging, this happens when you are using CredentialsAuthProvider. Within this class, a validator is defined that validates all instances of the Authenticate request. As the logout route uses the Authenticate request, this validator is fired.
I got round it by modifying the validator to:
RuleFor(x => x.UserName).NotEmpty().When(d => d.provider != "logout");
RuleFor(x => x.Password).NotEmpty().When(d => d.provider != "logout");
This is probably not the most elegant way of fixing long term, but got me up and running.
I know this question is old, but I recently have been struggling with the same thing. What occurs is that before the Authenticate.Post function is called, the validation cache is checked and the CredentialsAuthProvider which has the mentioned validator fails unless username and password are not empty.
Now, i'm not sure if it makes a difference if you only have that provider enabled or not - I've not tested. I actually have my own custom provider that subclasses CredentialsAuthProvider and it's the only one I register.
The only way currently is to either pass a non-empty (but useless) password and username, or modify your own custom provider, overriding the Authenticate function and using a modified version of the validator as mentioned above.

Servicestack - Call AuthProvider automatically

I would like to build my own AuthProvider. It should
Check if ss-id cookie is set and check for a valid session (this is
done automatically in servicestack)
If no valid session was found check a custom http-header (e.g. X-Api-Token)
If found a valid token create a new session
If not found a valid token send 401 Unauthorized
Basically this is the behaviour of the CredentialsAuthProvider except that I need to check for the X-Api-Token without making an explicit call to /auth/credentials. However the AuthProvider is never called automatically.
Any ideas how to get this done?
Edit: One idea was to use a request filter but there is still something missing:
this.GlobalRequestFilters.Add((request, response, arg3) =>
{
//If there is a valid ss-id cookie the it should have precedence and the request should be authenticated accordingly
if (!ValidatedViaSsIdCookie())
{
if (HeaderHasCorrectApiKey()) {
//Authenticate the current request by creating a new Session
AuthenticateRequest();
}
}
}
);
How to implement ValidatedViaSsIdCookie() and AuthenticateRequest()???
Edit: I don't think GlobalRequestFilters are the way to go because they will be executed after authentication... So if there is no valid session the filter is not executed at all and my Api key is never checked... Still searching for a better solution...
Regards
Dirk

WebClient with credentials still not downloading file

I am trying to download files from a website with username/password. You need to pay for a registered account in order to download files - which we have done. I am attempting to pass in the username/password and download a file as follows:
if (docUrl != null)
{
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
this.WebClientInstance.Credentials = new NetworkCredential(username, password);
fileData = this.WebClientInstance.DownloadData(docUrl);
this.WebClientInstance.Dispose();
isDataDownloaded = true;
}
WebClientInstance is a System.Net.WebClient. I debugged and verified that it is hitting the line to set credentials. Instead of downloading the PDF, I end up with an HTML page that prompts me to log in to get access to the file. I have verified that the username/password is correct. I use the same credentials to scrape the website with WatiN.
Is there something else that I'm supposed to be doing here?
UPDATE
Okay, I've done some sniffing around and found some useful info on this issue. I still haven't gotten it to work, but I think I'm closer. First, you need to create a cookie aware WebClient that extends the WebClient class, as follows:
public class CookiesAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public CookiesAwareWebClient()
{
this.CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
if (webRequest is HttpWebRequest)
(webRequest as HttpWebRequest).CookieContainer = this.CookieContainer;
return webRequest;
}
}
Next is to use the WebClient.UploadValues() method to upload the login info to the target website. The full process of authenticating and downloading the target resource is as follows:
using (var webClient = new CookiesAwareWebClient())
{
var postData = new NameValueCollection()
{
{ "userId", username },
{ "password", password }
};
webClient.UploadValues(docUrl, postData);
fileData = webClient.DownloadData(docUrl);
}
I was wrong about the site using forms auth. It is a JSP website and uses a JSESSIONID. I have verified that I am getting a cookie back with what appears to be a valid 32-byte JSESSIONID value.
However, when I call WebClient.DownloadData() it is still only returning the redirected login page. I've tried to fix this by setting the AllowAutoRedirect property on the HttpWebRequest to false, but then it returns 0 bytes.
Is there something else that I need to do so it won't redirect and will take me to the resource once I have authenticated?
(Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Solved. So the problem was between my ears. I was passing in the URL for the secure resource to the .UploadValues() method, knowing that it would redirect to the login page. However, I really needed to pass in the URL from the login form (where it goes upon submitting) - not the login page itself. Once I did that, it worked correctly. I think I'm going to go find a career in food service now.
LINKS
There were already a few questions posted on SO that addressed this issue. I just didn't know what I was looking for at first so I didn't see those... Anywhere here are a couple good resources that I came across when working on this issue:
how to maintaine cookies in between two Url's in asp.net
Trying to get authentication cookie(s) using HttpWebRequest

login automatically with Grails & Acegi

I'm using the Acegi plugin in my Grails app. After a user registers, he is redirected to an action that is protected. Therefore, he is shown the login form.
However, I would prefer if the user was automatically logged in as soon as he completes registration. It seems like I could achieve this by redirecting to the action that the login form uses
redirect(uri:"/j_acegi_security_check?j_username=${username}&j_password=${passed}")
But this would send a HTTP request to the client (and back to the server) which shows the user's password. Is there a way I can login automatically in a secure fashion?
Thanks,
Don
If you generate the controller classes for the spring security plugin (grails generate-registration) you'll see the following lines in RegisterController which does just what you want:
class RegisterController {
def daoAuthenticationProvider
...
def save = {
...
def auth = new AuthToken(person.username, params.passwd)
def authtoken = daoAuthenticationProvider.authenticate(auth)
SecurityContextHolder.context.authentication = authtoken
redirect uri: '/'
}
Be sure that params.passwd is the plain-text password (i.e. not hashed) and it works like a charm.
I haven't tried this with non-test code, but this is the method that I created to log a user in within my integration tests (after building/saving the appropriate users/roles in my test setup):
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsDaoAuthenticationProvider
import org.springframework.security.providers.UsernamePasswordAuthenticationToken
import org.springframework.security.context.SecurityContextHolder
...
def logInAsUser(username, password) {
daoAuthenticationProvider.getUserCache().removeUserFromCache(username)
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password)
SecurityContextHolder.context.authentication = daoAuthenticationProvider.authenticate(token)
}
I construct and inject the authentication token in the security context. There might be a little more that you need to do to get your user logged in and past security, but this would be the start of whatever that is.
I'll actually need to do exactly what you're asking in a week or two for my current app, post back if you figure it out fully before I do :).
This is Burt Beckwith's answer (not mine)
(It was left as a comment by Burt, but I think it deserves to be more prominent)
If you don't have the password, you can load the user via
def user = User.findByUsername(username)
and setting the authority array in the 3-parameter constructor. Create the auths via
GrantedAuthority[] auths = user.authorities.collect { new GrantedAuthorityImpl(it.authority) }
Then you can omit the call to authenticate() and use:
SecurityContextHolder.context.authentication = new UsernamePasswordAuthenticationToken(username, 'unknown', auths)

Resources