Getting 401-Unauthorized while getting photo using

2019-03-04 14:34发布

问题:

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());

回答1:

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.