Create Groups in O365 - javascript

Currently i am working on an App which will create groups in Office 365 programatically. I am wondering if this is possible using JavaScript. I also had another question regarding the Authentication and Authorization process. I am able to register the App and fetch the Authorization code. However when i try to fetch the Access token, it throws an error stating that it encountered a bad request. My Authorization URL is of the form:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=<some_client_id>
&scope=openid+profile
&response_type=id_token
&redirect_uri=<some_redirect_url>
&nonce=123456789
And my access token request url is:
https://login.microsoftonline.com/common/oauth2/v2.0/token?
grant_type=authorization_code
&code=<Code_generated_in_above_request>
&redirect_uri=<some_redirect_url>
&resource=https%3A%2F%2Fgraph.microsoft.com%2F
&scope=openid+profile
&client_id=<some_client_id>
&client_secret=<Some_client_secret>
If anyone could help me regarding my doubts, then it would be greatly appreciated. Thanks.

Microsoft Graph from JavaScript
Using Microsoft Graph from JavaScript works. HTTP requests to the REST endpoints with a valid access token will work great. You might also want to check out KurveJS (github:MicrosoftDX/kurvejs) for a simple library (handles authentication and some graph operations).
Authentication
If you are attempting client-side implicit flow, you can pass 'response_type=id_token+token' and avoid the second call. This will return you an access token in the resulting payload.
If you are attempting server-side authentication, you should pass 'response_type=code' and then make the second call for the access token with the resulting code.
References:
v2.0 Protocols - SPAs using the implicit flow
v2.0 Protocols - OAuth 2.0 Authorization Code Flow

Related

Html vs JSP - get request header token value

I am working on Java application . Front end would be Angular2 .
If I try to open my application home page( index.html is configured in web.xml as default page ) . Access URL should be http://localhost:8080/MyWebApp .
Then I have taken into an standard organization's login page for authentication. If authentication succes , HTTP Authorization token will be set in the request header and finally control comes to display my application home page.
If I use jsp, I can get request header as,
String authHeader = request.getHeader("authorization");
out.println("<h2>HTTP Authorization header:</h2>");
if (authHeader == null) {
out.print("No authorization header");
} else {
out.print("<textarea readonly id='authHeader' rows=\"5\" cols=\"80\">" + authHeader + "</textarea>");
}
But we are using html as front end, because of angular 2 .
So for my scenario, how I can I get the request header and token.
Please don't hesitate to edit my question, if it is not clear.
You can't get a value of a header from client-side JavaScript. The only exceptions are the User-Agent and Referrer headers, because the browser provides the values in the document and navigator objects.
You said you are working on a Java application with an Angular 2 front end and some other application provides a token (might be useful to specify if this is something standard, e.g. OAuth2). I will assume that it is a custom token. I believe you also meant you have some server side component, a servlet.
What you can do is to implement the authentication using the servlets (or even JSPs) and then redirect back to the Angular 2 front end application, passing the token in the URL as a query parameter. URL is easy to read in Angular 2. However this is not very secure, even if you use something like JWT. As an alternative to URL, you can use the Set-Cookie header and then read the cookie from Angular.
What would be almost secure would be to authenticate the user using the server side (servlet or even JSP). Then create a one-time token which is passed in the URL as a query parameter when redirecting to your HTML page. Then use the one-time token in a call to the server again to retrieve the real authentication token using a proper REST call from Angular 2 with request and response.
Depends on how much control you have and what kind of authentication the auth application uses, you might want to take a look at the OAuth2. It deals with plenty of different authentication scenarios. Specifically the OAuth2 implicit grant flow is used to authenticate users from client-side only applications. Even if you can't use that, it will give you some ideas.
When you are using a server-side authorization, your server put headers with authorization to your HTML pages. But also you can put this tokens to your page response by meta tags at server side. And then access to meta tags by js.
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Meta tags are similar to response headers and can complete or override response headers.
Read this post please Spring Security CSRF Token not working with AJAX call & form submit in same JSP
You can handle this at server side(JSP's expressions work on server side), create a handler method on server where you can check header and then redirect to your Angular App.
I think we can use HTTP HEAD method as JQUERY AJAX request in your HTML page .
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
ajaxRequest = $.ajax({
type: "HEAD",
async: true,
url: 'index.jsp',
success: function(message){
var headerValue =ajaxRequest.getResponseHeader('Content-Length')]);
}
});
There are various way to solve this issue as I faced it a lot before and what I prefer is;
When authentication is completed in login page and a token generates I store it into HTML storage, make be in localStorage.
The main point you should understand that your views should not be accessed directly and there has to be a authentication (or may be a authorisation) step(s) before accessing the page(view).
So what you can do is set a URI for accessing any page, consider that is;
http://host/appname/pageName
And when you connect with this URI via ajax call add the token that is stored in localStorage in headers. And check all authentication and authorisation works and if success return the view(as the pageName suggested in the URI), else return the login view.
If i understand you correctly,
Angularjs is a client side framework and is intended to run inside a browser without any intervention of server by reducing its load by serving the application logic
All operations that need to be performed by angular will only be initiated at client side by the browser after loading the HTML and javascript.
The scope of angular is only limited to that area any way it is not a disadvantage it is the actual intention of client side frameworks.
Regarding request response headers you can only have access to headers of AJAX request
Following are the solutions to these problems:-
If you are using tomcat or any servelet container in order to serve the application or hosting angular code you can use JSP insted of HTML,since JSP is processed to html by the servelet container before passing it to client side.I think this solution will work in your case based on my inference form your question
Otherwise configure servelet that process the success and failure handlers from the authentication server and from angular you need to poll the servelet for getting the request header value.

Login through spring-security from javascript

We are working on application, where my friend is working on server side (spring) and he created REST api, and I'm creating client with angularJS. REST and client webpage are on different domains, so I had to faced Same-origin policy - I handled this with php proxy and everything works fine. Until yesterday - now we had authentication service (spring-security) and I have no idea how to login into REST. I can login when I simple write service adress into browser, but I cant get response I need when calling from JS.
When I'm sending simple get request, in response I'm getting HTML code with login page. I putted <form> to login on my page (taken from response, so it's exacly the same as on '/login' page, I just added full action adress), but after send data I'm getting error page with this message:
HTTP Status 403 - Invalid CSRF Token 'blah-blah-many-numbers-and-letters' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
I'm not changing this CSRF token, so perhaps I don't know the proper way to handle this (now it's sending as paramaeter in POST from form - _csrf is hidden input with value attribute given by server).
So after this too long introduction, my question is: how to login into REST service (through spring-security) from angularJS controller? What is wrong in my way of doing this? (something has to be wrong, because it's not working ;)).
(Sorry for my english mistakes, I'm affraid there are many of them)
Angular have built-in support for CSRF but it use another name for CSRF Token.
If you already have CSRF Token repository in spring webservice, what have you to do is to change CSRF Token header name to XSRF-TOKEN.
You will find whole instruction how to solve your problem on https://spring.io/blog/2015/01/12/the-login-page-angular-js-and-spring-security-part-ii.
You can use Stateless authentication using server signed token i.e.JSON web token(JWT) for securing REST API's and using angularjs for client side implementation.
Please find the below link as reference for implementing the same:
http://blog.jdriven.com/2014/10/stateless-spring-security-part-1-stateless-csrf-protection/
Github:https://github.com/Robbert1/boot-stateless-auth
You need to have custom implementation of class AbstractAuthenticationProcessingFilter to avoid html response when you login into the Rest API.The blog and github reference will guide you in implementating the same.

How to connect to a API with oAuth 1.0a using javascript? [Angular.js]

Currently, I'm working on a web app that requires me to connect to an external API to GET a JSON file.
The API in question that I'm using noun project which requires an Oauth1.0a authentication. Now this project requires me to use Angular.JS to handle JSON data.
But before I can work with the JSON I need to GET it, and this is where things fall apart.
I keep getting the following error on my http://localhost:8080/ when I try to connect with the following code.
The error :
> XMLHttpRequest cannot load
> http://api.thenounproject.com/icons/fish&callback=?&oauth_consumer_key=9c70…891xxxx&oauth_version=1.0&oauth_signature=xxxxx6oeQI0p5U%2Br0xxxxxxx%3D.
> No 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://localhost:8080' is therefore not allowed
> access. The response had HTTP status code 403.
> Blockquote
The code :
var oAuth = OAuth({
consumer: {
public: '9c704cb01xxxxxxxxx',
secret: '45b7a8d86xxxxxxxxx'
},
signature_method: 'HMAC-SHA1'
});
var app = angular.module('nounProject', []);
app.controller('apiController', function(){
console.log("check");
var request_data = {
url: 'http://api.thenounproject.com/icons/fish&callback=?',
method: 'GET'
};
// var token = {
// public: 'f5fa91bedfd5xxxxxxxxxx',
// secret: '84228963d5e8xxxxxxxxxx'
// };
$.ajax({
url: request_data.url,
type: request_data.method,
data: oAuth.authorize(request_data)
}).done(function(data) {
console.log(data);
});
});
The library I use to access OAuth in JavaScript is the following: https://github.com/ddo/oauth-1.0a#client-side-usage-caution (by DDO)
Can anyone guide me in the right direction, or has a better way to OAuth connect to an API with Angular.JS?
Thanks in advance!
The right way is client <-> server <-> oauth services
All the oauth steps should be in your server side.
Why? The simple answer is you can't hide your secret consumer/token at your client side.
I was having the same problem with getting client-side to work, the original is here No Authentication Pop up with Tumblr Like <a> link: but I'll just repost it for ease..
Found an answer!
So let me break it down for you all.. I am just going to run down all the issues and caveats that were discovered while I was hacking away at the Tumblr API. In most cases you will not find any of these answers on the inter webs. If you do, they most likely will just be my answers to my own questions that I posted to the Forums.
A Tumblr Application is defined by any page template either hosted by Tumblr or not that will be using the Tumblr API. Applications must be registered with Tumblr at: https://www.tumblr.com/oauth/apps
All Tumblr Applications upon creation are given a set of keys for accessing the Tumblr API. OAuth Consumer Key aka API Key Secret Key
The Tumblr API is divided mainly into two different types of methods. The third being “Tagged” which is for pulling tagged posts from the Blog or the User.
“Blog Methods” which only require the submission of the Consumer Key. “User Methods” which require a full OAuth signed request which meets the OAuth 1.0a Protocol. The “User Likes” returns a maximum of 50 records at a time. This is not documented in the Tumblr API docs.
Currently the Tumblr API documentation directs developers to use one of the many open source API clients. However, all these clients seem to be Server Side applications. For providers, such as Tumblr, which support only OAuth1 or OAuth2 with Explicit Grant, the authentication flow needs to be signed with a secret key that may not be exposed in the browser.
HelloJS gets round this problem by the use of an intermediary webservice defined by oauth_proxy. This service looks up the secret from a database and performs the handshake required to provision an access_token. In the case of OAuth1, the webservice also signs subsequent API requests.
HelloJS - http://adodson.com/hello.js/ is the only client-side Oauth library that was available and free. There are many services out there that charge on a per-api hit basis to serve as a proxy. The HelloJS OAuth Proxy is available at: https://auth-server.herokuapp.com/
Login to the OAuth Proxy is done using one of the following social account credentials: Google, Windows Live, Facebook, or Yahoo. OAuth Proxy serves as a secure “man in the middle” allowing for the “Secret Key” to be securely stored while still allowing for Client-Side OAuth authentication.
HelloJS features a special Tumblr Module - http://adodson.com/hello.js/demos/tumblr.html
HelloJS utilizes the new Javascript Promises asynchronous functions specification - https://www.promisejs.org/
Javascript Promises have some unique rules when it comes to passing objects received from an asynchronous AJAX call. With everything is done in the callback. What jQuery calls a promise is in fact totally different to what everyone else calls a promise. Hope this helps for future Tumblr integrations.
John

Implementing Stripe Connect using JSONP in an Ember.js app

I am currently integrating Stripe Connect with an Ember.js 1.7.0-beta.4 application (which supports query params). Per Stripe documentation, I need to receive a GET Redirect from Stripe in my Ember.js application, and use the query params to make a final POST request.
So far, I've captured the query params and am attempting to make an AJAX POST from the same controller, but the AJAX POST returns an error because apparently Stripe's API no longer supports CORS - despite a 2-year-old Stripe blog entry saying otherwise:
XMLHttpRequest cannot load https://connect.stripe.com/oauth/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.
The current Stripe docs say to use JSONP, noting in that same blog post that "since JSONP only supports GET requests, but our API uses a variety of request methods, we had to implement HTTP method override support with a _method query parameter."
Unfortunately, I don't know how to integrate the JSONP approach into the Ember.js application.
Stripe's docs instruct me to "Add this script tag to your page to get started with Stripe.js."
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
Do I just paste this verbatim into a Handlebars.js template? Then how do I make the required POST request with query params? And where?
Bottom Line: How do I integrate Stripe's JSON approach to enable Stripe Connect in my Ember.js application?
I haven't tested it with stripe but i'll break apart your question into 3 parts and try to answer each part.
1) Where to put the script tag?
the script tag would go in the header
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
2) How to make a JSONP request?
You would make a reqular request using $.getJSON all you need to do is make sure that the contains ?callback=? see: http://api.jquery.com/jquery.getjson/#jsonp
3) How to do a GET request using _method to override the method.
You would do something like
$.getJSON('http://connect.stripe.com/whatever-the-correct-url-is?callback=?', {
_method: 'POST'
})
If you made a request like that the server should process it as a POST
To Tie it all together you should need to do something like in step 3 but also add in the rest of the params that stripe requires.
You can do it all server side, there is no need to work it into Ember.
The workflow is you redirect a user to the stripe server with your client id. It redirects the user back to an endpoint on your server with a code. You make a call to stripe with that code to obtain a token. After (or during if you want to be cool and async) you redirect the user back to the appropriate ember endpoint. The Stripe js file isn't necessary at all for this portion.
https://stripe.com/docs/connect/oauth#token-request

Authentication api twitter

by documentation (https://dev.twitter.com/docs/auth/application-only-auth) I need to implement an Ajax call to make an app only authentication. I've tried but twitter server respond me ever error 403 forbidden. Can anyone suggest me an Ajax implementation to do this?
Make manually an Ajax call to request an authentication for Twitter is a bit complicate because Twitter needs some parameters in the request header. Plus this parameters needs to be encoded.
To resolve this problem I've found a good library: codebird.js.
Below code to make an authentication and use all twitter api.:
var cb = new Codebird;
cb.setConsumerKey("Yourkey","Yoursecret");
cb.setToken("Access token", "Access token secret");
Yourkey,Yoursecret,Access token,Access token secret are your personal number you can get by your twitter app management.

Categories

Resources