Authentification for Android without third-party library - android

Is there any way to authenticate using OAuth 2 without using third-party libraries other than Retrofit?

If you are talking about Bearer token based authentication you just need to add an "Authorization" header to your requests.
if you using HttpURLConnection
URL url = new URL("http://www.my-back-end.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", "Bearer yourToken");
urlConnection.setRequestMethod("POST"); // Can be GET or something else
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
parseResponse(in);
} finally {
urlConnection.disconnect();
}

Well mobile apps are encouraged to meet requirements in RFC8252, of which these are the two most important:
Users login via the system browser so that the app never sees the password. On Android the most user friendly way to do this is to use a Chrome Custom Tab, as used by Gmail and other secure apps.
A standards based Authorization Code Flow (PKCE) is used, including various security checks and a tricky HTTP language.
You could code this yourself, but Retrofit is based on JSON and OAuth messages are based on browser redirects and form URL encoded posts.
The recommended Android solution is to use AppAuth libraries to implement these requirements - my blog post shows how this looks and enables you to run a working app quickly. A full solution is not a quick job though and may require discussion with stakeholders.
There are potential benefits to the UX once OAuth is implemented, such as use of WebAuthn for secure password-less logins.

Related

Account Manager + Cookie Based Authentication

Is it possible to use Android Account Manager using Cookie-based authentication? How (a code with a explanation would be much appreciated)?
I have seen many examples regarding authentication token, but that is not the case. I have just implemented cookie-based authentication on Python FLASK.
OBS.: I'm using Android Volley for the requests of the application.
All you need to do is to add this line in onCreate in your Application class:
CookieHandler.setDefault(new CookieManager());
this line will make your HttpUrlConnection hold cookies like browser, and since most of the http agents like Volley or okHttp are based on HttpUrlConnection they also will hold your cookies )

How to check whether url scheme is Http or Https and create URLConnection depending on it

So basically right now my app is configured to use https because in the "release" it will use a self signed certificate and obviously also use Https.
My current testsystem (few more features) doesn't use https but http instead. I thought it would be kinda nice to have some type of method to check whether the given URL is Http or Https and depending on the result create the right URLConnection.
My current problem is that I don't know what the method should exactly look like. I thought about using if-statements in the methods which connect to my server but there might be a better solution.
Help would be appreciated.
How about this:
URLUtil.isHttpUrl(String url)
URLUtil.isHttpsUrl(String url)
See also: http://developer.android.com/reference/android/webkit/URLUtil.html
If you don't want to do a manual check you can use a 3rd party library like this one: http://square.github.io/okhttp/ which allows you a simple:
Request request = new Request.Builder().url(url).build();
Response response = new OkHttpClient().newCall(request).execute();

Android connect to Mysql database tutorial

Does anybody know a complete and working tutorial about how to retrieve data from MYSQL and display it in Android? I'm asking this because all the tutorials I found are older than API 22 and from API 22 the HttpClient is deprecated. And I'm a new Android Developer so I can't write any code on my own. :)
HttpClient
Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
This interface was deprecated in API level 22.
Please use openConnection() instead.
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.
Please visit this webpage for further details.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.
Uses of this class follow a pattern:
Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
For example, to retrieve the webpage at http://www.android.com/:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Please visit this webpage for further details.
http://developer.android.com/reference/java/net/HttpURLConnection.html
urlconnection tutorials, can visit this websites
+http://www.vogella.com/tutorials/AndroidNetworking/article.html
+http://javatechig.com/android/android-networking-tutorial

Securing Spring Rest service

I'm trying to implement a RESTful web service using Spring. I've set up Spring Security to work on the links that apply to the REST service. I make calls to this web service from an Android application. What I've done now is connect to it using Basic Authentication. What I'm struggling with is finding decent information about how secure this really is. I figure I should at least be making these calls through SSL or something no?
My code on the Android client that calls the REST client
public MyClass callRest() {
final String url = "http://10.0.2.2:8080/myservice/rest/getSomething";
HttpAuthentication authHeader = new HttpBasicAuthentication(username,
password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections
.singletonList(MediaType.APPLICATION_JSON));
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJacksonHttpMessageConverter());
try {
ResponseEntity<MyClass> response = restTemplate.exchange(url,
HttpMethod.GET, new HttpEntity<Object>(requestHeaders),
MyClass.class);
return response.getBody();
} catch (HttpClientErrorException e) {
return new MyClass();
}
}
So what I've put in my Spring Security config right now:
<http auto-config='true'>
<intercept-url pattern="/rest/**" access="ROLE_USER"
requires-channel="https" />
</http>
I can't figure out where to go from there, because now the connection doesn't work anymore of course because of the https. I can't seem to find decent examples of how to figure this out using the Resttemplate.
Any help?
HTTP Basic Authentication is reasonably safe when used over HTTPS since the user and password fields are sent over an encrypted connection so they are much less vulnerable to man-in-the-middle attacks. There are some interesting points here: Securing an API: SSL & HTTP Basic Authentication vs Signature
In my opinion, if you are making a API with access to user's sensitive data (i.e. bank account details, credit card numbers, email addresses and passwords) then you may want a more secure approach because HTTP Basic Authentication is succeptible to brute force attacks as it is always available (unless you build in deterrents such as maximum retries etc.) If your API is for a game or basic business data then there should be less attraction for a hacker to spend the time on it.
Does your server support HTTPS - often you need to pay extra for a HTTPS certificate or you have to use a shared once which give you a subdomain on a shared HTTPS domain - i.e. https//your-site.your-hosting-provider.com/. You need to check this perhaps.
UPDATE 1: Your problem appears to be with your server and not with your program. Check out this blog post for information about how to set up HTTPS on your Tomcat Server. You need to do this before you can use HTTPS from your Spring application - looking at your code, there doesn't seem to be a problem other than your server.
Also try this.
UPDATE 2 Once you have access, you will then need to trust the certificate on the Android device (or your Java installation if you were making a desktop/web application). It needs to be trusted because you created it yourself rather than a CA authority. See this answer: Trusting all certificates using HttpClient over HTTPS (Not the part about trusting all certificates - this can be dangerous).

Android - Basic Authenticated HTTP Request

So basically i need my android app to connect to a web service using a url as such
"http://username:password#0.0.0.0" aka basic authentication.
obviously the username and password are checked by the web app before allowing access and otherwise doesn't allow the request.
my issue is that all the methods i try always say unauthorised (response code 401) regardless of what combination of classes and methods ive used to try and connect to the the url.
The web app in question is designed to return things only is un/pw clears otherwise it returns nothing, the web app and un/pw etc have all be checked and cleared.
so does anyone no the correct way to send a request to a url like that and have it work correctly?
android api8 btw
UPDATE
Turns out my issue is due to the web app using NTLM windows authentication which is not supported directly by androids/apache http library, investigating appropriate workarounds now
Here's some code form a really old project of mine. I used basic auth for some web service, and this worked at the time. I'm not sure if there are updated api's since then (this was Android 1.6), but it should still work.
HttpGet request = new HttpGet();
request.setURI(new URI(url));
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(authUser, authPass);
BasicScheme scheme = new BasicScheme();
Header authorizationHeader = scheme.authenticate(credentials, request);
request.addHeader(authorizationHeader);
Basically, Basic HTTP auth is a simple hash of the user and password. The browser allows you to stuff these values in the url, but it actually does the work of adding the basic auth header to your request.

Categories

Resources