I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}
Related
I've created a flutter application for android and web. In Flutter web, I tried to upload image to server just like it works with firebase. But it is not working somehow. I've seen some solutions for this task. But I wonder, what is actually wrong with my code.
final url = Uri.parse('$apiHeader/poststore');
String token = await getUserToken();
Map<String, String> headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var request = http.MultipartRequest("POST", url);
request.headers.addAll(headers);
request.fields['category_id'] = model.categoryId;
request.fields['title'] = model.title;
//I want to know about this section of the code, how can i make it work
if (kIsWeb) {
final fileBytes =
await model.image.readAsBytes(); // convert into bytes
var multipartFile = http.MultipartFile.fromBytes(
'fileName[]', fileBytes); // add bytes to multipart
request.files.add(multipartFile);
} else {
var multipartFile = await http.MultipartFile.fromPath(
'fileName[]', model.image.path);
request.files.add(multipartFile);
}
var response = await request.send();
private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?
I am new to flutter and I am using mongodb to save the credentials from signup page. When tried to give credentials that already exists server shows a response - 'user already exits' this response was viewed in postman. I am able to get statusCode but I am unable to get the same response in flutter. below is my flutter code.
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode);
return null;
}
To get the body response, use res.stream.bytesToString()
Complete code:
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode); // status code
var bodyResponse = await res.stream.bytesToString(); // response body
print(bodyResponse);
return null;
}
Can you point me to the right way and set of parameters to:
Make an authorization request with PKCE to my identity endpoint (https://.../login) in Postman
In the attachments there is the list of parameters that send.
as grant_type value I use --> authorization_code
Unfortunately I get "bad request", Invalid_grant in Postman
make the access token request. In this request I get Invalid request. I guess I miss the parameter refresh token but I don't know how to get/generate it:
I wrote the code of the Azure function to request the Access Token, unfortunately I get {"error":"invalid_request"} from the token endpoint.
Here is my code, can you tell me what I am doing wrong?
[FunctionName("GetAccessToken")]
public async Task<IActionResult> GetAccessToken(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
log.LogInformation("C# HTTP trigger function ''GetAccessToken'' processed a request.");
string clientSecret = "some secret";
string accessToken = "";
RequestAccessToken rT = new RequestAccessToken();
rT.Code = req.Form["code"];
rT.RedirectUri = req.Form["redirect_uri"];
rT.GrantType = req.Form["grant_type"];
rT.ClientId = req.Form["client_id"];
rT.CodeVerifier = req.Form["code_verifier"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://<access_token_endpoint_base_uri>");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
var body = new { EntityState = new {
code = rT.Code,
redirect_uri = rT.RedirectUri,
grant_type = rT.GrantType,
client_id = rT.ClientId,
client_secret = clientSecret,
code_verifier = rT.CodeVerifier
} };
var result = await client.PostAsJsonAsync(
"/login",
body);
accessToken = await result.Content.ReadAsStringAsync();
}
return new OkObjectResult(accessToken);
}
catch (Exception ex)
{
log.LogInformation(ex.ToString());
return new ObjectResult(ex.ToString()) { StatusCode = 500 };
}
}
Steps 4 and 8 of my blog post show the standard PKCE parameters.
It is tricky to reproduce the whole flow via a tool such as Postman though, since there is typically also the need to follow redirects and manage a form post of user + password.
I am having a difficult time using UseJwtBearerAuthentication Method, I am using Microsoft Azure ACS to obtain a token (using a service identity). The JWT token returns fine to my test program. In the test program the token is sent to a MVC WebAPI 2. (The WAAD authentication works fine when token is obtained from Azure Active Directory)
public partial class Startup
{
private const string Issuer = "https://bluebeam-us-east.accesscontrol.windows.net/";
public void ConfigureAuth(IAppBuilder app)
{
string CertificateThumbprint = "99B25E3E31FCD24F669C260A743FBD508D21FE30";
var audience = ConfigurationManager.AppSettings["ida:Audience"];
app.UseErrorPage(new ErrorPageOptions()
{
ShowEnvironment = true,
ShowCookies = false,
ShowSourceCode = true,
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = audience ,
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(Issuer, X509CertificateHelper.FindByThumbprint(StoreName.My,StoreLocation.LocalMachine,CertificateThumbprint).First())
},
});
}
The Code to get Token from ACS is as follows:
private async void GetJwtToken()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(IdP.Authority);
var content = new FormUrlEncodedContent(new Dictionary<String, String>
{
{"grant_type","client_credentials"},
{"client_id", IdP.UserName},
{"client_secret", IdP.Password},
{"scope", IdP.Resource}
});
var response = await client.PostAsync("v2/OAuth2-13", content);
response.EnsureSuccessStatusCode();
var jwtdata = await response.Content.ReadAsStringAsync();
var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
AccessToken = jwt.access_token;
TokenType = jwt.token_type;
long expire;
if (long.TryParse(jwt.expires_in, out expire))
{
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
}
Authorization = AccessToken;
}
}
catch (HttpRequestException re)
{
Response = re.Message;
}
}
The code to request a Resource (WebAPI):
private async void WebApiRequestCall()
{
try
{
ConfigureSsl();
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!String.IsNullOrWhiteSpace(Authorization))
client.DefaultRequestHeaders.Add("Authorization", Authorization);
var response = await client.GetAsync(WebApiRequest);
response.EnsureSuccessStatusCode();
Response = await response.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException e)
{
Response = e.Message;
}
}
The decoded Token (using google token decoder looks as follows)
Header
{
"x5t": "mbJePjH80k9mnCYKdD-9UI0h_jA",
"alg": "RS256",
"typ": "JWT"
}
Claims
{
"identityprovider": "https://bluebeam-us-east.accesscontrol.windows.net/",
"iss": "https://bluebeam-us-east.accesscontrol.windows.net/",
"http://schemas.microsoft.com/identity/claims/identityprovider": "revu",
"exp": 1406957036,
"nbf": 1406956676,
"aud": "https://bluebeam.com/Bluebeam.Licensing.WebApi/"
}
So I have the following questions:
1) Is using JwtBearerToken the correct method to use to decode decode JWT token from ACS
2) Is there any tracing facilities in Owin that can provide whats going on in the authentication pipeline?
I am using Microsoft Own 3.0-rc1.
It seems that I had an error in my code where I was not setting the correct "bearer header" for OWIN when sending the client request to WebAPI.
After Receiving the JWT Token from ACS, I needed to set the Authorization correctly
private async void GetJwtToken()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(IdP.Authority);
var content = new FormUrlEncodedContent(new Dictionary<String, String>
{
{"grant_type","client_credentials"},
{"client_id", IdP.UserName},
{"client_secret", IdP.Password},
{"scope", IdP.Resource}
});
var response = await client.PostAsync("v2/OAuth2-13", content);
response.EnsureSuccessStatusCode();
var jwtdata = await response.Content.ReadAsStringAsync();
var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
IdP.AccessToken = jwt.access_token;
IdP.TokenType = jwt.token_type;
long expire;
if (long.TryParse(jwt.expires_in, out expire))
{
IdP.ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
}
// Ensure that Correct Authorization Header for Owin
Authorization = String.Format("{0} {1}", "Bearer", IdP.AccessToken);**
}
}
catch (HttpRequestException re)
{
Response = re.Message;
}
}
We also need support for symmetric key on the WebAPI, based upon how ACS sends the token
public void ConfigureAuth(IAppBuilder app)
{
var thumbPrint = ConfigurationManager.AppSettings["ida:Thumbprint"];
var audience = ConfigurationManager.AppSettings["ida:Audience"];
var trustedTokenPolicyKey = ConfigurationManager.AppSettings["ida:SymmetricKey"];
app.UseErrorPage(new ErrorPageOptions()
{
ShowEnvironment = true,
ShowCookies = false,
ShowSourceCode = true,
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
{
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(Issuer,
X509CertificateHelper.FindByThumbprint(StoreName.My, StoreLocation.LocalMachine, thumbPrint)
.First()),
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, trustedTokenPolicyKey),
},
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = audience,
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
}