HTTP Response 401 while trying to subscribe Outlook Events - Java - java

I am using Outlook Rest API to subscribe events. However, I get error code 401 although I include the access token. I get the access token following https://learn.microsoft.com/en-us/outlook/rest/java-tutorial this tutorial. And my payload is like the following:
{
"#odata.type":"#Microsoft.OutlookServices.PushSubscription",
"Resource":"https://outlook.office.com/api/v2.0/me/events",
"NotificationURL":URL,
"ChangeType":"Created"
}
with the header:
authorization: Bearer + access token which I get from the tutorial. (I.E EwBAA8l6BAAURSN/FHlDW5xN74t6GzbtsBBeBUYAAeybQmu+RnQcYAQ3wTW3kJUclA03jKgc4Sdx2mp5SOlLswSAr9zTmO7qk33wpTD3ULZkUrl9IpTnnhtjeoSXt+z5GRRtmL40jyvAghrTseO8yEZtR04SLjl6i1KZNXxZwUTK8s6DkXESwkwaTmQKPckKHi9XeIbx8dolnT7vEeeUo5rmzcG251dQokfZYHCar3bd1bysV7oaTt5Iis6qgkYtg4BL/32QObgI8SHQS4my7FSsqLYFchYExEFeBXgUjt4yE0G0bbmykz3T5C713DAqo8BtCkkbRIckv6N4bpq84bpzaDAgdgHhnpcYzUaViJ2zhZXMrShUdpddug+DPkEDZgAACILe9sz+3mX7EAJrVvnkVpyZzC9WvQkY4xET3KdEstT..... Something like this)
content-type: application/json
Why do I get 401?
Thank you.

A 401 means that your token isn't valid for what you're trying to do. It could be expired, invalid, etc. Typically the body of the response gives more detail on the reason of the 401.
I'd recommend going to https://oauthplay.azurewebsites.net/ and playing with the notifications API there to see how it all works.

Related

Google OAuth returning invalid_grant Incorrect token type

I get a valid code on the client side login of my application using angularJS Oauth Module GAuth.checkAuth(). and then GAuth.getToken().
The code is valid only for 1 hour and any API like GoogleDocs,Gmail accessed after 1 hour fails and needs relogin.
To overcome this I am trying to send the code to the server for getting AccessCode at Server so that I can send same with requests to GoogleDocs, Gmail etc
GoogleAuthorizationCodeTokenRequest req =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
// "https://accounts.google.com/o/oauth2/token",
"901142925530-21ia7dqnsdsdsndnsnnnfdc9cm2u07.apps.googleusercontent.com",
"6NSvw0efghyuuG8YGOBWPln79n",
authCode,
"http://localhost:8080");
req.setGrantType("authorization_code");
//req.put("refresh_token", authCode);
//req.put("access_type", "offline");
GoogleTokenResponse tokenResponse =
req.execute();
tokenResponse.getAccessToken()
Where authCode is the code I received in GAuth Token
But the call is failing and in response I get
400 Bad Request
{
"error" : "invalid_grant",
"error_description" : "Incorrect token type."
}
Any help is highly appreciated!
When the user first authenticates your application you are given an authorization code. You then need to take this authorization code and exchange it for an access token and a refresh token. Once the authorization code has been used it can not be used again.
grant_type=authorization_code
Denotes that you are asking Google to verifiy that your authorization code and give you a new access token and refresh token.
It sound to me like you are taking either the access token returned from that request and sending it to grant_type=authorization_code end point which is not going to work its the wrong type of code. hens the error you are getting of
400 Bad Request { "error" : "invalid_grant", "error_description" : "Incorrect token type." }
You will need to take the refresh token you are given. If there is one I am not sure that you can even get a refresh token from AngularJs. You can get one using java though.
A refresh of an access token in pure rest will look like this
https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
Note the &grant_type=refresh_token. If you are using the Google api java client library it should handle all of that for you. However your tagging is a little confusing its unclear if you are trying to do this in java or angularjs which I do not believe will allow you to use refresh tokens. Again I am not an angular dev I could be wrong on that point.
Anwser:
You the code you are sending is not an authorization code. Only an authorization code can be sent to grant_type=authorization_code. Solution: Send an authorization_code
Types of Google codes and tokens:
There are three types of codes or tokens you should be aware of with Oauth2.
Authorization code.
Refresh token
Access token
When you request access of a user and they grant your application access you are given an Authorization code. The Authorization code is short lived it probably less then 10 minutes and it can only be used once.
The Authorization code is used to get the initial access token and the refresh token from googles authentication server. by using the grant_type=authorization_code
Access token are good for about an hour. They are used to make calls to google APIs
https://www.googleapis.com/plus/v1/people/me?access_token={your access token}
You can use the access token as often as you want during that hour assuming you don't blow out some quota.
Refresh tokens are used to request a new access token from the Google authentication server when the access token you have current has expired or you just want a new one. here the grant_type=refresh_token is used to request a new access token you are essentially telling google I am sending you a refresh token you know what to do.
additional reading
I have a coupe of tutorials that might help you out Google 3 Legged OAuth2 Flow and Google Developer Console Oauth2 credentials
Also helpful when learning Oauth: The OAuth 2.0 Authorization Framework

How to send back a JWT token with HttpURLConnection in java?

I am using an API to get some information. At the beginning of each session you need to get a JWT token to be able to send requests to the API. After I've got the token and I try to send a request, I get an error saying I'm unauthorized, which is fair since I did not attach the token in my request. The problem is that the documentation for the API does not explain how to do this, and I haven't been able to find it anywhere else either. How do I do this? I am doing this is Java and is using their own HttpURLConnection. Hopefully you understand what I mean.
Thank you in advanced!
It depends on how the web-service (API) wants to have the token represented.
Common are:
HTTP request headers (problem for XHR requests)
query parameters (bad idea because of caching/logging)
form fields (not universally useable)
URL segment (bad idea because of caching/logging)
certain cookies with the token as value (transparent) or
authentication header (typical)
The Authentication headers as defined in HTTP RFCs are typically be used with the Basic or Digest authorization scheme. In case a string (token) authenticates the bearer of that token, the "Bearer" scheme is used (for example defined for OAuth2 in RFC6750).
You would use
uc.setRequestProperty("Authorization","Bearer " + jwt);
for this.

Getting 401-Unauthorized while getting photo using outlook REST API - java cliet

I am trying to retrieve user photo using outlook REST API(https://msdn.microsoft.com/en-us/office/office365/api/photo-rest-operations#UserphotooperationsGetphoto)
I got the access token following (https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx)
but getting this error : any help?
HTTP/1.1 401 Unauthorized [Content-Length: 0, Server: Microsoft-IIS/8.0, request-id: 6925fcab-9021-4059-af4b-4cbf130faea7, X-CalculatedBETarget: CY1PR0401MB1388.namprd04.prod.outlook.com, X-BackEndHttpStatus: 401, Set-Cookie: exchangecookie=87cb2447eae9401c80a96c497dff06a9; expires=Sat, 22-Apr-2017 07:56:53 GMT; path=/; HttpOnly, x-ms-diagnostics: 2000001;reason="The access token is acquired using an authentication method that is too weak to allow access for this application. Presented auth strength was 1, required is 2.";error_category="invalid_token",
code looks something like this:
HttpClient httpclient = HttpClients.createDefault();
final String bearerToken = getBearerToken();
HttpGet request = new HttpGet("https://outlook.office.com/api/v2.0/me/photo/$value");
request.setHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken);
request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
HttpResponse response = httpclient.execute(request);
return IOUtils.toByteArray(response.getEntity().getContent());
According to the error message. Instead of a client_secret in your request body, you need a client_assertion.
For more details, you can reference the blog Building Daemon or Service Apps with Office 365 Mail, Calendar, and Contacts APIs (OAuth2 client credential flow)
According to the API you call "https://outlook.office.com/api/v2.0/me/photo/$value". It seems that you only want to get the photo for the current login user; if so, you can use Authorization Code Grant Flow to get the token which will not require the client certificates.
UPDATE#1:
Can this be done programmatically/API way
As far as I know, the consent need the user's or admin's interactivity.
https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&resource={1}&redirect_uri={2}&prompt={3}
If you are developing a ASP.NET web application, you can reference the sample project O365-WebApp-MultiTenant.
BTW, when calling the API with app-token, you need to specify the user name.
e.g.
https://outlook.office.com/api/v2.0/users('user1#customdomain.onmicrosoft.com')/messages
UPDATE#2:
The 403 code when updating the photo using the app token is expected result.
As we can see from the figure above, updating the user photo requires the delegated permission "User.Read.Write". The app token does not have permission to update user's photo.

paypal access token not returning

I trying to send a payment with my test application. Im using the paypal java sdk package.
Im not receiving my access token. Im receiving only the bearer token,
Bearer WesirDWp61YcTr8N8XWZHnPk7tCch.ZgcMvLfyp-FRA : appId :
APP-80W284485P519543T
Thus when I try to send a payment Im getting and 401 authorization error because of no access token. The first time I sent the request it returned the access token but every subsequent attempt brings this error:
Java exception "com.paypal.core.rest.PayPalRESTException: Error code : 401
with response : Server returned HTTP resp" when calling method "create" with
signature "(Ljava.lang.String;)Lcom.paypal.api.payments.Payment;" in class
"com.paypal.api.payments.Payment".
I do not understand what is happening here . Am I completely missing the boat here?
Thank You for any response.
Hit this URL with POST Request on Postman.
POST https://api.sandbox.paypal.com/v1/oauth2/token
On Authorization choose basic auth and enter the username as a clientID and password as a ClientSecret.
In Header set Content-Type: application/x-www-form-urlencoded
In Body seelect x-www-form-urlencoded and write grant_type: client_credentials
after that send request you will get the access_token
The bearer token is the access token, more specifically it is the type of access token returned. As per the REST API Reference (which is what the java sdk calls), the call to the oauth end point returns:
{
"scope": "https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
"access_token": "EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG",
"token_type": "Bearer",
"app_id": "APP-6XR95014SS315863X",
"expires_in": 28800
}
The SDK combines the two fields and returns them as the "Bearer token".
This bearer token is all you need to access the REST APIs (with some restrictions based on the permissions/scopes requested and how the bearer token was requested, however that is dependent on creation call). Pass the bearer token in the authorization header:
"Authorization: Bearer EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG"

Compulsory to use JSON form of request in Google GCM?

I am migrating from google C2DM to GCM using Java.
I read this post GCM Push Notification without using JSON. Even on google docs I found that plain-text or UTF-8 content-type is allowed. I am using API key for browser apps and also tried curl command. Every time I am getting response code 401 which is related to authorization. Below is the URL I am forming:
Collapse_key=0&Auth_Token=
> my api key for browser apps
&data.payload=
> meesage to be send
&registration_id=
> id of registered device
May I know the reason and solution for response code 401 ?
HTTP status code 401 occurred when API key is not valid. For details check here.
You should send data as a json format. The format is shown below. It is explained in details here.
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}

Categories

Resources