Menu
  • HOME
  • TAGS

ServiceStack Authenticates both iOS Apps when one is logged in

Tag: rest,xamarin,servicestack,restful-authentication,servicestack-auth

I'm using the awesome ServiceStack to implement my REST backend which serves two iPhone apps written in Xamarin. Everything works great but i'm struggling in getting sessions to work correctly when the two apps are installed on the same device !

The issue is that if I login in one of the apps the second app gets authenticated and doesn't require me to login as a result of 'isCurrentUserAuthenticated()' method below.

I pass cookies with my requests to mimic the browser and to make sure user doesn't have to pass his credentials every time but I guess the problem is that maybe ServiceStack sees two authentication requests from the same IP so it authenticated them both using the first authentication requests succeeds.

Note : The two apps accesses the same database and UserAuth table but every app supports a user role different than the other.

The only way to fix it is to logout from the second app so the user can login again with his credentials to make everything work.

Can you please help with this ?

Here is the code so far :

public static class BLL
{
    public static JsonServiceClient ServiceClient { get; set; }

    public static string HostUri = "http://test.elasticbeanstalk.com";
    public static string HostDomain = "test.elasticbeanstalk.com";

    static BLL ()
    {
        string ss_id = ConfigRepository.GetConfigString ("ss-id");
        string ss_pid = ConfigRepository.GetConfigString ("ss-pid");

        ServiceClient = new  JsonServiceClient (HostUri);

        ServiceClient.CookieContainer.Add (new Cookie ("ss-id", ss_id, "/", HostDomain));
        ServiceClient.CookieContainer.Add (new Cookie ("ss-pid", ss_pid, "/", HostDomain));
    }


    public static async Task<bool> isCurrentUserAuthenticated ()
    {
        bool result = false;

        try {

            Authenticate authRequest = new Authenticate ();

            // Restore the cookie
            var response = await ServiceClient.PostAsync<AuthenticateResponse> (authRequest);

            NSUserDefaults.StandardUserDefaults.SetString (response.UserId, "UserId");
            NSUserDefaults.StandardUserDefaults.Synchronize ();

            result = true;

        } catch (Exception Ex) {
            result = false;
        }

        return result;
    }

    public static async Task<AuthenticateResponse> Login (string userName, string password)
    {
        Authenticate authRequest = new Authenticate () {
            provider = "credentials",
            UserName = userName,
            Password = password,
            RememberMe = true,
        };

        var response = await ServiceClient.PostAsync<AuthenticateResponse> (authRequest);

        var cookies = ServiceClient.CookieContainer.GetCookies (new Uri (HostUri));

        if (cookies != null) {
            var ss_id = cookies ["ss-id"].Value;
            var ss_pid = cookies ["ss-pid"].Value;

            if (!ss_id.IsNullOrEmpty ()) {
                int r = ConfigRepository.AddConfigKey ("ss-id", ss_id);
                System.Diagnostics.Debug.WriteLine ("ss-id " + ss_id.ToString ());
            }
            if (!ss_pid.IsNullOrEmpty ()) {
                int r = ConfigRepository.AddConfigKey ("ss-pid", ss_pid);
                System.Diagnostics.Debug.WriteLine ("ss-pid " + ss_pid.ToString ());
            }
        }

        NSUserDefaults.StandardUserDefaults.SetString (response.UserId, "UserId");
        NSUserDefaults.StandardUserDefaults.Synchronize ();


        return response;
    }

    public static async Task<AuthenticateResponse> Logout ()
    {
        Authenticate authRequest = new Authenticate () {
            provider = "logout"
        };

        var response = await ServiceClient.PostAsync<AuthenticateResponse> (authRequest);
        return response;
    }
}

Best How To :

The issue is because you're using the same Session Cookies with a shared ServiceClient instance which ends up referencing the same Authenticated Users Session.

ServiceStack Sessions are only based on the session identifiers (ss-id/ss-pid) specified by the clients cookies, if you use the same cookies you will be referencing the same Authenticated Users Session, they're not affected by IP Address or anything else.

If you want to authenticate as another user, use a new instance of the ServiceClient (so it's not using an existing Sessions Cookies).

Adding authorization to routes

ruby-on-rails,rest,routes,authorization

Do you know the gems rolify and CanCanCan? I think they can help you manage authorizations on resources in a single place instead of having to do it in every controller....

REST-API Different Content-Type on Error Response

java,json,api,rest,spring-mvc

User should always specify what content it's expecting with Accept header. It's you job to return the error that was thrown/caught on the server side in the format that was specified in Accept header. In spring as far as I know it could be achieved with a special mapper. Below...

.NET web service gets null object

c#,.net,ajax,web-services,rest

Possibly the mistake in this line var data = '{ "c:":{"Id": "1", "Name": "myname"}'; should be var data = '{ "c":{"Id": "1", "Name": "myname"}'; ...

Remove resource wrapper from CakePHP REST API JSON

rest,cakephp,cakephp-2.2

Use the Hash utility to rewrite the results returned before setting the data for the View:- class LeadPostsController extends AppController { public $components = array('RequestHandler'); public function index() { $records = $this->LeadPost->find('all', ['limit' => 20]); $this->set(array( 'leadposts' => Hash::extract($records, '{n}.LeadPost'), '_serialize' => 'leadposts' )); } } Here Hash::extract($records, '{n}.LeadPost') will...

Springboot REST application should accept and produce both XML and JSON

java,xml,rest,jackson,spring-boot

Try to add a @XmlRootElement(name="myRootTag") JAXB annotation with the tag you use as the root tag to the class MatchRequest. I have had similar issues when using both XML and JSON as transport format in a REST request, but using moxy instead of Jackson. In any case, proper JAXB annotations...

Stuck with nested serializer using Django Rest Framework and default user

django,api,rest,django-rest-framework,serializer

By default DRF will look at an attribute on the User model named after the serializer's field (member here). However the related name is profile. This can be worked around by passing the source="profile" to your MemberProfileSerializer....

How to specify supported http operation for a resource in json-ld?

rest,http-method,json-ld

No, you can't specify it in the context. What you can do, however, is to bind an operation to a property in a Hydra ApiDocumentation (example 10 in the spec) and reference it via an HTTP Link header.

Sencha/Extjs rest call with all parameters

json,rest,extjs,sencha-touch

You need to specify a writer config on your proxy with writeAllFields: true. By default it's false, and the default writer itself is just {type: 'json'}.

Consuming and exposing webservices in one project (.NET)

.net,web-services,rest,soap

If you are trying to enrich the data from one source and combine that with information from another source, I think this is a decent solution. I think it is better to have one single point to talk to (your REST service), than to have two in your application and...

namespace prefix “myapp” is not defined in Xamarin While Building App?

android,xamarin,monodroid,xamarin-studio

Why do you use myapp prefix? Use android instead. <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/android-auto"> <item android:id="@+id/action_reply" android:icon="@drawable/ic_action_reply" android:title="Reply" android:showAsAction ="always" /> <item android:id="@+id/action_undo" android:icon="@drawable/ic_action_undo" android:title="Undo" android:showAsAction ="never" /> </menu> ...

Intercepting login calls with Spring-Security-Rest plugin in Grails

rest,grails,spring-security

Yes, you can provide a custom bean that implements the RestAuthenticationSuccessHandler. Take a look at the API documentation for the class to see what you need to implement. Then it's as simple as overriding the bean in your application context: // Resources.groovy restAuthenticationSuccessHandler(MyCustomRestAuthenticationSuccessHandler) { renderer = ref('accessTokenJsonRenderer') } It might...

REST Jersey server JAX-RS 500 Internal Server Error

java,rest,jersey,jax-rs

IllegalAnnotationException: Class has two properties of the same name "list" Look at your two model classes XmlMessageBean and ResponseList. Do you see any difference? The main difference (and the cause for the error), is the @XmlAccessorType(XmlAccessType.FIELD) annotation (or lack there of). JAXB by default will look for the public...

Trying to write a unit test for file upload to a django Restless API

python,django,rest,file-upload,request

I tried to fix this but in the end it was quicker and easier to switch to the Django-REST framework. The docs are so much better for Djano-REST that it was trivial to set it up and build tests. There seem to be no time savings to be had with...

RESTful routing best practice when referencing current_user from route?

ruby-on-rails,rest

I would've added special routes for current user profile actions, in this case you don't have to check anything. Just load and display the data of current user. For example: /my-profile/edit /my-profile/newsfeed It's not that RESTful but you don't have to put extra checks keeping your code clean. If you...

Do we HAVE to generate and use client libraries to use Google App Engine's Endpoints?

ios,swift,rest,google-app-engine,google-cloud-endpoints

Yes, it's totally possible to access endpoints via HTTP requests. The client libraries just help you to generate those requests without having to know the exact URLs. The biggest part where the client libraries help you is for authentication, but if you authenticate with Google and get an access token...

Unable to select values from the select list

javascript,jquery,rest

Here is the working fiddle: https://jsfiddle.net/64djszjf/14/ If you take a look at the source js file: https://aui-cdn.atlassian.com/aui-adg/5.8.13/js/aui-experimental.js, there are few lines that sets unselectable class: populateResults: function(container, results, query) { var populate, id=this.opts.id; populate=function(results, container, depth) { var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; results =...

TableView Header Section Covers The Rows

xamarin,tableview,xamarin.forms

You should use a ListView instead of a TableView. This will allow you to have the custom table headers you are looking for. The default functionality of the headers are to "stick" under the nav bar until the next section header reaches the top. Here is an excellent blog post...

@RestController throws HTTP Status 406

java,spring,rest,maven

The issue is with the dependencies that you have in pom.xml file. In Spring 4.1.* version the pom.xml dependency for Jackson libraries should include these: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1.1</version> </dependency> You...

Link to another resource in a REST API: by its ID, or by its URL?

json,api,rest,api-design,hateoas

DO include absolute entity URIs in your responses (such as /customers/12 or even http://www.example.com/customers/12). DO NOT include just an entity's ID (such as 12) in a response, because that way you're forcing clients to put together resource URIs themselves. In order to do that, they would need to have prior...

Laravel: Retrieve polymorphic attributes efficiently

rest,laravel,polymorphism,eloquent

You might be almost there. Your getAvatarAttribute() is way too complicated, indeed. You could try to do something like: /** we hide the relation from the json */ protected $hidden = ['avatar']; /** we append the url of the avatar to the json */ protected $appends = ['avatar_url']; /** *...

mono - xamarin studio System.MissingMethodException

xamarin,monodevelop

The MissingMethodException is because Mono's System.Web assembly didn't have the equivalent InClientBuildManager property from MS.NET. This is a mono bug, and has been recently fixed in the master branch. So I recommend you to wait for Mono 4.3/4.4 or use the weekly packages provided by Xamarin....

How to manipulate local files with webdav

javascript,jquery,rest,file-upload,webdav

So I figured it out a while ago. I was thinking the wrong way. It is not the client that will do anything it will be the server. So the client can make a regular http call and just change the "type" string from get or what ever to MKCOL...

How can I get json objects without the object number?

javascript,jquery,json,rest

Create an object. Loop over the array Get the name of each member of the array Copy each member into the object using a property name that is the same as the name you just got Then just use the object instead of the array. You might want to...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?

android,xamarin,xamarin.forms

You don't want to use it from assets, even if you could, because assets is a compressed read only file, part of your installation. You can't write updates into it, which kills 90% of database use. And its inefficient for reading as its zipped up. So you really do need...

What's the best way to map objects into ember model from REST Web API?

json,rest,ember.js,asp.net-web-api,ember-data

I think this should fix your problem: export default DS.RESTSerializer.extend({ primaryKey: 'inventory_id' }); With this parameter Ember Data will map inventory_id to it's id parameter....

Mailchimp Ecommerce360 Javascript Implementation

javascript,rest,e-commerce,mailchimp

If you mean from client-side Javascript, this isn't possible because the MailChimp API doesn't support CORS and (in most cases) this is a huge security issue. You'll need to communicate with Javascript back to your own servers and have those machines make the requisite API calls.

Accessing Activity Methods from WebChromeClient

javascript,android,xamarin,webchromeclient

Accept and store a reference of type MainActivity in myWebChromeClient class. Only then can you call the setUpGraph() function in MainActivity. EDIT The myWebChromeClient class: class myWebChromeClient : WebChromeClient { public MainActivity activity; public override void OnProgressChanged(WebView view, int newProgress) { base.OnProgressChanged(view, newProgress); if (newProgress == 100) { activity.setUpGraph(); }...

Spring Data Rest executes query but returns 500 internal Server Error

java,spring,rest,spring-boot,spring-data-rest

Hum... This is strange but I found this question and added a controller to call the method and it worked like a charm... Obv this is not a fix, but it is a good workaround... EDIT: The error happens because it is expecting an entity, so all I had to...

Spring Boot REST display id of parent only in a JSON response

json,spring,rest,spring-boot

Basically returning entities directly from endpoints isn't a good idea. You make very tight coupling between DB model and responses. Instead, implement a POJO class that will be equivalent of the HTTP response you sent. This POJO will have all ChildEntity fields and parentId only and will be constructed in...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

REST API with token based authentication

angularjs,codeigniter,api,rest,token

You can use an API key, however - as you wrote - it's pure protection and easily accessible value - potential abuser just needs to view the source or investigate the queries. In general REST APIs are secured with tokens. At the beginning of the session (not in traditional meaning...

Can't save json data to variable (or cache) with angularjs $http.get

json,angularjs,web-services,rest

$http.get is asynchronous. When cache.get or return result are executed, HTTP request has not completed yet. How are you going to use that data? Display in UI? E.g. try the following: // Some View <div>{{myData}}</div> // Controller app.controller('MyController', function ($scope) { $http.get('yoururl').success(function (data) { $scope.myData = data; }); }); You...

In simple RESTful design, does PATCH imply mapping to CRUD's (ORM's) “update” and PUT to “destroy”+“create” (to replace a resource)?

database,rest,http,orm,crud

Well, Both the actions actually means update, where PUT is full update and PATCH is partial update. In case of PUT you already know the identifier of the resource and the resource already exists, so it is not a create and delete action per se. Infact, you can make do...

REST api : correctly ask for an action

api,rest,endpoint

Try to separate API from your application logic. From API you GET the quote and API from now on shouldn't care what you do with that data. The same with marking quotes as favorites. It's your application's and user db's problem how to mark something. Again, API should care only...

Not able to hit 2nd services with generated Token

c#,web-services,rest,soap,drupal-services

Finally i figured out what was the issue i was creating new cookie container for both the request request.CookieContainer = new CookieContainer(); thus server was unable to authenticate Error was resolved by using this code CookieContainer cookieJar = new CookieContainer(); private void CreateObject() { try { string abc = "";...

remote data fetching inside model object in objective c using AFNetworking

ios,objective-c,rest,model-view-controller,afnetworking-2

I dont have anything to say about your MVC(Model–view–controller) correct? I just want to add something that may be useful approach avoiding unwanted crashes.. First is under [[MyAPI sharedInstance] POST:@"auth/" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) { if([responseObject objectForKey:@"id"]) { [[NSUserDefaults standardUserDefaults] setObject:(NSDictionary*) responseObject forKey:USER_KEY]; [[NSUserDefaults standardUserDefaults] synchronize]; result = [responseObject...

Exception when launching activity from PreferenceScreen

android,xamarin,monodroid,android-preferences

The issue here is that you need to use the [Register] attribute on your Activity. This is required since Xamarin.Android 5.1 as it will otherwise prepend your activities with a MD5 sum, such that the package name is unique. So do something like this: [Register("com.mycompany.myproject.config.actDeviceList")] [Activity(Label = "Device List" ...)]...

AngularJS $resource Custom Action for Requesting a Password Reset

angularjs,rest,ngresource,angularjs-1.3

yes, looks a little bit weird. Instead of GET I will use POST request to reset the password and pass the email param in request body

How to avoid abusive use of REST endpoint [closed]

java,javascript,rest

The answer is simple: Don't use the UI as the definitive state for your users. Stack Overflow is actually a great example of this. When I voted up your question, the UI only updated after the REST call to the backend completed successfully with no errors. So you should be...

Floating Action Button in Xamarin.Forms

android,xamarin,monodroid,xamarin.forms,floating-action-button

Before the official support library came out I ported the FAB over. There is now a Xamarin.Forms sample in my GitHub repo that you can use: https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android...

Unable to upload file to Sharepoint @ Office 365 via REST

javascript,ajax,rest,sharepoint,office365

To me it just seems a bit light, visit this link https://msdn.microsoft.com/en-us/library/office/dn769086.aspx on technet, and compare your upload function to this: // Add the file to the file collection in the Shared Documents folder. function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page....

The runtime version supported by this application is unavailable during app startup

xamarin,monotouch

This is just some debug spew we haven't had time to remove yet. You can safely ignore it....

How to expose existing REST API through Azure Service Bus (or through something else)

rest,azure,azureservicebus

If you want to access an On-Premise service from the Azure service/websites what you need is a Hybrid Connection. For that you will need a BizTalk service to redirect the trafic to your on-prem service. Here are the steps to how to setup a Hybrid connection: https://azure.microsoft.com/en-us/documentation/articles/web-sites-hybrid-connection-get-started/...

How to respond in Middleware Slim PHP Framework

php,rest,authentication,middleware,slim

You cannot use halt in middleware: http://stackoverflow.com/a/10201595/2970321 Halt should only be invoked within the context of a route callback. Instead, you could manually generate a 400 response using PHP's header along with exit: header("HTTP/1.1 400 Access denied"); exit; Alternatively, you could define a new type of Exception: class AuthException extends...

Xamarin.Android and Parse

c#,parse.com,xamarin,monodroid

FindAsync will never return null. It always returns a Task<IEnumerable<T>>. And the result of this task is never null either. If it doesn't find anything, it will return an empty list. Because you are using await you don't actually have to deal with the task. You just have to check...

Default/Constant values for POST/PUT arguments with Retrofit

java,rest,retrofit

Maybe one option would be to send an object, which encapsulates all your values, instead of all string values separately? The object would implement your default values. For example, you could create a class: public class CreateObject { private String type = "constant"; private String value; private String otherValue; public...

Retrofit updating class PUT error code 301

android,rest,retrofit,put

Finally I solved it. The problem was that we had two different Client objects and the one that you fetch is the one that you must change and use it to upload with PUT. I hope that this help somebody....

How to run mtouch command to launch Xamarin.iOS app on simulator for automated testing?

testing,xamarin,monotouch

mtouch -launchsim Hello.app mtouch docs are here On a Mac, the mtouch binary should be here /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mtouch ...

How can I use animation in xamarin android application?

c#,android,xamarin,titanium-android

first add a folder under "resources " folder name it "anim". then you can add your animation resources to it , Ex: for fade-in animation create a resource under anim folder and name it "fade_in.xml" and paste this code into it: <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <alpha android:duration="1000"...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield

As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...