Integrating BankID (Swedish authentication service) into Flutter (Android and Ios) - flutter

I'm trying to impletment Swedish bankid on one of my project. But the resources that are available on the internet is too little. Can anybody help me how to implement BankId authentication on flutter app.

Not sure on how much experience you have whit BankId, so maybe you already know some of the stuffs, but this is how I solved it.
The service has three main endpoints for performing verification:
/auth/start: This endpoint is used to initiate the verification process and generates a unique key, called a bankIdToken, which is returned in the form of a GUID.
/auth/status: This endpoint is used to check the status of a verification process that has been initiated with the /auth/start endpoint. The status can be "waiting" or "completed".
/auth/verify: This endpoint is used to verify the identity of a user who has completed the verification process and returns a JSON object containing information about the user.
To perform a verification, the steps are as follows:
Send a request to /auth/start to initiate the process and receive the bankIdToken.
Pass the bankIdToken to /auth/verify to trigger the verification on the user's device (mobile, pc) , the status will be waiting.
After the user completes the process on their device, check the status by sending a request to /auth/status that will change the status to completed.
Send a request to /auth/verify to verify the user, this will return a JSON object containing user information.
You can also get testing bankid at https://demo.bankid.com/ and fake Swedish person numbers in skatteverket or https://fejka.nu/ ( GDPR Approved)
This is my flutter code whit hardcoded values
class AuthDataSource {
Future<AuthVerifyModel> authFlow() async {
final authStartResponse = await http.post(
Uri.https(BASEURL, '/auth/start'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'bankIdNumber': '198806192392',
}),
);
if (authStartResponse.statusCode != 200) {
throw ServerException();
}
final authStartModel =
AuthStartModel.fromJson(jsonDecode(authStartResponse.body));
final authStatusResponse = await http.post(
Uri.https(BASEURL, '/auth/status'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'bankIdToken': authStartModel.bankIdToken.toString(),
}),
);
if (authStatusResponse.statusCode != 200) {
throw ServerException();
}
final authVerifyResponse = await http.post(
Uri.https(BASEURL, '/auth/verify'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'bankIdToken': authStartModel.bankIdToken.toString()
}),
);
if (authVerifyResponse.statusCode != 200) {
throw ServerException();
}
return AuthVerifyModel.fromJson(jsonDecode(authVerifyResponse.body));
}
}

Related

How to update row in a database table using http put request with id of the row?

I am trying to update my database table row using http put request in flutter web app.
My backend server working fine and able to put data on database using postman app. But unable to update data from my Flutter web app. How to Create Put Request and update the data using the id ofthe row.
Getting Below Error on browser_client.dart:
unawaited(xhr.onError.first.then((_) {
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
// specific information about the error itself.
completer.completeError(
ClientException('XMLHttpRequest error.', request.url),
StackTrace.current);
}));
I am trying below Api: id is row ID in the table. company, name, address, phone are updatable variables. Passing from TextEditfields from the flutter page.
Future<Company> updatedata(
id,
company,
name,
address,
phone,
) async {
Uri url =
Uri.parse("http://--link--/$id");
var response = await http.put(url);
print(response);
headers:
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',
};
body:
jsonEncode(<String, String>{
"company": company,
"name": name,
"address": address,
"phone": phone,
});
if (response.statusCode == 200) {
return Company.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to update.');
}
}
The body and header details are placed outside the request. Make sure to include that along with the request.
var response = await http.put(url, headers:
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',
}, body:
jsonEncode(<String, String>{
"company": company,
"name": name,
"address": address,
"phone": phone,
});
);

Flutter Http post call Doesn't work on web and works on mobile only

loginUser(email, password) async {
var url = Uri.parse
.call("https://us-central1-agenie-webapp.cloudfunctions.net/api/login");
final http.Response response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{'email': email, 'password': password}),
);
if (response.statusCode == 200) return response.body;
return null;
}
This is the api post call when I run this on web localhost with flutter run ,when I click on login button that calls this function on pressed it open a window in vscode named browser_client.dart and goes to line 69 where it shows :
unawaited(xhr.onError.first.then((_) {
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
// specific information about the error itself.
completer.completeError(
ClientException('XMLHttpRequest error.', request.url),
StackTrace.current);
}));
Any solutions ? Thanks
I suggest you trying to use the dio package (https://pub.dev/packages/dio), it worked in my web project.

How to make a proper http request?

I can't seem to make a proper http request with my code. Whenever I run the following code,
var url = Uri.https('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2?BusStopCode=', {'BusStopCode': busStopCode});
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);
I get the following error
I/flutter (24816): SocketException: OS Error: Connection refused, errno = 111, address = datamall2.mytransport.sg
This is the http request I'm trying to make
http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=busStopCode (busStopCode is a 5 digit number)
The wrong protocol is being used.
You've requested httpS.
The server is only responding to http.
You could try something simpler:
String url = 'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?$busStopCode';
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);
You should change your url variable to:
var url = Uri.http('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2', {'BusStopCode': busStopCode});

Rest API in Flutter Login

When I give header and body information inside my http request, it redirects automatically to next page even if i dont give any login credential in my Mobile App.
Future<Login> fetchLoginData() async {
final http.Response response = await http.post(
'http://lmsapi.design.net:88//api/login/login',
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic XfnatLYBaDO2AKP6KfcIJg=='
},
/* body: {
'companycode': 'ABC1001',
'deploymentcode': 'ui11'
}*/
);
if (response.statusCode == 200) {
// then parse the JSON.
return Login.fromJson(jsonDecode(response.body));
} else {
// then throw an exception.
throw Exception('Failed to load Data');
}
}
Can someone help me how to pass header and body inside my http request?
The issue doesn't seem to be about handling the http response and leans more toward on how the navigation to the next page is handled. You'd need to check if fetchLoginData() returns the response. Future callback can be handled by using fetchLoginData().then() for example.
fetchLoginData().then((Login? loginData){
if(loginData!=null){
// Handle Navigation
}
});
Then you may consider implementing the navigation once you got a successful response from fetchLoginData()

http.post return 307 error code in flutter

I am using http client for flutter network call.
My request working on postman getting response properly,
But while trying with http.post it returns error code 307-Temporary Redirect,
Method Body:
static Future<http.Response> httpPost(
Map postParam, String serviceURL) async {
Map tempParam = {"id": "username", "pwd": "password"};
var param = json.encode(tempParam);
serviceURL = "http:xxxx/Login/Login";
// temp check
Map<String, String> headers = {
'Content-Type': 'application/json',
'cache-control': 'no-cache',
};
await http.post(serviceURL, headers: headers, body: param).then((response) {
return response;
});
}
Also, the same code returns a proper response to other requests and URLs.
First I trying with chopper client but had same issue.
I am unable to detect that issue from my end of from server-side.
Any help/hint will be helpful
Try to put a slash / at the end of the serviceUrl. So, serviceUrl is serviceURL = "http:xxxx/Login/Login/" instead of serviceURL = "http:xxxx/Login/Login".
This works for me.
You need to find a way to follow redirect.
Maybe postman is doing that.
Read this >>
https://api.flutter.dev/flutter/dart-io/HttpClientRequest/followRedirects.html
Can you try with using get instead of post? At least to try and see what happend
In the documentation said:
Automatic redirect will only happen for "GET" and "HEAD" requests
only for the status codes
HttpStatus.movedPermanently (301),
HttpStatus.found (302),
HttpStatus.movedTemporarily (302, alias for HttpStatus.found),
HttpStatus.seeOther (303),
HttpStatus.temporaryRedirect (307)
keeping https instead of http in the URL it is helping me.
#Abel's answer above is correct but I had to switch from using:
Uri url = Uri.https(defaultUri, path);
to
Uri url = Uri.parse('https://todo-fastapi-flutter.herokuapp.com/plan/');
to get that last / after plan.
The first way kept dropping it so I was getting 307 errors.
flutter.dev shows a full example:
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
here: https://flutter.dev/docs/cookbook/networking/send-data#2-sending-data-to-server
For Dio Http Client, use Dio Option follow redirect as True
getDioOption(){
return BaseOptions(connectTimeout: 30, receiveTimeout: 30,
followRedirects: true);
}