I'm developing an application using ChopperClient. To improve application security I want to do certificate pinning by using http_certificate_pinning library.
What I've tried:
I try using HttpCertificatePinning.check as suggested in the library's official guide. The serverURL is my mock api url. When I run the application, the application crashed and exited. When I change the url to https://www.google.com/ the application is not crash and the result is returned as false.
Does anyone have experience using Chopper with this library?
How should I do certificate pinning with this library?
Future<bool> myCustomImplementation(String url, Map<String, String> headers,
List<String> allowedSHAFingerprints) async {
try {
final String secure = await HttpCertificatePinning.check(
serverURL: url, //mock api url
headerHttp: headers, //mock headers
sha: SHA.SHA256,
allowedSHAFingerprints: allowedSHAFingerprints, //mock fingerprints
timeout: 100);
if (secure.contains("CONNECTION_SECURE")) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
Related
I am creating a Flutter Web app that requires login verification. The user makes a post request with authentication information and then my Flask app with send a cookie back to the client.
Here is the code for the Flask App
#app.route('/test', methods=['POST'])
#cross_origin(supports_credentials=True)
def test():
resp = jsonify({'message' : 'Logged in!'})
resp.set_cookie('Set-Cookie', "token", httponly = True, secure = False)
return resp
Here is the Dart/Flutter code where I make the POST request and expect a cookie called 'Set-Cookie'.
class HttpService {
static var dio = Dio();
static testMethod() async {
try {
dio.options.extra['withCredentials'] = true;
var response = await dio.post('http://127.0.0.1:5000/test');
print(response);
} catch (e) {
print(e);
}
}
As you can see, I don't receive this cookie on my browser, but the request is successful and I get the JSON message!
BUT, when I make this same request on Postman, I get the JSON response AND the cookie.
Any help would be greatly appreciated! Let me know if you need any more details/code.
Thanks to Kris, I realized I was making the request from Flutter (Client) to an IP rather than the domain name localhost. Because setting a cookie is domain specific, I couldn't see the cookie set in the developer console.
Here is the updated code
static testMethod() async {
try {
dio.options.extra['withCredentials'] = true;
var response = await dio.post('http://localhost:5000/test');
print(response);
} catch (e) {
print(e);
}
}
Could someone help me on implementing SSL public key pinning in flutter? I have searched a lot in google but I did not find a proper article that explains how this can be implemented.
Kindly help !!!
There is a package called http_certificate_pinning which provides 3 different APIs to use. You can check it here.
1-As an interceptor for Dio:
import 'package:http_certificate_pinning/certificate_pinning_interceptor.dart';
// Add CertificatePinningInterceptor in dio Client
Dio getClient(String baseUrl, List<String> allowedSHAFingerprints){
var dio = Dio(BaseOptions(baseUrl: baseUrl))
..interceptors.add(CertificatePinningInterceptor(allowedSHAFingerprints));
return dio;
}
myRepositoryMethod(){
dio.get("myurl.com");
}
2-Creating an http client:
import 'package:http_certificate_pinning/secure_http_client.dart';
// Uses SecureHttpClient to make requests
SecureHttpClient getClient(List<String> allowedSHAFingerprints){
final secureClient = SecureHttpClient.build(certificateSHA256Fingerprints);
return secureClient;
}
myRepositoryMethod(){
secureClient.get("myurl.com");
}
3-Checking if the handshake happens correctly and do whatever you want:
import 'package:http_certificate_pinning/http_certificate_pinning.dart';
Future myCustomImplementation(String url, Map<String,String> headers, List<String> allowedSHAFingerprints) async {
try{
final secure = await HttpCertificatePinning.check(
serverURL: url,
headerHttp: headers,
sha: SHA.SHA256,
allowedSHAFingerprints:allowedSHAFingerprints,
timeout : 50
);
if(secure.contains("CONNECTION_SECURE")){
return true;
}else{
return false;
}
}catch(e){
return false;
}
}
So I have this piece of my code that handle's some basic post authentication with a django/nginx backend, and when I'm dev testing it on the iOS simulator, it works fine. However, when I am testing it on Flutter web, I keep getting this error.
XMLHttpRequest error.
Any help would be appreciated!
Code in question (the function: working connection, funny enough is working as expected)
static Future<bool> login(String username, String password) async {
final Uri url = Uri.parse(baseUri.toString() + "/api/login/");
var data = jsonEncode({"username": username, "password": password});
if (await workingConneciton()) {
var response = await http.post(url, headers: baseHeader, body: data);
Map<String, dynamic> json = jsonDecode(response.body);
print(response.body);
if (json.containsKey("token")) {
await User.setToken(json["token"]! as String);
return true;
} else {
return false;
}
} else {
return false;
}
}
Most of the times when using an API with flutter ang getting this type of error, adding header("Access-Control-Allow-Origin: *"); to the header might fix the issue
I am making a calendar app with flutter using googleApi library.
but, When you turn off the app, need to auth again in web site.
i want auth only first time.
is it possible?
// mycode
get _SCOPES => [CalendarApi.CalendarScope];
await clientViaUserConsent(_clientID, _SCOPES, prompt)
.then((AuthClient client) async {
CalendarClient.calendar = CalendarApi(client);
calendarId = await CalendarClient.calendar.calendarList
.list()
.then((value) => value.items[0].id);
});
void saveData(AccessCredentials credentials) {
GetStorage().write(credetialKey, {
"accessTokenData": credentials.accessToken.data,
"accessTokenExpiry": credentials.accessToken.expiry.toString(),
"refreshToken": credentials.refreshToken,
"scopes": credentials.scopes,
"idToken": credentials.idToken
});
}
AccessCredentials getCredetial() {
try {
var map = GetStorage().read(credetialKey);
return AccessCredentials(
AccessToken("Bearer", map["accessTokenData"] as String,
DateTime.parse(map["accessTokenExpiry"])),
map["refreshToken"],
map["scopes"].cast<String>(),
idToken: map["idToken"] as String);
} catch (e) {
return null;
}
}
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
authenticatedClient(cli, c);
error :
DetailedApiRequestError(status: 401, message: Request is missing required authentication credential. Expected OAuth 2 access tok
You can save user session using for example sharedPreferences. Each time the user launch the app your must first check if the session is saved so you can skip the auth process, otherwise you initiate the authentication
i solved it.
save AccessCredentials,
and use autoRefreshingClient;
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
cli = autoRefreshingClient(_clientID, c, cli);
I need use Auth0 with Flutter but there is no such SDK in Auth0 site.
Auth0 works to create such SDK for Flutter.
Did anyone use Auth0 with Flutter or what can you advise?
Its very simple to get started with flutter auth0
Have a class for auth0 and call this at the places you need them. But also be sure to set the constants AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_REDIRECT_URI, AUTH0_ISSUER
class Auth0 {
final FlutterAppAuth appAuth = FlutterAppAuth();
Map<String, Object> parseIdToken(String idToken) {
final List<String> parts = idToken.split('.');
assert(parts.length == 3);
return jsonDecode(
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))));
}
Future<Map<String, Object>> getUserDetails(String accessToken) async {
const String url = 'https://$AUTH0_DOMAIN/userinfo';
final http.Response response = await http.get(
url,
headers: <String, String>{'Authorization': 'Bearer $accessToken'},
);
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to get user details');
}
}
Future<void> loginAction() async {
isBusy = true;
errorMessage = 'Error! - ';
try {
final AuthorizationTokenResponse result =
await appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest(
AUTH0_CLIENT_ID,
AUTH0_REDIRECT_URI,
issuer: 'https://$AUTH0_DOMAIN',
scopes: <String>['openid', 'email', 'profile', 'offline_access'],
promptValues: ['login']
),
);
final Map<String, Object> idToken = parseIdToken(result.idToken);
final Map<String, Object> profile =
await getUserDetails(result.accessToken);
isBusy = false;
name = idToken['name'];
email = profile['email'];
picture = profile['picture'];
} on Exception catch (e, s) {
print('login error: $e - stack: $s');
isBusy = false;
errorMessage = e.toString();
}
}
Instead of using a boolean for checking isLoggedIn try saving the token in the localstorage and that will set the state as is.
There's an auth0 package for flutter to use Auth0 API provides login, logout and access APIs for authentication in your App. However, you need to make changes inside android and ios files in your flutter project. You need to configure your callbacks and application settings for that, The author has their example on github that you should check out.
I would advise you to follow the blog post provided by the Auth0 team -
Get Started with Flutter Authentication
For Flutter Web App, I am making a wrapper around Auth0 JS SPA SDK.
GitHub: https://github.com/anthonychwong/auth0-flutter-web
Pub.dev: https://pub.dev/packages/auth0_flutter_web
import 'package:auth0_flutter_web/auth0_flutter_web.dart';
Auth0 auth0 = await createAuth0Client(
Auth0CreateOptions(
domain: '-- domain of the universal login page --',
client_id: '-- id of your app --',
)
);
String token = await auth0.getTokenWithPopup();
It is in very early stage and PRs are welcome.