Friday, October 14, 2016

Amazon API GW integration with WSO2 IS for OAuth 2.0 token validation

In this blog thought of discussing another interesting topic which is relate token validation and how you can register a custom Authorizers via lambda functions to the Amazon API Gateway and use WSO2 Identity Server as authorization server.

  So, Following steps will guide you on how to use WSO2 IS as a custom authorize for Amazon APIs.

Setup WSO2 Identity Server
  • We will be generating tokens in WSO2 IS and using them to call APIs configured in Amazon API Gateway Preparing WSO2 IS And Generating tokens 
  • When testing WSO2 IS for Amazon API Gateway, we used OAuth 2.0 Token Introspection API. You need host  (introspect.war) ​ that you need to deploy in IS. 
  • The source for this is found in [1]
    • Extract the downloaded zip file to a convenient file location. This distributed folder (by default the folder name is wso2is-5.2.0​ ) will be referred to as throughout the document.
    • Copy introspect.war file to /repository/deployment/server/webapps location. In order to generate an access token we need to create an Oauth2 application and get client credentials from there
    • Start the server and login to the management console with admin:admin credentials. Steps to start the product are in [2]. Also you can find the complete installation guide in [3] Note : In order to be accessed by Amazon Gateway Lambda function, this up and running Identity Server should be hosted with a public URL 4. In the main menu in management console, click “Add” under Service Provider
  • Give a Service Provider name and click Register. You will see the Service Provider
    Configuration page.
  • Expand Inbound Authentication Configuration​ panel.
  • Expand the OAuth/OpenID Connect Configuration​ and click Configure.
  • Fill in the form that appears. For the Allowed Grant Types​ you can disable the ones you do not require or wish to block.
  • Use following request to generate tokens with password grant type
 Replace and values with admin. Replace with Base64 encoded values

curl -k -d
"grant_type=password&username=<USERNAME>&password=<PASSWORD>&scope=<SCOPE>"​ ​-H
"Authorization: Basic <ENCODED_KEY>"​ ​-H "Content-Type:
application/x-www-form-urlencoded"
https://<IS_HOST>t:<IS_HTTPS_PORT>/oauth2/token
will have a response similar to,
curl -k -d "grant_type=password&username=admin&password=admin&scope=default "​ ​-H
"Authorization: Basic
X1ZpREJUMWJUSHF5eXFfR1Y0UWJoc0V6X1IwYTpLdzIxV1JPRmYyeTc4RGViMXY0UGpoRkdydGhq"​ ​-H
"Content-Type: application/x-www-form-urlencoded"
https://localhost:9443/oauth2/token
This will have a response similar to,
{
 "scope": "default"
 "token_type": "Bearer"
 "expires_in": 956
 "refresh_token": "23444-dff-32b0-b4cf-7dc7d8fd8205"
 "access_token": "455533ed-d222-3b0e-9512-fec0b94c1592"
}

  • We will use this access_token value when invoking APIs in AWS side.

Configuring Amazon API Gateway

  • Goto Lambda console in Amazon API Gateway and create new Lambda function.

  • This function should call Token Introspection API of WSO2 IS Server. I have attached a sample lambda function (Lambda.js) which is calling this API. You can copy the source of this file and
console.log('starting lambda');
var http = require('http');
exports.handler = function(event, context) {
    var tkn = event.authorizationToken;
 var postData = 'token='+tkn;
 console.log(postData);

 var options = {
   hostname: 'ip.address',
   port: 9763,
   path: '/introspect',
   method: 'POST',
   headers: {
     'Content-Type': 'application/x-www-form-urlencoded'
   }
 };

 var req = http.request(options, (res) => {
   console.log(`STATUS: ${res.statusCode}`);
   console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
   res.setEncoding('utf8');
   res.on('data', (chunk) => {
     console.log(`BODY: ${JSON.stringify(chunk)}`);
  validationReq(chunk,event,context);
   });
   res.on('end', () => {
     console.log('No more data in response.');
   });
 });

 req.on('error', (e) => {
   console.log(`problem with request: ${e.message}`);
 });

 // write data to request body
 req.write(postData);
 req.end();

}

var validationReq = function (obj,evt,ctx) {
    console.log(obj);
    obj = JSON.parse(obj);

    var bool = obj['active'];
 if(bool) {
     console.log('Token verified');
     ctx.succeed(generatePolicy('user', 'Allow', evt.methodArn));
 } else {
     ctx.fail("Unauthorized");
 }
 
}


var generatePolicy = function(principalId, effect, resource) {
    var authResponse = {};
    console.log(resource);
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; // default version
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; // default action
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    return authResponse;
}






  • Copy it as the Lambda function code. Note that you have to replace <host_name of publiclyhosted wso2 is> and <port of publicly hosted wso2 is> values with actual host and port before using it.
  •  Save the Lambda function.
  • Follow Configure Custom Authorizer Using the API Gateway Console ​in [1] When creating the custom authorizer, make sure you give Lamba Region and Lambda Function details according to the function you created in Step 1.







  • After above configurations are done, you should have an API deployed in Amazon API
  • Gateway which is configured to use the custom authorizer which calls WSO2 IS to authorize. 
  • Invoke this API giving the access_token obtained from WSO2 IS as the Identity token source header value you configured when above step.
 Note:- How Please refer OAuth 2.0 Token Introspection API for WSO2 Identity Server to understand how introspect API calls would validate the access tokens and responses
Empty token
curl -k -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=' https://localhost:9443/introspect
Response: {"active":false} 
Invalid token: 
curl -k -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=Bjhk98792k9hkjhk' https://localhost:9443/introspect 
Response: {"active":false,"token_type":"bearer"} 
Get a valid token: 
curl -v -X POST --basic -u client_id:client_secret -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -k -d "grant_type=client_credentials" https://localhost:9443/oauth2/token Validate the token:
curl -k -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=99f0a7092c71a6e772cbcf77addd39ea' https://localhost:9443/introspect 
   Response: 
   { "username":"admin@carbon.super", 
     "nbf":3272, 
     "active":true, 
     "token_type":"bearer", 
     "client_id":"LUG28MI5yjL5dATxQWdYGhDLSywa" 
   } 

[1] https://github.com/facilelogin/aratuwa/tree/master/api-security/org.wso2.carbon.identity.oauth.introspection
[2] https://docs.wso2.com/display/IS520/Running+the+Product
[3] https://docs.wso2.com/display/IS520/Installation+Guide
[4] http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html

90 comments:

  1. I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else! Regards aws jobs in hyderabad.

    ReplyDelete
  2. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Best Hadoop Training Institute In chennai

    ReplyDelete
  3. WSO2 currently using some of the organization as API Gateway. This tips really helps for implementation of security gateway in AWS.

    Java Training in Chennai | Python Training in Chennai

    ReplyDelete
  4. like WSO2, Mule Also one of best tool for API implementation, to learn Mule ESB Online Training contact us Orange TechnoMind

    IBM Training and Support

    ReplyDelete
  5. Enjoyed reading the article above , really explains everything in detail,the article is very interesting and effective.Thank you and good luck for the upcoming articles...
    Good Vacation Classes in Chennai | Best Summer Course in Porur

    ReplyDelete
  6. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here. aws training in chennai

    ReplyDelete
  7. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    aws training in chennai

    advanced aws training in chennai



    aws training in velachery

    ReplyDelete
  8. Thanks for your contribution in sharing such a useful information. This was really helpful to me. Waiting for your further updates.

    IELTS Coaching in T Nagar | IELTS Training in T Nagar | IELTS Classes in Mylapore Chennai | IELTS Classes in Vadapalani | IELTS Class in Kodambakkam | IELTS Classes in Chennai Saidapet

    ReplyDelete
  9. I am really enjoying reading your well written articles.
    It looks like you spend a lot of effort and time on your blog.
    I have bookmarked it and I am looking forward to reading new articles. Keep up the good work..
    Best IELTS Coaching in Chennai
    IELTS Coaching Center in Chennai
    IELTS Coaching Center in Mumbai
    Best IELTS Coaching Centers in Chennai
    IELTS Classes in Chennai

    ReplyDelete
  10. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    Hadoop Training in Chennai
    Big Data Hadoop Training
    Hadoop training institutes in chennai
    hadoop big data training in chennai
    big data training institute in chennai
    Best Hadoop Training in Chennai

    ReplyDelete
  11. Nice idea,keep sharing your ideas with us.i hope this informations will be helpful for the new learners.
    Java Training
    Best Java Training Institute in Annanagar
    Java Training in Guindy
    Java Courses in Sholinganallur

    ReplyDelete
  12. Awwsome informative blog ,Very good information thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    Airport Ground Staff Training Courses in Chennai | Airport Ground Staff Training in Chennai | Ground Staff Training in Chennai

    ReplyDelete
  13. Nice way of expressing your ideas with us.
    thanks for sharing with us and please add more information's.
    AWS training courses near me
    AWS Training in anna nagar
    AWS Training Institutes in Vadapalani

    ReplyDelete
  14. It is a great post. Keep sharing such kind of useful information.

    Article submission sites
    Education

    ReplyDelete
  15. I have gone through your blog, it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic. Kindly post more like this, Thank You.
    Air hostess training in Chennai
    Air Hostess Training Institute in chennai
    air hostess academy in chennai
    air hostess course in chennai

    ReplyDelete
  16. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    Java Training in Chennai
    Java course in Chennai
    Hadoop Training in Chennai
    Python Training in Chennai
    Java Training in Porur
    Java Training in Adyar
    Java Training in Tnagar

    ReplyDelete
  17. This is really too useful and have more ideas and keep sharing many techniques. Eagerly waiting for your new blog keep doing more.
    Regards,
    Tableau training in Chennai | Tableau Courses Training in Chennai | Tableau training Institute in Chennai

    ReplyDelete
  18. Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on
    updating...

    securityguardpedia
    Article submission sites

    ReplyDelete

  19. I recently visited your blog and it is a very impressive blog and you have got some interesting details in this post. Provide enough knowledge for me. Thank you for sharing the useful post and Well do...
    Corporate Training in Chennai
    Corporate Training
    Power BI Training in Chennai
    Unix Training in Chennai
    Linux Training in Chennai
    Pega Training in Chennai
    Oracle DBA Training in Chennai
    job Openings in chennai
    Corporate Training in Porur
    Corporate Training in T Nagar

    ReplyDelete
  20. Keywords drive potential customers to your product, thus it is important to try to add product specific keywords to your Amazon product description as well as anywhere else that you may be writing about your product. Younglanes All kinds of feedback can be useful for the seller.

    ReplyDelete
  21. Items From Wholesalers - The conventional retail business model, you could source items from wholesalers or makers and sell them with an increase on Amazon.Start ranking on Amazon

    ReplyDelete
  22. Your info is really amazing with impressive content..Excellent blog with informative concept. Really I feel happy to see this useful blog, Thanks for sharing such a nice blog..
    If you are looking for any python Related information please visit our website Python Training In Bangalore page!

    ReplyDelete
  23. Sometimes you may need to check a keyword tool to make sure you are finding relevant keywords and phrases to use as tags. check this Most marketing and advertising costs big money, but the only cost of SEO is how much time you spend learning SEO strategies and writing content, or paying an SEO specialist to improve your Google rankings.

    ReplyDelete
  24. Loaded with superb and virtuosic words.Powerful is all that is in this blog.
    how to set up alexa

    ReplyDelete
  25. Excellent post. I have read your blog it's very interesting and informative. Keep sharing.
    Best JAVA / J2EE / J2ME Course Training Institute in kanchipuram|

    ReplyDelete
  26. Nice post.. Really you are done a wonderful job. Thanks for sharing such wonderful information with us. Please keep on updating...
    Best C & C++ Course Training Institute in kanchipuram|

    ReplyDelete
  27. Lower overheads. You'll need to do the figures but, in most cases, there can be good cost savings. With FBA you won't need premises for storage, s click here now

    ReplyDelete
  28. Very nice post here and thanks for it .I always like and such a super blog of these post.Excellent and very cool idea and great blog of different kinds of the valuable information's.
    Best Tally Erp 9.0 Course Training Institute in kanchipuram|

    ReplyDelete
  29. Interesting post!!! Thanks for posting such a useful information. I wish to read your upcoming post to enhance my skill set and keep blogging.
    Best Tally Erp 9.0 Course Training Institute in kanchipuram|

    ReplyDelete
  30. This is excellent information. It is amazing and wonderful to visit your

    site.Thanks for sharing this information, this is useful to me.
    Best Selenium

    Automation Course Training Institute in kanchipuram
    |

    ReplyDelete
  31. I have read your blog. Good and more information useful for me, Thanks for sharing this information keep it up....
    Best Dot Net Course Training Institute in kanchipuram|

    ReplyDelete
  32. Really it was an awesome blog...very interesting to read..You have provided an nice information....Thanks for sharing..
    Best Hardware & Networking Course Training Institute in kanchipuram|

    ReplyDelete
  33. Thanks for sharing in this blog...its very useful for us...keep on going...
    Best MS Office Course Training Institute in kanchipuram|

    ReplyDelete
  34. Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it.
    Best PCB (Printed Circuit Board) Course Training Institute in kanchipuram|

    ReplyDelete
  35. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
    Cyber Security Projects for Final Year

    JavaScript Training in Chennai

    Project Centers in Chennai

    JavaScript Training in Chennai

    ReplyDelete
  36. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Best PCB (Printed Circuit Board) Course Training Institute in kanchipuram|

    ReplyDelete
  37. Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it.
    No:1 Tally Training Academy in Kanchipuram

    ReplyDelete
  38. Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it.
    No:1 Hardware and Networking Training Academy in Kanchipuram

    ReplyDelete
  39. Nice blog. Thank you for sharing. The information you shared is very effective for

    learners I have got some important suggestions from it.
    No:1 Azure Training Academy in

    Kanchipuram


    ReplyDelete
  40. Awesome post. Really you are shared very informative information... Thank you for sharing. Keep on updating...
    Best AWS (Advanced Amazon Web Services) Course Training Institute in kanchipuram|

    ReplyDelete
  41. Great post..Its very useful for me to understand the information..Keep on blogging..
    Best Software Testing Course Training Institute in kanchipuram|

    ReplyDelete
  42. Nice..You have clearly explained about the conept..Its very useful for me to undertand..Keep on sharing..

    No:1 Azure Training Academy in Kanchipuram



    ReplyDelete
  43. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Best Cloud Computing Course Training Institute in kanchipuram|

    ReplyDelete
  44. Nice..You have clearly explained about the conept..Its very useful for me to

    undertand..Keep on sharing..

    No:1Tally Training Academy in Kanchipuram







    ReplyDelete
  45. I found some useful information in your blog, it was awesome to read, thanks for sharing this great information to my vision, keep sharing.
    Best Graphic Designing Course Training Institute in kanchipuram|

    ReplyDelete
  46. Marvelous and fascinating information.Thanks for this greatful blog. keep your blog updated.
    Best Hardware & Networking Course Training Institute in kanchipuram|

    ReplyDelete
  47. Thanks a lot for offering this unique post with us. I really enjoyed by reading your blog post.keep sharing.
    Best Python Course Training Institute in kanchipuram|

    ReplyDelete
  48. This is really awesome. Full of knowledge and latest information.Thanks for sharing.
    Best JAVA / J2EE / J2ME Course Training Institute in kanchipuram|

    ReplyDelete
  49. he plan holds down the cost of entering the new market and minimizes various risks that can occur during the process. visit here

    ReplyDelete
  50. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    No:1 Best EEE Project Center in kanchipuram|

    ReplyDelete
  51. really you have posted an informative blog. it will be really helpful to many peoples. thank you for sharing this blog. so keep on sharing such kind of useful blogs.
    No:1 Best NS2 (Network Simulator) Project Center in kanchipuram|

    ReplyDelete
  52. The provided information’s are very useful to me.Thanks for sharing.Keep updating your blog.

    No:1 Networking project Centre in kanchipuram

    ReplyDelete
  53. very usefull informatation.and iam expecting more posts like this please keep updating us....
    No:1 Best Android Project Center in kanchipuram|

    ReplyDelete
  54. This is excellent information. It is amazing and wonderful to visit your site.Thanks

    for sharing this information, this is useful to me…

    No:1Mobile computing Training Center in Kanchipuram









    ReplyDelete
  55. Thanks for this greatful information. all this information is very important to all the users and can be used good at all this process.please keep on updating..
    No:1 Best ECE ( Electronics & Communications Engineering) Project Center in kanchipuram|

    ReplyDelete
  56. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…

    No:1Mobile computing Training Center in Kanchipuram









    ReplyDelete