18 Web Service Using Laravel and Android
18 Web Service Using Laravel and Android
Applications
Web Service using Laravel and Android
ADF
1 08/10/2024
Web Service
A method of communication between two
electronic devices over a network
– a software function provided at a network address over
the Web with the service always on as in the concept of
utility computing
W3C
– a software system designed to support interoperable
machine-to-machine interaction over a network
2 08/10/2024
Web Service
"Web services" describes a standardized way of integrating
Web-based applications using the XML, SOAP, WSDL and
UDDI open standards over an Internet protocol backbone
3 08/10/2024
two major classes of Web services
REST-compliant Web services
– the primary purpose of the service is to manipulate
representations of Web resources using a uniform set of
stateless operations
4 08/10/2024
Web Sites and Web Services
Web Sites
– Interactive interface for data presentation
– Present information
– Open in web browsers
Web Services
– Interface is somewhat that you can see
– Provide information
– Open in all-type client application
5 08/10/2024
Web Sites and Web Services
6 08/10/2024
Web Service Benefit
Interoperability
– interfaces are completely understood, to work with other
products or systems, present or future, without any restricted
access or implementation
DCOM only for Windows, RMI only for Java
Firewall Traversal
– establish and maintain Internet protocol connections across
gateways that implement network address translation (NAT)
Using standard port
Complexity
– Developer friendly
7 08/10/2024
Web Services - Components
XML
– eXtensible Markup Language
SOAP
– Simple Object Access Protocol
UDDI
– Universal Description, Discovery and Integration
specification
WSDL
– Web Services Description Language
8 08/10/2024
Simple Object Access Protocol
a protocol specification for exchanging structured
information in the implementation of web services
in computer networks
uses XML Information Set for its message format,
and relies on other application layer protocols,
most notably Hypertext Transfer Protocol (HTTP)
or Simple Mail Transfer Protocol (SMTP), for
message negotiation and transmission.
9 08/10/2024
Web Services Description Language
an XML-based language for describing web
services and how to access them.
describes a web service, along with the message
format and protocol details for the web service.
10 08/10/2024
Representational State Transfer
software architectural style of the World Wide
Web.
gives a coordinated set of constraints to the
design of components in a distributed hypermedia
system that can lead to a higher-performing and
more maintainable architecture
11 08/10/2024
12 08/10/2024
Web Service using Laravel API
We already build our API from the last lesson
Next:
– Build token-based authentication
JSON Web Tokens
– Create Android App to communicate to the API
13 08/10/2024
Authentication
Server Based Authentication (The Traditional
Method)
– store the user logged in information on the server.
– This can be done in a few different ways on the session,
usually in memory or stored on the disk.
Token-Based Authentication
– User receive a “token” key after logged in
– Send token along with the request to authenticate
14 08/10/2024
Server Based
Authentication
15 08/10/2024
Problem with Server Based
Authentication
Sessions:
– Every time a user is authenticated, the server will need to
create a record. The overhead on server increased as the
user increased.
Scalability:
– having vital information in session memory will limit the
ability to scale.
16 08/10/2024
Problem with Server Based
Authentication
Cross-origin Resource Sharing :
– When using AJAX calls to grab resources from another
domain (mobile to our API server), we could run into
problems with forbidden requests.
17 08/10/2024
Token-based Authentication
General concept:
– Allow users to enter their username and
password in order to obtain a token which allows
them to fetch a specific resource - without using
their username and password.
– Once their token has been obtained, the user
can offer the token - which offers access to a
specific resource for a time period - to the
remote site
18 08/10/2024
Token-Based
Authentication
19 08/10/2024
Benefit using Token-Based
Authentication
Stateless and Scalable:
– stored on client side
– No session information means your application can scale
and add more machines as necessary without worrying
about where a user is logged in
Security
– no session based information to manipulate
– no cookie being sent, this helps to prevent CSRF attacks
– The token also expires after a set amount of time, so a
user will be required to login once again
20 08/10/2024
Benefit using Token-Based
Authentication
Extensibility
– Allow us to build applications that share permissions with
another
– provide selective permissions to third-party applications.
21 08/10/2024
Setting Laravel JWT-Auth
Add require tymon/jwt-auth
– composer require tymon/jwt-auth
– composer update
22 08/10/2024
Setting Laravel JWT-Auth
Update the providers and alias array in
config/app.php
'providers' => [
...
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
...
],
'aliases' => [
...
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class
],
\config\app.php
23 08/10/2024
Setting Laravel JWT-Auth
Publish assets for this package
– php artisan vendor:publish --provider="Tymon\
JWTAuth\Providers\JWTAuthServiceProvider“
24 08/10/2024
Setting Laravel JWT-Auth
Add jwt-auth in middleware routes
– Modify kernel.php
...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class
];
...
\app\Http\Kernel.php
25 08/10/2024
Setting Laravel JWT-Auth
Add authenticate method in APIController
...
public function authenticate(Request $request){
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials))
{
return response()->json(['error' =>
'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' =>
'could_not_create_token‘
], 500);
} \app\Http\Contollers\APIController.php
return response()->json(compact('token'));
}
26 ...
08/10/2024
Setting Laravel JWT-Auth
Add authenticate route in routes.php
...
Route::group(['prefix' => 'api/v1'], function()
{
Route::post('authenticate','APIController@authenticate');
Route::resource('authors','AuthorsAPIController');
Route::resource('books','BooksAPIController');
Route::resource('authors.books','BooksAPIController',
['only' => ['index', 'show']]);
});
...
\app\Http\routes.php
27 08/10/2024
Setting Laravel JWT-Auth
Modify the middleware setting in
AuthorsAPIController
– Change from auth.basic into jwt.auth
...
function __construct(AuthorTransformer $authorTransformer){
$this->middleware('jwt.auth',['only' => 'store']);
$this->authorTransformer = $authorTransformer;
}
...
\app\Http\Contollers\AithorsAPIController.php
28 08/10/2024
Test our API
29 08/10/2024
Test our API
30 08/10/2024
Test our API
31 08/10/2024
Test our API
32 08/10/2024
Android App
Application send Http request POST
– (and later GET)
33 08/10/2024
Android App
Modify gradle
– Since the old apache http lib is deprecated since API 22
– Open build.gradle Module App
– Add useLibrary ‘org.apache.http.legacy’
...
android {
useLibrary 'org.apache.http.legacy'
...
34 08/10/2024
UI Layout
2 views
– Login panel view
Email input text
Password input text
Login button
– Input panel view
Author Name
Gender Radio Group
Add button
35 08/10/2024
UI Layout
36 08/10/2024
UI Layout – Login Panel
37 08/10/2024
UI Layout – Input Panel
38 08/10/2024
Post Request Class
Create Post request class extends Asynchronous
Task
public class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
private Context context;
private String Server = "http://192.168.56.1/tugas5/public/api/v1/";
...
SendPostReqAsyncTask.java
39 08/10/2024
Post Request Class
Implement doInBackground method
List all parameters
...
@Override
protected String doInBackground(String... params) {
String paramTarget = params[0];
String paramValue[][] = new String[params.length / 2][2];
int j = 0;
for (int i = 1; i < params.length; i += 2) {
paramValue[j][0] = params[i];
paramValue[j][1] = params[i + 1];
j++;
}
...
42 08/10/2024
Post Request Class
Override onPostExecute() method
Send result to MainActivity (we will make setObject method later)
...
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObject = new JSONObject(result);
if (jObject.has("token")) {
Toast.makeText(context, "Login Accepted",
Toast.LENGTH_LONG).show();
((MainActivity) context).setjObject(jObject);
} else if (jObject.has("message")) {
Toast.makeText(context, "message: " +
jObject.getString("message"),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, jObject.getString("error"),
Toast.LENGTH_LONG).show();
} SendPostReqAsyncTask.java
} catch (JSONException e) {e.printStackTrace();}
}
43 08/10/2024
...
Main Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
...
MainActivity.java
44 08/10/2024
Main Activity
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
45 08/10/2024
Main Activity
...
public void onRadioButtonClicked(View view) {
switch (view.getId()) {
case R.id.f:
if ((RadioButton)
view).isChecked()) {
...
47 08/10/2024
Main Activity
...
@Override
public void onClick(View v) {
if (v.getId() == R.id.loginBtn) {
String givenUsername = userName.getEditableText().toString();
String givenPassword = password.getEditableText().toString();
if (CheckFields()) {
sendLoginRequest(givenUsername, givenPassword);
}
} else if (v.getId() == R.id.addBtn) {
String givenName = authorName.getEditableText().toString();
sendPostRequest(givenName, gender);
}
}
...
MainActivity.java
48 08/10/2024
Main Activity
...
public void setjObject(JSONObject jObject) throws JSONException {
this.jObject = jObject;
if (this.jObject.has("token")) {
this.token = this.jObject.getString("token");
System.out.println(this.token);
loginPanel.setVisibility(View.GONE);
inputPanel.setVisibility(View.VISIBLE);
}
}
...
MainActivity.java
49 08/10/2024
Get JSON
Create Class to send Get Request
Create new Activity to receive JSON response
– Main2Activity.java
50 08/10/2024
Get Request Class
Create Get request class extends Asynchronous
Task
public class SendGetReqAsyncTask extends AsyncTask<String, Void, String> {
private Context context;
private String Server = "http://192.168.56.1/tugas5/public/api/v1/";
SendGetReqAsyncTask.java
51 08/10/2024
Get Request Class
...
@Override
protected String doInBackground(String... params) {
String paramTarget = params[0];
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResp = httpclient.execute(new
HttpGet(Server+ paramTarget));
inputStream = httpResp.getEntity().getContent();
if (inputStream != null)
result =
convertInputStreamToString(inputStream);
else
result = "Failed to Fetch Data";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result; SendGetReqAsyncTask.java
}
52
... 08/10/2024
Get Request Class
...
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, "Received!", Toast.LENGTH_LONG).show();
((Main2Activity) context).setResponseText(result);
}
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
SendGetReqAsyncTask.java
result += line;
inputStream.close();
53 08/10/2024 return result;
UI Layout – Get Response Panel
54 08/10/2024
Activity Main 2
public class Main2Activity extends AppCompatActivity {
private EditText responseTab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
responseTab = (EditText) findViewById(R.id.responseTab);
getAuthorsRequest();
}
Main2Activity.java
55 08/10/2024
Activity Main 2
...
public void setResponseText(String text) {
JSONObject json = null;
try {
json = new JSONObject(text);
responseTab.setText(json.toString(1));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main2Activity.java
56 08/10/2024
Test Application
57 08/10/2024
Test Application
58 08/10/2024
THANK YOU
08/10/2024
59