Friday, February 21, 2014

AWS Web Identity Federation for Mobile Apps - Amazon (3 of 3 series)

This is last part of a three part series. You may want to read about basic introduction and Facebook authentication and Google authentication before reading this blog. In this blog, I will cover the Amazon authentication in this blog.

Prerequisites

·         Sign up for AWS and get the AccessKey & SecretKey. You can find the info about AWS Account and Access Keys here.
·         Have Visual Studio installed, I used Visual Studio 2013. Although I did not test it, earlier version should work.
·         Install AWS SDK for .Net from here follow the “Getting Started” instructions.

Overview

1.       Register your application and note down the app ID and client ID. Unlike Facebook/Google, you need these two.
2.       Create a role in AWS, this is the role the user will be impersonated.
3.       The app includes logic to make https request to https://www.amazon.com/ap/oa and to get back a token (or code) from the provider.
4.       The app calls AssumeRoleWithWebIdentity without using any AWS security credentials. The call includes the token received from the provider previously.
5.       AWS STS is able to verify that the token passed from the app is valid and then returns temporary security credentials to the app. The mobile app's permissions to access AWS are established by the role that the app assumes.

Register Application

Create an app at App Console. Save the client ID and client secret in the app.config as described below. You should also define the redirect URL, only https is supported. I chose to use https://google.com. This is the only redirect URL allowed to receive the token.


Create an AWS Role

This is the role that an Amazon authenticated user will assume. The role is associated with two things a) trust policy – who can assume this role and b) access policy – what permission does the assumed user have.

C# code below creates a role. Normally, this is manually created once. I chose to write C# code because it is handy for automation. This role can be assumed by any authenticated Amazon user. The user only has access to their specific key which is located under “federationbucket/Amazon/”. Code below is slightly complicated because the same code works for all the identity providers (i.e.) Facebook/Google/Amazon.

    providerURL = "www.amazon.com";
    providerAppIdName = "app_id";
    providerUserIdName = "user_id";

    //identity provider specific AppId is loaded from app.config (e.g)
    //  FacebookProviderAppId. GoogleProviderAppId, AmazonProviderAppId
    providerAppId = ConfigurationManager.AppSettings[identityProvider +
                                                        "ProviderAppId"];

    // Since the string is passed to String.Format, '{' & '}' has to be escaped.
    // Policy document specifies who can invoke AssumeRoleWithWebIdentity
    string trustPolicyTemplate = @"{{
            ""Version"": ""2012-10-17"",
            ""Statement"": [
                {{
                        ""Effect"": ""Allow"",
                        ""Principal"": {{ ""Federated"": ""{1}"" }},
                        ""Action"": ""sts:AssumeRoleWithWebIdentity"",
                        ""Condition"": {{
                            ""StringEquals"": {{""{1}:{2}"": ""{3}""}}
                        }}
                }}
            ]
        }}";

    // Defines what permissions to grant when AssumeRoleWithWebIdentity is called
    string accessPolicyTemplate = @"{{
            ""Version"": ""2012-10-17"",
            ""Statement"": [
            {{
                ""Effect"":""Allow"",
                ""Action"":[""s3:GetObject"", ""s3:PutObject"", ""s3:DeleteObject""],
                ""Resource"": [
                        ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}"",
                        ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}/*""
                ]
            }}
            ]
        }}";

    // Create Trust policy
    CreateRoleRequest createRoleRequest = new CreateRoleRequest
    {
        RoleName = "federationtestrole",
        AssumeRolePolicyDocument = string.Format(trustPolicyTemplate,
                                                    identityProvider,
                                                    providerURL,
                                                    providerAppIdName,
                                                    providerAppId)
    };
    Console.WriteLine("\nTrust Policy Document:\n{0}\n",
        createRoleRequest.AssumeRolePolicyDocument);
    CreateRoleResponse createRoleResponse = iamClient.CreateRole(createRoleRequest);

    // Create Access policy (Permissions)
    PutRolePolicyRequest putRolePolicyRequest = new PutRolePolicyRequest
    {
        PolicyName = "federationtestrole-rolepolicy",
        RoleName = "federationtestrole",
        PolicyDocument = string.Format(accessPolicyTemplate,
                                        identityProvider,
                                        providerURL,
                                        providerAppIdName,
                                        providerAppId,
                                        providerUserIdName)

    };
    Console.WriteLine("\nAccess Policy Document (Permissions):\n{0}\n",
                                        putRolePolicyRequest.PolicyDocument);
    PutRolePolicyResponse putRolePolicyResponse = iamClient.PutRolePolicy(
                                                        putRolePolicyRequest);

Above code assumes an app.config file to contain the following values.
    <appSettings>
        <add key="AWSAccessKey" value="YOUR_ACCESS_KEY_A134" />
        <add key="AWSSecretKey" value="YOUR_SECRET_KEY_HERE_SECRET_KEY_HEREndgN" />
        <add key="AWSRegion" value="us-east-1" />
        <add key="AmazonProviderAppId"
             value="amzn1.application.your_app_id_here_your_appid_here" />
        <add key="AmazonProviderClientId"
             value="amzn1.application-oa2-client.your_client_id_here_client_id_ab" />
    </appSettings>

Trust Policy document produced by the above code:
{
  "Version": "2012-10-17",
  "Statement": [
     {
       "Effect": "Allow",
       "Principal": { "Federated": "www.amazon.com" },
       "Action": "sts:AssumeRoleWithWebIdentity",
       "Condition": {
         "StringEquals": {"www.amazon.com:app_id":
                     "amzn1.application-oa2-client.your_client_id_here_client_id_ab"}
          }
      }
    ]
}

Access Policy document (permissions) produced by the above code:
{
    "Version": "2012-10-17",
    "Statement": [
       {
         "Effect":"Allow",
         "Action":["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
         "Resource": [
           "arn:aws:s3:::federationtestbucket/Amazon/${www.amazon.com:user_id}",
           "arn:aws:s3:::federationtestbucket/Amazon/${www.amazon.com:user_id}/*"
          ]
       }
    ]
}

Authenticate with Amazon and get the token

The authorization sequence begins when your application redirects a browser to Amazon URL (https://www.amazon.com/ap/oa); the URL includes query parameters that indicate the type of access being requested. Amazon handles user authentication, session selection, and user consent. The result is an authorization code, which Amazon returns to your application in a query string.

The code below constructs the query and makes the http call to retrieve the token directly. The GET action is performed in the browser control. If the authentication succeeds, it will be redirected to the URL specified in the query (This redirect URL has to be pre-configured as described above). The C# code below uses the Forms based WebBrowser control to automate this process. As soon as the token is retrieved, the browser control is closed. The structure of the query is pretty straight forward. It can be inferred by looking at the code below.

    string query = "https://www.amazon.com/ap/oa?" +
                    string.Format("client_id={0}&", client_id) +
                    "response_type=token&" +
                    "scope=profile&" +
                    "redirect_uri=https://www.google.com";

The GetToken helper function, does GET operation and retrieves the token from the redirected URL.
    class MyWebBrowser : WebBrowser
    {
        public string CapturedUrl;
        string token;
        public MyWebBrowser(string token)
        {
            this.token = token + "=";
        }

        protected override void OnDocumentCompleted(
            WebBrowserDocumentCompletedEventArgs e)
        {
            base.OnDocumentCompleted(e);
            string st = e.Url.ToString();
            if (st.Contains(token))
            {
                // hack, closing the form here does not work always.
                this.Navigate("about:blank");
                this.CapturedUrl = st;
                Console.WriteLine("Captured: {0}", st);
            }
            else if (st == "about:blank")
            {
                ((Form)this.Parent).Close();
            }
        }
    }

    string GetToken(string token, string url)
    {
        Form f = new Form();
        MyWebBrowser wb = new MyWebBrowser(token);
        wb.Dock = DockStyle.Fill;
        f.Controls.Add(wb);
        wb.Navigate(url);
        f.WindowState = FormWindowState.Maximized;
        f.ShowDialog();

        string st = wb.CapturedUrl;
        f.Dispose();

        if (st == null)
            throw new Exception("Oops! Error getting the token");

        int index = st.IndexOfAny(new char[] { '?', '#' });
        st = index < 0 ? "" : st.Substring(index + 1);
        NameValueCollection pairs = HttpUtility.ParseQueryString(st);

        string tokenValue = pairs[token];
        Console.WriteLine("TOKEN={0}, Value={1}", token, tokenValue);
        return tokenValue;
    }

Get Temporary Credentials with AssumeRoleWithWebIdentity

Key concept to grasp here is, you start with anonymous AWS credentials, pass the token received from Amazon and get the temporary credentials. This is important because the mobile app user will not have any AWS credentials.
    public AssumeRoleWithWebIdentityResponse GetTemporaryCredentialUsingAmazon(
        string client_id,
        string role)
    {
        string query = "https://www.amazon.com/ap/oa?" +
                        string.Format("client_id={0}&", client_id) +
                        "response_type=token&" +
                        "scope=profile&" +
                        "redirect_uri=https://www.google.com";

        AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest =
            new AssumeRoleWithWebIdentityRequest ()
            {
                ProviderId = "www.amazon.com",
                WebIdentityToken = GetToken("access_token", query),
                RoleArn = role
            };
        return GetAssumeRoleWithWebIdentityResponse(
            assumeRoleWithWebIdentityRequest);
    }

References


You can find the code under “AWS\AWS CSharp Test” folder at https://github.com/padisetty/Samples.

Explore & Enjoy!

/Siva

114 comments:

  1. Thank you for your comment, feel free to suggest useful topics.

    ReplyDelete
  2. nice piece of information, I had come to know about your internet site from my friend vinay, delhi,i have read atleast 12 posts of yours by now, and let me tell you, your website gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new post, once again hats off to you! Thanx a ton once again, Regards, obiee training in hyderabad

    ReplyDelete
  3. If you develop any app then its very important to test it, whether it is working properly or not, the user interface, the icons, the layout everything is needed to be tested any if there is any bug issues then it has to be resolved at the earliest. Testing an app is as important as developing an app.
    mobile application testing

    ReplyDelete
  4. Useful post.Mobile application testing is a procedure by which application programming produced for handheld cell phones is tested for its consistency, functionality and usability.
    Thanks,
    Mobile Testing Training in Chennai | Mobile Testing Training | Mobile Apps Testing

    ReplyDelete
  5. Mobile apps can help increase brand awareness and also make people more loyal. It's simple, when your company's name or logo is on the user's mobile screen, they will find it difficult to forget or neglect it. Make money

    ReplyDelete
  6. Compose a digital book, enroll for a free Amazon.com account, visit the computerized content stage, enter in your item depiction, undercover your digital book to advanced content, set your offering cost, and distribute.Click here

    ReplyDelete
  7. Code below creates a role. Normally, this is manually created once.Web design

    ReplyDelete
  8. So coming off several posts on DevOps and how its practices combined with agile development can lead to an improved execution, I thought to share some incites on how to recognize and improve IT culture.devops openings in hyderabad

    ReplyDelete
  9. Hi, I have read your blog. Really very informative and excellent post I had ever seen about AWS. Thank you for sharing such a wonderful blog to our vision. Learn AWS Training in Chennai to know more details about this technology.
    Web Designing Training in Chennai | Dot Net Training in Chennai

    ReplyDelete
  10. Hello admin, I have read your blog, it was very nice to read & I am getting useful information’s through your blog. Keep update your blog. AWS Training in Bangalore | Big Data Hadoop Training in Bangalore

    ReplyDelete
  11. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Aws Online Training

    ReplyDelete
  12. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us.
    AWS Training in Chennai | Best AWS Training in Chennai

    ReplyDelete
  13. The creator has so delightfully enchanted the thought of group by this brilliant blog.Web design in Bellevue NE

    ReplyDelete
  14. Utilization of refined and mesmeric is all that is expected to deliver such a grand blog.
    phone tracker

    ReplyDelete
  15. Established in 2013 to provide exciting, effective design solutions. Since its inception, Globalwebsolution has grown considerably into a recognised brand design and digital marketing innovator. Rewarding our clients with compelling visual solutions that create value and recognition in their marketplace.

    ReplyDelete
  16. The creator has so delightfully enchanted the thought of group by this brilliant blog
    AWS Jobs in Hyderabad .

    ReplyDelete
  17. Informative post! I really like and appreciate your work, thank you for sharing such a useful facts and information about Web Identity Federation, hear i prefer some more information about digital marketing training institute in hyderabad

    ReplyDelete
  18. It’s always so sweet and also full of a lot of fun for me personally and my office colleagues to search your blog a minimum of thrice in a week to see the new guidance you have got.

    Java Training in Bangalore|

    ReplyDelete
  19. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    I’ve bookmarked your site, and I’m adding your RSS feeds to my Google account.
    hadoop training in bangalore

    ReplyDelete
  20. • Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site........."Devops Training in Bangalore"

    ReplyDelete
  21. I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.
    web design training in chennai

    ReplyDelete
  22. Please let me know if you’re looking for an author for your site. You have some great posts, and I think I would be a good asset. If you ever want to take some of the load off, I’d like to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks.
    aws training in marathahalli|

    ReplyDelete
  23. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.
    selenium training in bangalore|
    selenium training in chennai|

    ReplyDelete
  24. Thanks a lot very much for the high quality and results-oriented help.
    I won’t think twice to endorse your blog post to anybody who wants
    and needs support about this area.


    AWS Training in Chennai


    AWS Training in Bangalore


    AWS Training in Bangalore

    ReplyDelete
  25. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.

    QlikView Training in Chennai
    Informatica Training in Chennai
    Python Training in Chennai
    AngularJS Training in Chennai

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Hello admin, I have read your blog, it was very nice to read & I am getting useful information’s through your blog. Keep update your blog

    AWS Training in Chennai

    ReplyDelete
  29. This is amazing! I'll be recommending this website to my friends for more interesting contents, keep them coming! If you need to company secretarial services services, check out the best business incorporation provider! The top singapore company incorporation!

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    rprogramming training in chennai

    ReplyDelete
  32. Informative post! I really like and appreciate your work, thank you for sharing such a useful facts and information about Web Identity Federation, hear i prefer some more information about


    aws training in bangalore



    aws training in chennai


    ReplyDelete
  33. Nice post about MSBI, looking for best msbi online training institute ?

    ReplyDelete
  34. This is very good blog for learners, Thanks for sharing valuable content on MSBI Online Training

    ReplyDelete
  35. As I read the blog I felt a tug on the heartstrings.
    link building services company

    ReplyDelete
  36. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. The Sims Mobile Hack

    ReplyDelete
  37. They are not going to share our site with others since it looks cool, however they will share when our business site encourages them and teaches them about our industry and how to settle on the best decision for their necessities. Edkent Media

    ReplyDelete

  38. In the event that that is the situation and you're endeavoring to get in the best position in the outcomes, you could wind up paying through the nose cheapest link building service

    ReplyDelete
  39. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    amazon-web-services-training-institute-in-chennai

    ReplyDelete
  40. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.


    Amazon Web Services Training in Chennai


    ReplyDelete
  41. I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article... unlockmobiledevice

    ReplyDelete
  42. informative blog thanks for providing such a great information.
    Aws Training in Hyderabad

    ReplyDelete
  43. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    white label website builder

    ReplyDelete
  44. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.


    AWS Certified Developer

    AWS Interview Questions

    Aws Azure Job Opening

    Aws Freshers Opening in Chennai and Bangalore

    ReplyDelete
  45. In reality, however both web designers developers must be good with people, albeit for different reasons. The website designer must be good with people so that he/ she can deal with their individual needs and translate these needs into a workable design. http://hmmedia.uk/Blog/website-traffic/

    ReplyDelete
  46. Great post! Thanks for sharing this valuable information.

    Web Designing Training in Chennai

    ReplyDelete
  47. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..

    aws training in chennai

    digital marketing training in chennai

    ReplyDelete
  48. Very useful information to everyone thanks for sharing, learn the latest updated Technology at Best Training institutions
    Salesforce Lightning is the latest updated technology
    Best Salesforce Training in Hyderabad
    Salesforce Online Training in Bangalore

    ReplyDelete
  49. Mau menang banyak dengan modal sedikit..
    Ayo gabung di Agen Domino CROWNQQ.
    =>Bonus Refferal 20%
    =>Bonus Turn Over 0,5%
    =>Min Deposit Rp20.000
    =>1 User ID 8 Games
    Situs yang bisa memberikan kemenangan AGEN BANDARQ
    raih kemenangan anda segera...
    WHATSAPP : +855967646513
    PIN BB : 2B382398

    ReplyDelete
  50. Nice post keep do posting The Info was too good, for more information regarding the technology Click


    aws training in chennai

    selenium training in chennai

    ReplyDelete
  51. This comment has been removed by the author.

    ReplyDelete
  52. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Digital marketing course in chennai

    ReplyDelete
  53. Thankyou for sharing the data which is beneficial for me and others likewise to see. lesmeilleursvpn

    ReplyDelete
  54. Great work. Quite a useful post, I learned some new points here.I wish you luck as you continue to follow that passion.

    AWS Training
    AWS Training in Chennai

    ReplyDelete
  55. I am all that much satisfied with the substance you have specified. I needed to thank you for this extraordinary article.  privacidadenlared.es

    ReplyDelete
  56. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us. Do check Six Sigma Training in Bangalore | Six Sigma Training in Dubai & Get trained by an expert who will enrich you with the latest trends.

    ReplyDelete
  57. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. vpnforexpats.com

    ReplyDelete
    Replies
    1. Thanks for sharing,
      I am expat in New Zealand, and here many sites are blocked, I have found the guide about New Zealand VPN, Can you guys suggest me which VPN I can signup for New Zealand.

      Delete
  58. I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post. lemigliorivpn.com

    ReplyDelete
  59. I think things like this are really interesting. I absolutely love to find unique places like this. It really looks super creepy though!! R Programming Course Fees

    ReplyDelete
  60. I don’t have time to go through it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the awesome job.
    best safety course in chennai

    ReplyDelete
  61. This comment has been removed by the author.

    ReplyDelete

  62. Great work. Quite a useful post, I learned some new points here.I wish you luck as you continue to follow that passion.

    Cloud Training
    Cloud Training in Chennai

    ReplyDelete
  63. Thanks For sharing such a wonderful Blog on RPA. This blog contains so much of data about RPA that anyone who is searching for RPA, its really helpful for them to grab this data from your blog on RPA. Again thank you so much for your blog on RPA.
    Thanks and Regards,
    blue prism training in chennai
    Best blue prism training in chennai
    blue prism training cost in chennai

    ReplyDelete
  64. Nice post. I was checking constantly this blog and I’m impressed! Extremely useful info specially the last part I care for such information a lot. I was seeking this certain info for a long time. Thank you and good luck. wallmart blockchain jobs

    ReplyDelete
  65. Your blog on RPA is so attractive that i am not able to stop myself to read this blog of yours on RPA.This blog contains all the important topics and points of RPA. Requesting you keep updating this post on RPAand help them who is eager to gain knowledge on RPA.
    Thanks and Regards,
    Uipath training in chennai
    blue prism training institute in chennai
    blue prism training with certification in chennai

    ReplyDelete
  66. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.


    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai | trending technologies list 2018

    ReplyDelete
  67. Anyhow I am here now and would just like to say thanks a lot for a tremendous post and an all-round exciting blog
    safety course in chennai

    ReplyDelete
  68. A debt of gratitude is in order for the significant data and experiences you have so given here... https://vpnveteran.com/

    ReplyDelete
  69. I came onto your blog while focusing just slightly submits. Nice strategy for next, I will be bookmarking at once seize your complete rises...
    mason soiza

    ReplyDelete
  70. Your texts on this subject are correct, see how I wrote this site is really very good.
    mason soiza

    ReplyDelete
  71. This information is impressive. I am inspired with your post writing style & how continuously you describe this topic. Eagerly waiting for your new blog keep doing more.
    Android Classes in Bangalore
    Android Development Training in Bangalore
    Android Development Course in Bangalore
    Best Android Training in Bangalore
    Aws Classes in Bangalore
    Aws Cloud Training in Bangalore

    ReplyDelete
  72. Such an excellent and interesting blog, Do post like this more with more information, This was very useful, Thank you.
    Airport management courses in chennai
    airlines training chennai
    airline academy in chennai
    Airline Courses in Chennai

    ReplyDelete