How to get user mail picture from exchange Web services - exchange-server

I’m trying to get AD user picture through Exchange Serve web services. But when I  run the code to the server it returns me the following error:               
The remote server returned an error: (401) Unauthorized.
  Credential to my mail box are correctly!              
HttpWebRequest request =
            WebRequest.Create("https://www.contoso.com/ews/exchange.asmx/s/GetUserPhoto?email=sadie#contoso.com&size=HR240x240";)
            as HttpWebRequest;
            CredentialCache cc = new CredentialCache();
            cc.Add(
            new Uri("https://www.contoso.com/ews/exchange.asmx/s/GetUserPhoto?email=sadie#contoso.com&size=HR240x240";),
            "NTLM",
            new NetworkCredential("domainusername", "Mypass"));
            request.Credentials = cc;
                     request.Credentials =cc;
            // Submit the request.
            using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
            {
                // Take the response and save it as an image.
                Bitmap image = new Bitmap(resp.GetResponseStream());
                image.Save("Sadie.jpg");
            }
    

What if you try:
new NetworkCredential("username", "password", "domain")
And make sure the URI is the correct one (not www.contoso.com).

Related

Identity server 4 throws redirect uri not define error

I am trying connect the asp.net webform client to identity server 4 for authentication and athorization. When user is redirected to identity server for login I am getting an error and Identity server log says "redirect_uri is missing or too long" but I have defined the redirect uri on client config. Not sure why it is throwing an error on identity server side?
Client Configuration:
new Client {
ClientId = "testclient1",
ClientSecrets = { new Secret("client_secret_webform".ToSha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
RequirePkce = true,
RedirectUris = { "http://localhost:54602/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:54602/signin-oidc" },
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
},
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
}
Webform Client setting
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "testclient1",
Authority = "https://localhost:44314/",
ClientSecret = "client_secret_webform",
ResponseType = "id_token token",
SaveTokens = true
});
}
IdentityServer4.Validation.AuthorizeRequestValidator: Error: redirect_uri is missing or too long
The easiest way to figure out the correct redirectUrl is to locate the request to the Authenticate endpoint in Fiddler, and see what RedirectUrl the OpenIDConnect handler is sending to IdentityServer.
In Fiddler you can then locate the redirect_uri that should match exactly the url defined in IdentityServer
Try to change OpenID Connect settings on client to add RedirectUri and PostLogoutRedirectUri, like this:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "testclient1",
Authority = "https://localhost:44314/",
ClientSecret = "client_secret_webform",
ResponseType = "id_token token",
SaveTokens = true,
RedirectUri = "http://localhost:54602/signin-oidc",
PostLogoutRedirectUri = "http://localhost:54602/signin-oidc",
});
}
Also as other answer mentioned use Fiddler or activate log to check the values sent to IDS4
The redirect uri you configure in IdentityServer is not the same as the one you are actually using in the client request. Capture your request to see this redirect uri.
The exception can be caused by two resons:
The redirect Uri is empty, null or white space
The redirect Uri is longer than the maximum allowed. The default value is 400.
You can modify this value in the IdentityServerOptions:
services
.AddIdentityServer(options =>
{
options.InputLengthRestrictions.RedirectUri = 1000;
...
}
...
...

How to make jira attachments download work using jira rest api

I am trying to download attachments from Jira. I use /rest/api/2/attachment/{id} to get json response of the attachment. It has field "content" that is the attachment url. I use this url and construct HttpGet and execute to get response that always gives me html content asking for login. I am sending Basic Authorization in the httpGet header. Apparently this works for downloading .png files but not any other file types. I am using java spring rest to connect to Jira horizon.
Closeable httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(jira attachmenturl);
httpGet.setHeader("Authorization", "Basic <base64Credentials>);
CloseableHttpResponse response = httpclient.execute(httpGet)
The response for .txt, .jpeg, Microsoft documents is different from response that I get for .png files.
This works:
#GetMapping(value = "/getAttachment")
public String getAttachment(#RequestParam("id") String attachmentID) throws Exception {
Client client = Client.create();
WebResource webResource = client.resource(jiraBaseURLRest + "attachment/" +
attachmentID);
ClientResponse response = webResource.header("Authorization", "Basic " +
base64Creds).type("application/json")
.accept("application/json").get(ClientResponse.class);
String result = response.getEntity(String.class);
JSONObject jsonObj = new JSONObject(result);
System.out.println("JSON Object = "+jsonObj);
URL url = new URL(jsonObj.getString("content"));
Closeable httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url.toURI());
httpGet.setHeader("Authorization", "Basic " + base64Creds);
CloseableHttpResponse response1 = ((CloseableHttpClient) httpclient).execute(httpGet);
if(response1.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response1.getEntity();
if (entity.isStreaming())
{
System.out.println("Streaming...");
byte data[] = EntityUtils.toByteArray(entity);
FileOutputStream fout = new FileOutputStream(new File("D://pdf1.pdf"));
fout.write(data);
fout.close();
System.out.println("Done!!");
}
}
return "Success";
}

Angular6 File Upload (Image) with Spring boot

I have a problem when uploading an image in angular 6.
Angular:
addAvatar(username: string, file: File) {
const headers = new HttpHeaders({
});
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(`${this.API_URL}/addavatar/` + username, formData, {headers});
}
Spring controller:
#PostMapping("/addavatar/{username}")
public ResponseEntity<?> addAvatar(#PathVariable(value = "username") String username, #RequestPart(name = "file", required = false) MultipartFile file) {
return userService.addAvatar(username, file);
}
If I send request in Postman all works, but if I want to send request in Angular then I have a 404.
File Upload in Postman
Response in html
/file/ URI in Postman URL seems to be overlooked at Angular request path literal API_URL. That's why it occurs the 404 error.

Getting "unauthorized" error when trying to refresh access token

I am trying to refresh the access token for a user following this tutorial.
However, I am getting
{
"error":"unauthorized",
"error_description":"Full authentication is required to access this resource"
}
and I do not see what's missing.
The following is how I am constructing the oauth/refresh request in my Angular application:
refreshToken() {
this.logger.info('Attempting to refresh access token');
const headers = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
// CLIENT_ID:CLIENT_SECRET
.set('Authorization', 'Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=');
const payload = {
refresh_token: AuthenticationService.getRefreshToken(),
grant_type: 'refresh_token'
};
return this.http.post(environment.apiUrl + '/oauth/refresh',
payload, {headers: headers})
.pipe(map(r => r));
}
What am I missing here?
Okay, I was almost right.
First, I did use the wrong endpoint /oauth/refresh - I don't know why I thought this existed. It has to be /oauth/token.
Also payload gets send via URL parameters:
const payload = `refresh_token=${AuthenticationService.getRefreshToken()}&grant_type=refresh_token`;
So in the end I got this working with:
refreshToken() {
this.logger.info('Attempting to refresh access token');
const headers = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
.set('Authorization', 'Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=');
const payload = `refresh_token=${AuthenticationService.getRefreshToken()}&grant_type=refresh_token`;
return this.http.post(environment.apiUrl + '/oauth/token',
payload, {headers: headers})
.pipe(map(r => r));
}

Cannot get cookies in wp7 using HttpWebRequest

I'm trying to save cookies in a post request. Here is my code :
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.UserAgent = userAgent;
myHttpWebRequest.CookieContainer = myCookieContainer;
myHttpWebRequest.Method = "POST";
byte[] postdata = encoding.GetBytes(submitString);
myHttpWebRequest.BeginGetRequestStream(async1 =>
{
using (Stream stream = myHttpWebRequest.EndGetRequestStream(async1))
stream.Write(postdata, 0, postdata.Length);
myHttpWebRequest.BeginGetResponse(async2 =>
{
HttpWebResponse rep = (HttpWebResponse)myHttpWebRequest.EndGetResponse(async2);
CookieCollection cookies = rep.Cookies;
using (Stream stream = rep.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
String content = sr.ReadToEnd();
if (pageDownloadedEventHandler != null)
pageDownloadedEventHandler(content);
}
}, null);
}, null);
Alaways the CookieContainer is empty.
How to get the cookies?
Your code seems to be perfect, if the server sends you back any cookies you should see them in rep.Cookies, as well as in myCookieContainer.
If you want to be sure use Fiddler or Wireshark to analyze the HTTP network traffic and look for the cookies, but if I'm right you won't find them. In this case my idea is to analyze the network traffic doing the same request with your browser, maybe the php/asp.net/other app decided not to set cookies due to some missing request headers.

Resources