04 February 2017

Spring Security with Google SignIn



It is long time again. This time I think write some article about Spring security  with Google Signing .Last week I have worked project which need to integrate spring security with google sign in. So I think this would help developers who using spring security. This diagram shows  the use case I am going to resolve.




First step is to Add Google login button to web site. For that this documentation shows how to add google login button to website. If you follow up this steps you can add this kind of button to your website.


After you sign-in using gmail account it will return google auth token to browser.


In your sign.jsp page you need to add  web form with hidden  token field.
 

1
2
3
4
<form id="custom_form"
                  action="<c:url value='j_spring_security_check' />" method='POST'>
                <input id="formToken" type='hidden' name='token'/>
 </form>

Next spring-security.xml should be configured this way.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<sec:http auto-config="true" use-expressions="true">
        <sec:intercept-url pattern="/login" access="isAnonymous()" />
        <sec:intercept-url pattern="/logout" access="isAnonymous()" />
        <sec:intercept-url pattern="/access_denied" access="isAnonymous()" />
        <sec:intercept-url pattern="/*" access="hasRole('ROLE_ADMIN')" />

        <sec:form-login login-page="/login" authentication-failure-url="/access_denied"
                        password-parameter="token"
                        default-target-url="/home"/>

        <sec:logout logout-success-url="/logout"/>

</sec:http>

<sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider ref="authenticationProvider">
        </sec:authentication-provider>
</sec:authentication-manager>


<bean class="dev.innova.util.CustomAuthenticationProvider" id="authenticationProvider"/>


Then the last part is create custom Authentication Provider to validate user google auth token.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import dev.innova.util.UserAccount;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Value("${client.id}")
    private String CLIENT_ID;

    private static final Logger logger = LogManager.getLogger(CustomAuthenticationProvider.class.getName());

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String token = (String) authentication.getCredentials();
        NetHttpTransport transport = new NetHttpTransport();
        JsonFactory mJFactory = new GsonFactory();
        boolean validUser = false;
        GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, mJFactory)
                .setAudience(Collections.singletonList(CLIENT_ID))
                .build();

        UserAccount userAccount = new UserAccount();
        try {
            GoogleIdToken idToken = verifier.verify(token);
            if (idToken != null) {
                GoogleIdToken.Payload payload = idToken.getPayload();
                String email = payload.getEmail();
                String pictureUrl = (String) payload.get("picture");
                String userId = payload.getSubject();
                boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
                String name = (String) payload.get("name");
                userAccount.setEmailAddress(email);
                userAccount.setImageUrl(pictureUrl);
                validUser = isValidUser(email);
                logger.info("User Details Name [{}]",name);
                logger.info("User Details userId [{}]",userId);
                logger.info("User Details emailVerified [{}]",emailVerified);
                logger.info("User Details Image [{}]",pictureUrl);
            } else {
                logger.info("Invalid ID token.");
            }
        }catch (IllegalArgumentException exx){
            logger.error("Failed {}", exx.getMessage());
        }catch (GeneralSecurityException e) {
            logger.error("Failed {}", e.getMessage());
        } catch (IOException e) {
            logger.error("Failed {}", e.getMessage());
        }
        if (validUser) {
            logger.info("Valid User Found");
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            Authentication auth = new UsernamePasswordAuthenticationToken(userAccount, token, grantedAuths);
            return auth;
        } else {
            throw new BadCredentialsException("Username not found.");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        boolean equals = authentication.equals(UsernamePasswordAuthenticationToken.class);
        return equals;
    }

    /**
     *  Mock Method to validate Email
     * @param email
     * @return
     */
    private boolean isValidUser(String email){
        return true;
    }

}

Then we can create Custom UserDetails to save custom data. Which will help you to save user image, extra details.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

public class UserAccount implements UserDetails {

    private String userId;

    private String userName;

    private String emailAddress;

    private String imageUrl;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }
}

And that is it.You  can login user with google account and use spring security to secure.

06 November 2016

Easy Way to Create wrapper for Java Project

Most of the articles I have written for android related development issues. I thought need to write something new for java and spring related article.when I was in university when we running project what wed did was always run the project using IDE. But after joining to industry we know that we have to write executable file to run project in different environments. Let's say customer server may be windows, linux or mac .Then we have to create executable file which run in all platforms. If the project is simple what we can do is create executable jar and give to customer.

 But if the project contents configuration files this approach is not good.  Then we have to use better way to bundle executable files. So in this tutorial I will show you to how to create wrapper for java project but make sure you have to use maven.

First you have to add following property to pom.xml

1
2
3
<properties>
    <wrapper.location>${project.build.directory}/generated-resources/appassembler/jsw/#wrapper-name</wrapper.location>
</properties>

Then need to add following plugins to pom.xml and make sure change the main class and wrapper name.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-resources</id>
                <phase>process-classes</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/conf</outputDirectory>
                    <resources>
                        <resource>
                            <directory>${project.basedir}/src/main/resources</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
            <excludes>
                <exclude>**/*.yml</exclude>
                <exclude>**/*.txt</exclude>
            </excludes>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>appassembler-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
            <execution>
                <id>generate-jsw-scripts</id>
                <phase>package</phase>
                <goals>
                    <goal>generate-daemons</goal>
                </goals>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationDirectory>conf</configurationDirectory>
                    <daemons>
                        <daemon>
                            <id>#wrapper-name</id>
                            <wrapperMainClass>org.tanukisoftware.wrapper.WrapperSimpleApp</wrapperMainClass>
                            <mainClass>#Main-class</mainClass>
                            <commandLineArguments>
                                <commandLineArgument>start</commandLineArgument>
                            </commandLineArguments>
                            <platforms>
                                <platform>jsw</platform>
                            </platforms>
                            <generatorConfigurations>
                                <generatorConfiguration>
                                    <generator>jsw</generator>
                                    <configuration>
                                        <property>
                                            <name>wrapper.java.additional.1</name>
                                            <value>-Xloggc:logs/gclog</value>
                                        </property>
                                        <property>
                                            <name>wrapper.java.additional.2</name>
                                            <value>-XX:MaxDirectMemorySize=256M</value>
                                        </property>
                                        <property>
                                            <name>configuration.directory.in.classpath.first</name>
                                            <value>conf</value>
                                        </property>
                                        <property>
                                            <name>set.default.REPO_DIR</name>
                                            <value>lib</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile</name>
                                            <value>logs/wrapper.log</value>
                                        </property>
                                    </configuration>
                                    <includes>
                                        <include>linux-x86-32</include>
                                        <include>linux-x86-64</include>
                                    </includes>
                                </generatorConfiguration>
                            </generatorConfigurations>
                        </daemon>
                    </daemons>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.6</version>
        <executions>
            <execution>
                <id>make-log-dir</id>
                <phase>package</phase>
                <configuration>
                    <tasks>
                        <mkdir dir="${wrapper.location}/logs" />
                        <copy todir="${wrapper.location}/conf">
                            <fileset dir="target/conf" />
                        </copy>
                        <chmod dir="${wrapper.location}/bin" includes="**/*" perm="0755" />
                    </tasks>
                </configuration>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
            <descriptor>src/assembly/dep.xml</descriptor>
            <finalName>#app-name</finalName>
        </configuration>
        <executions>
            <execution>
                <id>create-archive</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>




And final Step is need to add assembly file to your project. Create assembly folder inside src folder and put the following dep.xml file in to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>bin</id>
<formats>
    <format>zip</format>
</formats>
<fileSets>
    <fileSet>
        <directory>${wrapper.location}</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
</fileSets>
</assembly>

And now you can see the wrapper-name.zip file in target folder. after extracting it inside the bin folder four executable files are there and bat file for windows and wrapper for linux . All the dependency jar files are under lib folder. and configurations in conf folder. Now in this way we can easily handle projects. Hope now you will learn something from my tutorial.

Android Dynamically Change Style colors

In this Tutorial I will discuss How to Change Android Style theme colors. Last few days I had to I have searched how to change android theme style color dynamically but android doesn't support to change theme colors dynamically. (Note :You can changed android pre-defined theme styles dynamically not the dynamic generated themes)

If we using Theme.AppCompat.Light.DarkActionBar then these are the main properties in layout.



If You want to change theme what you did was change the primary color and primaryDark color. And this code helps you to dynamically change the theme (above mention colors) colors.

This is for change primary Dark color.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static void setStatusBarColor(String color) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = currentActivity.getWindow();
        int statusBarColor = Color.parseColor(color);

        if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }
        window.setStatusBarColor(statusBarColor);
    }
}




This is for change primary color


1
2
getSupportActionBar().setBackgroundDrawable(
        new ColorDrawable(Color.parseColor("#AA3939")));



I hope this article help you to resolve your problem.
Thanks

07 August 2016

Android Realm Db Tutorial

These Days I have worked with android realm db project. So After done the project I thought It is better to write post about Realm db with android.

What Is Realm ??


Realm Db is No SQL framework which support android, ios to persistence data in mobile devices. When I start develop application with android there were few frameworks which support persistence. I worked with sqlite but the problem is It is hard to understand and write data and retrieve data.  But Realm db is the best android persistence framework I have ever seen. The main advantage is there is no sql syntax or queries . It is easy to understand  and implement.


This Diagram shows the simplicity of Realm db.



Configuration for android realm project

Add the following dependency to main project.


1
classpath "io.realm:realm-gradle-plugin:1.1.0"

Add the following dependency to sub project build.gradle file.
   
   Add the following line top of the build gradle file.

1
apply plugin: 'realm-android'

How to use Realm

Realm can be used any insert,update,delete operations in database. But unlikely sqlite realm gives easy way to handle data base operations . In here I will not show all the things in realm because realm documentation is better than my blog. So first we need realm object because realm object is a main concept in realm.

Let's say I need to add sales merchants to sales merchant table . First I create merchant object like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class SalesMerchant extends RealmObject {

    @PrimaryKey    private String id;

    private String name;

    private String address;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
Let's insert first data to realm db. First I will add the db 
configuration class to my project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import android.content.Context;

import io.realm.Realm;
import io.realm.RealmConfiguration;


public class DBConfiguration {

    private static String REALM_NAME = "sajith-blog.realm";

    public Realm getRealm(Context context) {
        Realm myOtherRealm = Realm.getInstance(
                new RealmConfiguration.Builder(context)
                        .name(REALM_NAME)
                        .build()
        );
        return myOtherRealm;
    }

}
Then Final stage write factory class to add data to database.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import domain.db.SalesMerchant;
import io.realm.Realm;


public class MerchantFactory {
    private Realm realm;

    public MerchantFactory(Realm realm) {
        this.realm = realm;
    }

    public void insertMerchant(final SalesMerchant salesMerchant) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override            public void execute(Realm bgRealm) {
                SalesMerchant addProduct = bgRealm.createObject(SalesMerchant.class);
                addProduct.setName(salesMerchant.getName());
                addProduct.setId(salesMerchant.getId());
                addProduct.setAddress(salesMerchant.getAddress());
            }
        });
    }

}
And that is it now you can see your data stored in database.
It is easy to handle transactions in realm db.
This tutorial is simple introduction of realm db. I just want to show how easy to use realm  and next tutorial i hope to go deep how to handle relationships in realm objects , Handle in different threads ,how to automatically populate db change in UI thread and other advanced techniques .


30 May 2016

Swagger with Dropwizard

In this post I will discuss how to integrate swagger in to dropwizard project.If you new to dropwizard this will help you to understand what is the dropwizard. So swagger is api documentation tool . For get basic knowledge swagger this will helps. But today I will integrate swagger in to dropwizard.

First you need to add this dependency to your project.

1
2
3
4
5
<dependency>
    <groupId>com.smoketurner</groupId>
    <artifactId>dropwizard-swagger</artifactId>
    <version>0.9.2-3</version>
</dependency>

And next thing is using annotation you have to document  resource class. This is the example of how to use swagger anotation.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Path("/studentManagement/api/")
@Api(value = "Student Management API", description = "Student Management API")
public interface StudentManagement {
    @GET
    @PermitAll
    @Path("/getAllStudent")
    @ApiOperation(value = "Get All Students")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "Error Occurred 
                                                     while getting data"),
            @ApiResponse(code = 404, message = "Student not found"),
            @ApiResponse(code = 405, message = "Validation exception") })
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Response getAllStudents();

    @GET
    @PermitAll
    @Path("/getStudent")
    @ApiOperation(value = "Get Students by Name")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "Error Occurred 
                                                     while getting data"),
            @ApiResponse(code = 404, message = "Student not found"),
            @ApiResponse(code = 405, message = "Validation exception") })
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    Response getStudent(@QueryParam("name") String name,
                                 @QueryParam("age") int age);
}

And next step is you need add this swagger configuration to your dropwizard configuration class.


1
2
@JsonProperty("swagger")
    public SwaggerBundleConfiguration swaggerBundleConfiguration

And next step is in your dropwizard application you need to add swagger configuration bundle.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Override
    public void initialize(Bootstrap bootstrap) {
        bootstrap.addBundle(new SwaggerBundle() {
            @Override
            protected SwaggerBundleConfiguration 
                  getSwaggerBundleConfiguration(StudentManagementServerConfiguration configuration) {
                return configuration.swaggerBundleConfiguration;
            }
        });
    }
Last step is need to add your resource class package to yaml configuration file.


1
swagger:   resourcePackage: dev.innova.student.api




And that is all for this blog post.If you have any issue please
comment here.Thanks

29 March 2016

Introduction to Json Web Token




JSON web tokens are specifically for pass data between two parties securly.It is a industry standard protocol format.[https://tools.ietf.org/html/rfc7519]. In this tutorial i am mainly going to talk about how JWT is useful for client to server communication.Let’s assume you have http client and you need to communicate to rest server.So basically there are different ways to secure your connection.


  1. HTTPS
  2. User name password based authentication
  3. Pass custom secure   element using http header.

We all know that HTTPS is the secure way to communicate via HTTP protocol. But it is costly.So token based authentication gives the best security for your API design.


Usage Of JWT


JWT use for token based authentication.Token based authentication helps to authenticate server and client stateless. So No need to store client data in server side(Like sessions).

So Let’s see how JWT work in API.First when client login using username and password Then server validate the credentials and generate sign token and sent to client.Then client store token and every request send token with header.Then server verify the token and validate request.

Structure of JWT


Jason web token is this type.
aaaaa.bbbbbb.cccc So It have three parts.

Header
Payload
Signature

Header contains algorithm and type of token.

Payload is simply data you want to exchange two parties. These data type called as clams. There are two type of clams (Public and Private).
Ex:-
iss (issuer)
exp (expiration time)
sub (subject)
aud (audience)

Signature is the most advance part in web token. signature made using using this structure. Algorithem(base64urlencode(header) +"."base64urlencode(payload)+ secret)

Implementation Of JWT

There are lot of libraries available for creating and validate JSON web tokens.In this tutorial I have used this library.


1
2
3
4
5
<dependency>
    <groupid>org.bitbucket.b_c</groupid>
    <artifactid>jose4j</artifactid>
    <version>0.4.4</version>
</dependency>

Create JASON web token.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public String generateToken(String userName) {
        String jwt = null;
        try {
            JwtClaims claims = new JwtClaims();
            claims.setIssuer(userName);
            claims.setExpirationTimeMinutesInTheFuture(expiryTimeInMinutes);
            claims.setGeneratedJwtId();
            claims.setIssuedAtToNow();
            claims.setNotBeforeMinutesInThePast(beforeTimeTest);
            claims.setSubject(subject);


            JsonWebSignature jws = new JsonWebSignature();
            jws.setPayload(claims.toJson());
            jws.setKey(rsaJsonWebKey.getPrivateKey());
            jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
            jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

            jwt = jws.getCompactSerialization();
            logger.info("Token Created {}", jwt);

        } catch (JoseException e) {
            logger.error("Creating Token Failed {}", e);
        } catch (Exception ex) {
            logger.error("Error occurred while Creating Token {}", ex);
        }
        return jwt;
    }
Most important thing is creating token we can set expiration time so when authentication token from server side if token is expired then it helps to easily authenticate token.As example when user first login to system we create token send and then sequentially request by request client append that token to header and send to server.

Validating Web Token


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public boolean validateToken(String token) {
        boolean state;
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime()
                .setAllowedClockSkewInSeconds(30)
                .setRequireSubject()
                .setRequireExpirationTime()
                .setVerificationKey(rsaJsonWebKey.getKey())
                .build();

        try {
            JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
            long expiredDateTime = jwtClaims.getExpirationTime().getValueInMillis();
            Date date = new Date(expiredDateTime);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.info("Token Expired Date : " + simpleDateFormat.format(date));
            state = true;
        } catch (InvalidJwtException e) {
            state = false;
            logger.debug("Error Occurred while validating JWT {}", e);
        } catch (MalformedClaimException e) {
            state = false;
        }
        return state;
    }

Above method validate Web Token if token expired it will throw exception. Hope you got some understand what is JSON web token and usage of web tokens.If you have any question feel free to comment in here.Thanks.