{"id":706,"date":"2019-05-11T10:34:26","date_gmt":"2019-05-11T10:34:26","guid":{"rendered":"https:\/\/sindhitutorials.com\/blog\/?p=706"},"modified":"2019-05-11T10:57:15","modified_gmt":"2019-05-11T10:57:15","slug":"spring-security-jwt-token-authentication-in-spring-boot","status":"publish","type":"post","link":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/","title":{"rendered":"Spring Security JWT token authentication in Spring boot"},"content":{"rendered":"\n<p>Firstly in this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Overview<\/h2>\n\n\n\n<p>We will use spring security, spring data JPA, MySQL. We will write following config classes  Initial Data Loader, <strong>JWT Authentication Filter<\/strong>, <strong>JWT Login Filter<\/strong>, <strong>Token Authentication Service<\/strong> and <strong>Web Security Config<\/strong><\/p>\n\n\n\n<section class=\"crelated-posts\">\n   <h2>Related posts:<\/h2>\n   <div class=\"fr-wrap\">\n      <div class=\"fr-item\">\n         <h3><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/spring-mvc-configuration-hibernate\">Spring MVC Configuration with Hibernate in Eclipse-maven-JQuery-JSON-CRUD\n<\/a><\/h3>\n         <p>Most of the people stuck when they are trying to configure Spring MVC project first time and They don\u2019t know about Each of statement or file.<\/p>\n         <p><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/spring-mvc-configuration-hibernate\">Read more<\/a> \u2192<\/p>\n      <\/div>\n      <div class=\"fr-item\">\n         <h3><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/static-resources-spring-mvc-images-css-javase\">How to add static resources in Spring MVC Java Images CSS\n<\/a><\/h3>\n         <p>It is a descriptive videos tutorial for using static resources like Images, CSS and Javascript in Spring mvc.<\/p>\n         <p><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/static-resources-spring-mvc-images-css-javase\">Read more<\/a> \u2192<\/p>\n      <\/div>\n      <div class=\"fr-item\">\n         <h3><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/file-upload-spring-mvc-jquery-ajax\">File Upload Spring MVC &#8211; Maven &#8211; JQuery &#8211; JavaScript &#8211; Ajax\n<\/a><\/h3>\n         <p>The Project &#8220;Chat Messenger Java Project Code&#8221; is an example of Java Chat App.<\/p>\n         <p><a href=\"https:\/\/sindhitutorials.com\/videos\/spring-mvc-hibernate-maven\/file-upload-spring-mvc-jquery-ajax\">Read more<\/a> \u2192<\/p>\n      <\/div>\n   <\/div>\n<\/section>\n\n\n\n<p>The first thing is to find out that what are the required dependencies. In short we need following dependencies in our project <strong>spring boot<\/strong>, <strong>spring security<\/strong>, <strong>JPA<\/strong> and <strong>JDBC<\/strong> java&nbsp;connector.<\/p>\n\n\n\n<p>Required Maven Dependencies for following purposes:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>WEB, Restful and Spring MVC.<\/li><li>Writing unit test cases, It also default requirement in spring.<\/li><li>Spring Security.<\/li><li>Spring Data, JPA and Hibernate.<\/li><li>JDBC driver type 4 for MySQL.<\/li><li>JSON Web.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">2. Project Setup<\/h2>\n\n\n\n<p>We are using IntelliJ IDE for this project. In the project setup, You will see each file&#8217;s usage and it&#8217;s purpose so that You could understand easily project setup. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Setup-1.png\" alt=\"Spring Security JWT token authentication in Spring boot - Project Setup First Look\" class=\"wp-image-711\" width=\"360\" height=\"339\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Setup-1.png 360w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Setup-1-300x283.png 300w\" sizes=\"auto, (max-width: 360px) 100vw, 360px\" \/><figcaption>Project Setup First Look<\/figcaption><\/figure><\/div>\n\n\n\n<p>In above figure you can see list of directories and list of files. Some directories and files are important to describe their usage for example source directory and target directory.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Src directory<\/strong>is used for writing Java Source code and Unit test cases.<\/li><li>Development file is saved into <strong>target directory<\/strong>.<\/li><li>When you need any dependency \/ library in your project then you just need to add an entry in <strong>pom<\/strong> file. It imports all dependencies in the project.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"> 2.1 Adding dependencies into pom.xml file <\/h3>\n\n\n\n<p>Adding all required dependencies in <strong>pom.xml<\/strong> file because we need libraries in our project.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;project xmlns=&quot;http:\/\/maven.apache.org\/POM\/4.0.0&quot; xmlns:xsi=&quot;http:\/\/www.w3.org\/2001\/XMLSchema-instance&quot;\n\t\t xsi:schemaLocation=&quot;http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd&quot;&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\n\t&lt;groupId&gt;com.example&lt;\/groupId&gt;\n\t&lt;artifactId&gt;demo&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n\t&lt;packaging&gt;jar&lt;\/packaging&gt;\n\n\t&lt;name&gt;demo&lt;\/name&gt;\n\t&lt;description&gt;Demo project for Spring Boot&lt;\/description&gt;\n\n\t&lt;parent&gt;\n\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t&lt;artifactId&gt;spring-boot-starter-parent&lt;\/artifactId&gt;\n\t\t&lt;version&gt;2.0.8.RELEASE&lt;\/version&gt;\n\t\t&lt;relativePath\/&gt; &lt;!-- lookup parent from repository --&gt;\n\t&lt;\/parent&gt;\n\n\t&lt;properties&gt;\n\t\t&lt;project.build.sourceEncoding&gt;UTF-8&lt;\/project.build.sourceEncoding&gt;\n\t\t&lt;project.reporting.outputEncoding&gt;UTF-8&lt;\/project.reporting.outputEncoding&gt;\n\t\t&lt;java.version&gt;1.8&lt;\/java.version&gt;\n\t&lt;\/properties&gt;\n\n\t&lt;dependencies&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-web&lt;\/artifactId&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-test&lt;\/artifactId&gt;\n\t\t\t&lt;scope&gt;test&lt;\/scope&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-security&lt;\/artifactId&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;\/artifactId&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;!-- https:\/\/mvnrepository.com\/artifact\/mysql\/mysql-connector-java --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;mysql&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;mysql-connector-java&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;8.0.15&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;io.jsonwebtoken&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;jjwt&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;0.7.0&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t&lt;\/dependencies&gt;\n\n\t&lt;build&gt;\n\t\t&lt;plugins&gt;\n\t\t\t&lt;plugin&gt;\n\t\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t\t&lt;artifactId&gt;spring-boot-maven-plugin&lt;\/artifactId&gt;\n\t\t\t&lt;\/plugin&gt;\n\t\t&lt;\/plugins&gt;\n\t&lt;\/build&gt;\n\n\n&lt;\/project&gt;\n<\/pre><\/div>\n\n\n<p>You can see that I have inserted all required dependencies into pom file because we need libraries in our project. <\/p>\n\n\n\n<p>There is maven project component so in this component we can clean and install maven project.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Default-Maven-Plugin.png\" alt=\"Default Maven Plugin In IntelliJ\" class=\"wp-image-716\" width=\"247\" height=\"350\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Default-Maven-Plugin.png 247w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Default-Maven-Plugin-212x300.png 212w\" sizes=\"auto, (max-width: 247px) 100vw, 247px\" \/><figcaption>Default Maven Plugin In IntelliJ<\/figcaption><\/figure><\/div>\n\n\n\n<p>In above figure you can see maven life cycle and life of commands.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.2 Project directory structure<\/h3>\n\n\n\n<p>I am creating each separate package for each section for example <strong>configuration<\/strong>, <strong>controllers<\/strong>, <strong>entities<\/strong>, <strong>repositories<\/strong> and <strong>services<\/strong>. Application properties reside into resources directory. Let&#8217;s see structure and then start to write application properties first. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Structure.png\" alt=\"Project Structure\" class=\"wp-image-717\" width=\"358\" height=\"389\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Structure.png 358w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Structure-276x300.png 276w\" sizes=\"auto, (max-width: 358px) 100vw, 358px\" \/><figcaption>Project Structure<\/figcaption><\/figure><\/div>\n\n\n\n<p>In above figure you can find each separate package moreover in the resources directory you will find application.properties.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.3 Application Properties <\/h3>\n\n\n\n<p>In the <strong>application.properties<\/strong> file we always assign custom property values to the application configuration because an application configuration needs custom config values for example <strong>database name<\/strong>, <strong>database username<\/strong>, <strong>database password<\/strong>, <strong>server port<\/strong> etc.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: xml; title: ; notranslate\" title=\"\">\nserver.port = 8090\n\n# create and drop tables and sequences, loads import.sql\nspring.jpa.hibernate.ddl-auto=create-drop\n\n#MySQL database\nspring.datasource.driver-class-name=com.mysql.jdbc.Driver\nspring.datasource.url=jdbc:mysql:\/\/localhost:3306\/test?autoReconnect=true\nspring.datasource.username=root\nspring.datasource.password=12345\n\n# logging\nlogging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n\nlogging.level.org.hibernate.SQL=debug\n<\/pre><\/div>\n\n\n<p>MySQL database is running on local machine therefore we used localhost in database URL and schema name.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. Write Project Code<\/h2>\n\n\n\n<p>Before starting to write code, Let&#8217;s check project structure first.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"351\" height=\"505\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Code-Structure.jpg\" alt=\"Spring Security JWT token authentication in Spring boot - Project Code Structure\" class=\"wp-image-735\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Code-Structure.jpg 351w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/04\/Spring-Security-JWT-token-authentication-in-Spring-boot-Project-Code-Structure-209x300.jpg 209w\" sizes=\"auto, (max-width: 351px) 100vw, 351px\" \/><figcaption>Project Code Structure<\/figcaption><\/figure><\/div>\n\n\n\n<p>In project structure you can find five different packages in the project. You may see a package for configuration For example, <strong>config<\/strong> package contains web security configuration class, jwt token authentication config classes. You also can find <strong>controllers<\/strong>, <strong>repositories<\/strong>, <strong>entities <\/strong>and <strong>services<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.1 Default Package<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">3.1.1 DemoApplication<\/h4>\n\n\n\n<p>In default package you will find <strong>DemoApplication.java<\/strong> which contains main method in other words It is starting point of the application.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.EnableAutoConfiguration;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RestController\n@EnableAutoConfiguration\n@ComponentScan(basePackages = {\"com.example.demo\"})\npublic class DemoApplication {\n\n\t@RequestMapping(\"\/\")\n\tpublic String hello(){\n\t\treturn \"Hello World\";\n\t}\n\n\tpublic static void main(String&#x5B;] args) {\n\t\tSpringApplication.run(DemoApplication.class, args);\n\t}\n\n\t@Bean\n\tpublic BCryptPasswordEncoder bCryptPasswordEncoder() {\n\t\treturn new BCryptPasswordEncoder();\n\t}\n}\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\"><li><strong>@SpringBootApplication;<\/strong> we put this annotation instead of auto-configuration, component-scan and extra configuration.<\/li><li><strong>@RestController;<\/strong> we place this annotation instead of @Controller and @ResponseBody.<\/li><li><strong>@EnableAutoConfiguration;<\/strong> we place this annotation for enabling auto configuration for beans so those are present at the classpath.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3.2 Config Package<\/h3>\n\n\n\n<p>Config package consists of all configuration classes so configuration for Spring security, JWT authentication and Web Configuration etc<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"> 3.2.1<strong>AccountCredentials.java<\/strong> <\/h4>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\n\/**\n * Created by sadiq.odho on 9\/11\/2018.\n *\/\npublic class AccountCredentials {\n    private String username;\n    private String password;\n\n    public String getUsername() {\n        return username;\n    }\n\n    public void setUsername(String username) {\n        this.username = username;\n    }\n\n    public String getPassword() {\n        return password;\n    }\n\n    public void setPassword(String password) {\n        this.password = password;\n    }\n}\n\n<\/pre><\/div>\n\n\n<p><strong>AccountCredentials;<\/strong> It is a very simple entity class which contains two properties for instance username and password.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.2 InitialDataLoader.java<\/h4>\n\n\n\n<p>Following class is used for saving a single user with role and privilege which is done when application listener is called. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\nimport com.example.demo.entities.Privilege;\nimport com.example.demo.entities.Role;\nimport com.example.demo.entities.User;\nimport com.example.demo.repositories.PrivilegeRepository;\nimport com.example.demo.repositories.RoleRepository;\nimport com.example.demo.repositories.UserRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.context.event.ContextRefreshedEvent;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.stereotype.Component;\n\nimport javax.transaction.Transactional;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\n\n\/**\n * Created by sadiq.odho on 2\/1\/2019.\n *\/\n\n@Component\npublic class InitialDataLoader implements\n        ApplicationListener&lt;ContextRefreshedEvent&gt; {\n\n    boolean alreadySetup = false;\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Autowired\n    private RoleRepository roleRepository;\n\n    @Autowired\n    private PrivilegeRepository privilegeRepository;\n\n    @Autowired\n    private PasswordEncoder passwordEncoder;\n\n    @Override\n    @Transactional\n    public void onApplicationEvent(ContextRefreshedEvent event) {\n\n        if (alreadySetup)\n            return;\n        Privilege readPrivilege\n                = createPrivilegeIfNotFound(&quot;READ_PRIVILEGE&quot;);\n        Privilege writePrivilege\n                = createPrivilegeIfNotFound(&quot;WRITE_PRIVILEGE&quot;);\n\n        List&lt;Privilege&gt; adminPrivileges = Arrays.asList(\n                readPrivilege, writePrivilege);\n        createRoleIfNotFound(&quot;ROLE_ADMIN&quot;, adminPrivileges);\n        createRoleIfNotFound(&quot;ROLE_USER&quot;, Arrays.asList(readPrivilege));\n\n        Role adminRole = roleRepository.findByName(&quot;ROLE_ADMIN&quot;);\n        User user = new User();\n        user.setName(&quot;First Name&quot;);\n        user.setPassword(passwordEncoder.encode(&quot;test&quot;));\n        user.setEmail(&quot;test@test.com&quot;);\n        user.setRoles(Arrays.asList(adminRole));\n        user.setEnabled(true);\n        userRepository.save(user);\n\n        alreadySetup = true;\n    }\n\n    @Transactional\n    private Privilege createPrivilegeIfNotFound(String name) {\n\n        Privilege privilege = privilegeRepository.findByName(name);\n        if (privilege == null) {\n            privilege = new Privilege();\n            privilege.setName(name);\n            privilegeRepository.save(privilege);\n        }\n        return privilege;\n    }\n\n    @Transactional\n    private Role createRoleIfNotFound(\n            String name, Collection&lt;Privilege&gt; privileges) {\n\n        Role role = roleRepository.findByName(name);\n        if (role == null) {\n            role = new Role();\n            role.setName(name);\n            role.setPrivileges(privileges);\n            roleRepository.save(role);\n        }\n        return role;\n    }\n}\n\n<\/pre><\/div>\n\n\n<p>InitialDataLoader which implements ApplicationListener for ContextRefreshedEvent, we override a method onApplicationEvent which called when context is refreshed. <\/p>\n\n\n\n<p>In that method we created two privileges for example &#8220;<strong>READ_PRIVILEGE<\/strong>&#8221; and &#8220;<strong>WRITE_PRIVILEGE<\/strong>&#8220;. We have also created two roles for example &#8220;<strong>ROLE_ADMIN<\/strong>&#8221; and &#8220;<strong>ROLE_USER<\/strong>&#8220;.<\/p>\n\n\n\n<p>We need to create now user with email and password because we should have these credentials for login in the system.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.3 JWTAuthenticationFilter.java <\/h4>\n\n\n\n<p>This is a filter class which will be added filter before in spring security config file. All request gonna be filtered before processing any thing request. User may not be logged in therefore we use filter to check first then process.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\n\/**\n * Created by sadiq.odho on 9\/11\/2018.\n *\/\n\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.web.filter.GenericFilterBean;\n\nimport javax.servlet.FilterChain;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\n\npublic class JWTAuthenticationFilter extends GenericFilterBean {\n\n    @Override\n    public void doFilter(ServletRequest request,\n                         ServletResponse response,\n                         FilterChain filterChain)\n            throws IOException, ServletException {\n        Authentication authentication = TokenAuthenticationService\n                .getAuthentication((HttpServletRequest)request);\n\n        SecurityContextHolder.getContext()\n                .setAuthentication(authentication);\n        filterChain.doFilter(request,response);\n    }\n}\n<\/pre><\/div>\n\n\n<p>The JWTAuthenticationFilter extends GenericFilterBean so we overriding doFilter method. In this filter we are setting Http Servlet Request to authentication and setting into security context.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">3.2.4 JWTLoginFilter.java<\/h4>\n\n\n\n<p>In this login filter we will get the user credentials and try to attempt authentication. If it is successful attempt then we will make JWT token and then set into header response.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport org.springframework.security.authentication.AuthenticationManager;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.AuthenticationException;\nimport org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;\nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher;\n\nimport javax.servlet.FilterChain;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.IOException;\n\nimport static java.util.Collections.emptyList;\n\npublic class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {\n\n    public JWTLoginFilter(String url, AuthenticationManager authManager) {\n        super(new AntPathRequestMatcher(url));\n        setAuthenticationManager(authManager);\n    }\n\n    @Override\n    public Authentication attemptAuthentication(\n            HttpServletRequest req, HttpServletResponse res)\n            throws AuthenticationException, IOException, ServletException {\n        AccountCredentials creds = new ObjectMapper()\n                .readValue(req.getInputStream(), AccountCredentials.class);\n\n\n        return getAuthenticationManager().authenticate(\n                new UsernamePasswordAuthenticationToken(\n                        creds.getUsername(),\n                        creds.getPassword(),\n                        emptyList()\n                )\n        );\n    }\n\n    @Override\n    protected void successfulAuthentication(\n            HttpServletRequest req,\n            HttpServletResponse res, FilterChain chain,\n            Authentication auth) throws IOException, ServletException {\n        TokenAuthenticationService\n                .addAuthentication(res, auth.getName());\n    }\n}\n<\/pre><\/div>\n\n\n<p>JWT Login Filter extends Abstract Authentication Processing Filter and have two override methods attempt Authentication and successful authentication. <\/p>\n\n\n\n<p>In attempt authentication method, we extracts credentials and set into account credentials and then we authenticate with Username Password Authentication Token.<\/p>\n\n\n\n<p>In successful authentication method. We are adding JWT token into header using method add Authentication in Token Authentication Service class.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4 class=\"wp-block-heading\"> 3.2.5 TokenAuthenticationService.java<\/h4>\n\n\n\n<p><strong>T<\/strong>So it is simple class for getting JWT token from request header and setting JWT token into response header. In addition each request must have JWT token in header.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.SignatureAlgorithm;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.Authentication;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.Date;\n\nimport static java.util.Collections.emptyList;\n\n\/**\n * Created by sadiq.odho on 9\/11\/2018.\n *\/\npublic class TokenAuthenticationService {\n    static final long EXPIRATIONTIME = 864_000_000; \/\/ 10 days\n    static final String SECRET = \"ThisIsASecret\";\n    static final String TOKEN_PREFIX = \"Bearer\";\n    static final String HEADER_STRING = \"Authorization\";\n\n    static void addAuthentication(HttpServletResponse res, String username) {\n        String JWT = Jwts.builder()\n                .setSubject(username)\n                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))\n                .signWith(SignatureAlgorithm.\n\n\n\n                        HS512, SECRET)\n                .compact();\n        res.addHeader(HEADER_STRING, TOKEN_PREFIX + \" \" + JWT);\n    }\n\n    static Authentication getAuthentication(HttpServletRequest request) {\n        String token = request.getHeader(HEADER_STRING);\n        if (token != null) {\n            \/\/ parse the token.\n            String user = Jwts.parser()\n                    .setSigningKey(SECRET)\n                    .parseClaimsJws(token.replace(TOKEN_PREFIX, \"\"))\n                    .getBody()\n                    .getSubject();\n\n            return user != null ?\n                    new UsernamePasswordAuthenticationToken(user, null, emptyList()) :\n                    null;\n        }\n        return null;\n    }\n}\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4 class=\"wp-block-heading\"> 3.2.6 WebSecurityConfig.java<\/h4>\n\n\n\n<p>Further we configure all security configuration in configure method with http request we are adding some filters and making some URLs restricted without login. For spring security you will find more details on following guide <a href=\"https:\/\/www.baeldung.com\/spring-security-authentication-and-registration\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"Link (opens in a new tab)\">Link<\/a><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.config;\n\nimport com.example.demo.services.UserDetailServiceImpl;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.factory.PasswordEncoderFactories;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;\n\n\/**\n * Created by sadiq.odho on 9\/11\/2018.\n *\/\n@Configuration\n@EnableWebSecurity\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n\n    @Autowired\n    private UserDetailServiceImpl userDetailService;\n\n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http.csrf().disable().authorizeRequests()\n                .antMatchers(\"\/\", \"\/users\/register\").permitAll()\n                .antMatchers(\"\/login\").permitAll()\n\/\/                .antMatchers(\"\/quotes\").permitAll()\n                .anyRequest().authenticated()\n                .and()\n                \/\/ We filter the api\/login requests\n                .addFilterBefore(new JWTLoginFilter(\"\/login\", authenticationManager()),\n                        UsernamePasswordAuthenticationFilter.class)\n                \/\/ And filter other requests to check the presence of JWT in header\n                .addFilterBefore(new JWTAuthenticationFilter(),\n                        UsernamePasswordAuthenticationFilter.class);\n    }\n\n    @Override\n    protected void configure(AuthenticationManagerBuilder auth) throws Exception {\n        \/\/ Create a default account\n        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();\n        auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder);\n        \/*auth.inMemoryAuthentication()\n                .withUser(\"admin\")\n                .password(encoder.encode(\"password\"))\n                .roles(\"ADMIN\");*\/\n\n    }\n}\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3.3 Controllers Package<\/h3>\n\n\n\n<p><strong>UserController.java;<\/strong> In this controller package we have only User Controller with three methods.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>get Users:<\/strong> we will get all users by calling this method.<\/li><li><strong>get Logged In User:<\/strong> By using this method we can retrieve current logged in user.<\/li><li><strong>sing Up:<\/strong> One can register using sing up method.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.controllers;\n\nimport com.example.demo.entities.User;\nimport com.example.demo.repositories.RoleRepository;\nimport com.example.demo.repositories.UserRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.util.StringUtils;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\n\n\/**\n * Created by sadiq.odho on 9\/11\/2018.\n *\/\n@RestController\n@RequestMapping(&quot;\/users&quot;)\npublic class UserController {\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Autowired\n    private PasswordEncoder passwordEncoder;\n\n    @Autowired\n    private RoleRepository roleRepository;\n\n    \/* Maps to all HTTP actions by default (GET,POST,..)*\/\n    @RequestMapping(&quot;\/all&quot;)\n    public @ResponseBody\n    List&lt;User&gt; getUsers() {\n        return userRepository.findAll();\n    }\n\n    @RequestMapping(&quot;\/get-logged-in-user&quot;)\n    public User getLoggedInUser(){\n        String username = SecurityContextHolder.getContext().getAuthentication().getName();\n        if(username != null){\n            return userRepository.findByEmail(username);\n        }\n        return null;\n    }\n\n    @PostMapping(&quot;\/register&quot;)\n    public User singUp(@RequestBody User user) throws Exception{\n        if (userRepository.findByEmail(user.getEmail()) != null) {\n            throw new Exception(&quot;There is an account with that email adress: &quot; + user.getEmail());\n        }\n\n        User newUser = new User();\n        newUser.setName(user.getName());\n        user.setPassword(passwordEncoder.encode(user.getPassword()));\n        user.setEmail(user.getEmail());\n\n        user.setRoles(Arrays.asList(roleRepository.findByName(&quot;ROLE_USER&quot;)));\n        return userRepository.save(user);\n    }\n}\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3.4 Entities Package<\/h3>\n\n\n\n<p>Entities package contains only model classes For example User, Role and  <br>Privilege classes.<\/p>\n\n\n\n<p><strong>Privilege.java;<\/strong> Privilege class can contains privileges of roles for example <strong>READ_PRIVILEGE<\/strong> and <strong>WRITE_PRIVILEGE<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.entities;\n\nimport com.fasterxml.jackson.annotation.JsonManagedReference;\n\nimport javax.persistence.*;\nimport java.util.Collection;\n\n\/**\n * Created by sadiq.odho on 1\/31\/2019.\n *\/\n@Entity\npublic class Privilege implements java.io.Serializable{\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    private String name;\n\n    @ManyToMany(mappedBy = &quot;privileges&quot;)\n\n    private Collection&lt;Role&gt; roles;\n\n    public Long getId() {\n        return id;\n    }\n\n    public void setId(Long id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public Collection&lt;Role&gt; getRoles() {\n        return roles;\n    }\n\n    public void setRoles(Collection&lt;Role&gt; roles) {\n        this.roles = roles;\n    }\n}\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><strong>Role.java;<\/strong> Role class contains roles of the users for example <strong>ROLE_ADMIN<\/strong> and <strong>ROLE_USER<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.entities;\n\nimport com.fasterxml.jackson.annotation.JsonBackReference;\nimport com.fasterxml.jackson.annotation.JsonManagedReference;\n\nimport javax.persistence.*;\nimport java.util.Collection;\n\n\/**\n * Created by sadiq.odho on 1\/31\/2019.\n *\/\n@Entity\npublic class Role implements java.io.Serializable{\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n\n    @Column\n    private String name;\n\n    @ManyToMany(mappedBy = &quot;roles&quot;)\n    private Collection&lt;User&gt; users;\n\n    @ManyToMany\n    @JoinTable(\n            name = &quot;roles_privileges&quot;,\n            joinColumns = @JoinColumn(\n                    name = &quot;role_id&quot;, referencedColumnName = &quot;id&quot;),\n            inverseJoinColumns = @JoinColumn(\n                    name = &quot;privilege_id&quot;, referencedColumnName = &quot;id&quot;))\n\n    private Collection&lt;Privilege&gt; privileges;\n\n    public Long getId() {\n        return id;\n    }\n\n    public void setId(Long id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public Collection&lt;User&gt; getUsers() {\n        return users;\n    }\n\n    public void setUsers(Collection&lt;User&gt; users) {\n        this.users = users;\n    }\n\n    public Collection&lt;Privilege&gt; getPrivileges() {\n        return privileges;\n    }\n\n    public void setPrivileges(Collection&lt;Privilege&gt; privileges) {\n        this.privileges = privileges;\n    }\n}\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><strong>User.java;<\/strong> User class is used for logged in user information for instance username, email, password.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.entities;\n\nimport com.fasterxml.jackson.annotation.JsonBackReference;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonManagedReference;\n\nimport javax.persistence.*;\nimport java.util.Collection;\n\n\/**\n * Created by sadiq.odho on 1\/31\/2019.\n *\/\n@Entity\npublic class User {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Long id;\n    private String name;\n    private String email;\n    private String password;\n    private boolean enabled;\n    private boolean tokenExpired;\n\n    @JsonIgnore\n    @ManyToMany\n    @JoinTable(\n            name = &quot;users_roles&quot;,\n            joinColumns = @JoinColumn(\n                    name = &quot;user_id&quot;, referencedColumnName = &quot;id&quot;),\n            inverseJoinColumns = @JoinColumn(\n                    name = &quot;role_id&quot;, referencedColumnName = &quot;id&quot;))\n    private Collection&lt;Role&gt; roles;\n\n    public Long getId() {\n        return id;\n    }\n\n    public void setId(Long id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public String getEmail() {\n        return email;\n    }\n\n    public void setEmail(String email) {\n        this.email = email;\n    }\n\n    public String getPassword() {\n        return password;\n    }\n\n    public void setPassword(String password) {\n        this.password = password;\n    }\n\n    public boolean isEnabled() {\n        return enabled;\n    }\n\n    public void setEnabled(boolean enabled) {\n        this.enabled = enabled;\n    }\n\n    public boolean isTokenExpired() {\n        return tokenExpired;\n    }\n\n    public void setTokenExpired(boolean tokenExpired) {\n        this.tokenExpired = tokenExpired;\n    }\n\n    public Collection&lt;Role&gt; getRoles() {\n        return roles;\n    }\n\n    public void setRoles(Collection&lt;Role&gt; roles) {\n        this.roles = roles;\n    }\n}\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3.5 Repositories package<\/h3>\n\n\n\n<p>These repositories are used for accessing data objects in the project so in this package you will find repositories for User, Roles and Privileges.<\/p>\n\n\n\n<p><strong>PrivilegeRepository.java;<\/strong> we create privilege repository for accessing data object of privilege entity<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.repositories;\n\nimport com.example.demo.entities.Privilege;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.JpaSpecificationExecutor;\nimport org.springframework.stereotype.Repository;\n\n\/**\n * Created by sadiq.odho on 2\/1\/2019.\n *\/\n@Repository\npublic interface PrivilegeRepository extends JpaRepository&lt;Privilege, Integer&gt;, JpaSpecificationExecutor&lt;Privilege&gt; {\n    public Privilege findByName(String name);\n}\n\n<\/pre><\/div>\n\n\n<p><strong>RoleRepository.java;<\/strong> we create role repository for accessing data object of role entity.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.repositories;\n\nimport com.example.demo.entities.Role;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.JpaSpecificationExecutor;\nimport org.springframework.stereotype.Repository;\n\n\/**\n * Created by sadiq.odho on 2\/1\/2019.\n *\/\n@Repository\npublic interface RoleRepository extends JpaRepository&lt;Role, Integer&gt;, JpaSpecificationExecutor&lt;Role&gt; {\n    public Role findByName(String name);\n}\n\n<\/pre><\/div>\n\n\n<p><strong>UserRepository.java;<\/strong> we create user repository for accessing data object of User entity<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.repositories;\n\nimport com.example.demo.entities.User;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.JpaSpecificationExecutor;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\n\/**\n * Created by sadiq.odho on 1\/31\/2019.\n *\/\n@Repository\npublic interface UserRepository extends JpaRepository&lt;User, Integer&gt;, JpaSpecificationExecutor&lt;User&gt;{\n    @Query(value = &quot;FROM User WHERE email = :email&quot;, nativeQuery = false)\n    public User findByEmail(@Param(&quot;email&quot;) String email);\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3.6 Services package<\/h3>\n\n\n\n<p>This Service package contains all classes for business logic.<\/p>\n\n\n\n<p><strong>UserDetailServiceImpl.java;<\/strong> UserDetailServiceImpl contains all business logic for user entity object.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npackage com.example.demo.services;\n\nimport com.example.demo.entities.Privilege;\nimport com.example.demo.entities.Role;\nimport com.example.demo.entities.User;\nimport com.example.demo.repositories.RoleRepository;\nimport com.example.demo.repositories.UserRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.MessageSource;\nimport org.springframework.security.core.GrantedAuthority;\nimport org.springframework.security.core.authority.SimpleGrantedAuthority;\nimport org.springframework.security.core.userdetails.UserDetails;\nimport org.springframework.security.core.userdetails.UserDetailsService;\nimport org.springframework.security.core.userdetails.UsernameNotFoundException;\nimport org.springframework.stereotype.Component;\nimport org.springframework.stereotype.Service;\n\nimport javax.transaction.Transactional;\nimport java.util.*;\n\n\/**\n * Created by sadiq.odho on 1\/31\/2019.\n *\/\n@Service\n@Transactional\npublic class UserDetailServiceImpl implements UserDetailsService{\n\n    @Autowired\n    private UserRepository userRepository;\n\n    @Autowired\n    private MessageSource messages;\n\n    @Autowired\n    private RoleRepository roleRepository;\n\n    @Override\n    public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException{\n        User user = userRepository.findByEmail(username);\n        if(user == null){\n            return new org.springframework.security.core.userdetails.User(\n                    &quot; &quot;, &quot; &quot;, true, true, true, true,\n                    getAuthorities(Arrays.asList(\n                            roleRepository.findByName(&quot;ROLE_USER&quot;))));\n        }\n\n        return new org.springframework.security.core.userdetails.User(\n                user.getEmail(), user.getPassword(), user.isEnabled(), true, true,\n                true, getAuthorities(user.getRoles()));\n    }\n\n    private Collection&lt;? extends GrantedAuthority&gt; getAuthorities(\n            Collection&lt;Role&gt; roles) {\n\n        return getGrantedAuthorities(getPrivileges(roles));\n    }\n\n    private List&lt;String&gt; getPrivileges(Collection&lt;Role&gt; roles) {\n\n        List&lt;String&gt; privileges = new ArrayList&lt;&gt;();\n        List&lt;Privilege&gt; collection = new ArrayList&lt;&gt;();\n        for (Role role : roles) {\n            collection.addAll(role.getPrivileges());\n        }\n        for (Privilege item : collection) {\n            privileges.add(item.getName());\n        }\n        return privileges;\n    }\n\n    private List&lt;GrantedAuthority&gt; getGrantedAuthorities(List&lt;String&gt; privileges) {\n        List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();\n        for (String privilege : privileges) {\n            authorities.add(new SimpleGrantedAuthority(privilege));\n        }\n        return authorities;\n    }\n}\n\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">4. Test in Postman Client<\/h2>\n\n\n\n<p>Postman Client is a browser extension which helps us in web  <br>testing services however it is very useful application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4.1 Login User<\/h3>\n\n\n\n<p>Let&#8217;s try to login user, basically you need JWT token for accessing any authenticated request. <\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-login-postman-1024x628.png\" alt=\"Login User in Postman\" class=\"wp-image-770\" width=\"580\" height=\"355\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-login-postman-1024x628.png 1024w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-login-postman-300x184.png 300w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-login-postman-768x471.png 768w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-login-postman.png 1044w\" sizes=\"auto, (max-width: 580px) 100vw, 580px\" \/><figcaption>Login User<\/figcaption><\/figure>\n\n\n\n<p>Following details of <strong>Login User<\/strong> postman<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>URL and HTTP method<\/strong>: localhost:8090\/login and Post method<\/li><li><strong>Data Type:<\/strong> JSON (application \/ json)<\/li><li><strong>Response Header:<\/strong> If there is successful login authentication then you will find authorization code in response header which starts with Bearer.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">4.2 Get logged In User<\/h3>\n\n\n\n<p>In following Example we will see that How to avail logged in user in spring security.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"480\" src=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-get-logged-in-user-postman-1024x480.png\" alt=\"\" class=\"wp-image-771\" srcset=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-get-logged-in-user-postman-1024x480.png 1024w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-get-logged-in-user-postman-300x141.png 300w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-get-logged-in-user-postman-768x360.png 768w, https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Security-JWT-token-authentication-in-Spring-boot-get-logged-in-user-postman.png 1050w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Get Logged In User<\/figcaption><\/figure>\n\n\n\n<p> Following details of <strong>Get Logged in User<\/strong> figure <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>URL and HTTP method:<\/strong> localhost:8090\/users\/get-logged-in-user and GET method.<\/li><li><strong>Request Header:<\/strong> In request header you must set Authorization with JWT token so it is already retrieved in above example.<\/li><li><strong>Response Body:<\/strong> After successful authorization you will receive logged in user information in other words you can get authentication after logged in.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">5. Conclusion <\/h2>\n\n\n\n<p>In conclusion we have implemented spring boot project for Spring security JWT token authentication. <\/p>\n\n\n\n<p>Finally we have tested this application in postman client application.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Firstly in this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front&#8230; <\/p>\n","protected":false},"author":1,"featured_media":784,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[154,153,155],"tags":[123,122],"class_list":["post-706","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-java-projects","category-spring","tag-java","tag-spring-mvc"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Spring Security JWT token authentication in Spring boot - SindhiTutorials<\/title>\n<meta name=\"description\" content=\"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Spring Security JWT token authentication in Spring boot - SindhiTutorials\" \/>\n<meta property=\"og:description\" content=\"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client\" \/>\n<meta property=\"og:url\" content=\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/\" \/>\n<meta property=\"og:site_name\" content=\"SindhiTutorials\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/sindhitutorials\/\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/sindhitutorials\/\" \/>\n<meta property=\"article:published_time\" content=\"2019-05-11T10:34:26+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-05-11T10:57:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"sadiqodho\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@SindhiTutorials\" \/>\n<meta name=\"twitter:site\" content=\"@SindhiTutorials\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"sadiqodho\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"19 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/\",\"url\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/\",\"name\":\"Spring Security JWT token authentication in Spring boot - SindhiTutorials\",\"isPartOf\":{\"@id\":\"https:\/\/sindhitutorials.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg\",\"datePublished\":\"2019-05-11T10:34:26+00:00\",\"dateModified\":\"2019-05-11T10:57:15+00:00\",\"author\":{\"@id\":\"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/0643c170d77d3d0db865c1e7f6f56169\"},\"description\":\"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client\",\"breadcrumb\":{\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage\",\"url\":\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg\",\"contentUrl\":\"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg\",\"width\":1200,\"height\":628,\"caption\":\"Spring Framework\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/sindhitutorials.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Spring Security JWT token authentication in Spring boot\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/#website\",\"url\":\"https:\/\/sindhitutorials.com\/blog\/\",\"name\":\"SindhiTutorials\",\"description\":\"A Platform for learning\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/sindhitutorials.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/0643c170d77d3d0db865c1e7f6f56169\",\"name\":\"sadiqodho\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c25afbd4104cdbe5c36d38acbb81619f?s=96&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c25afbd4104cdbe5c36d38acbb81619f?s=96&r=g\",\"caption\":\"sadiqodho\"},\"description\":\"I am passionate about teaching and learning\",\"sameAs\":[\"http:\/\/sindhitutorials.com\/\",\"https:\/\/www.facebook.com\/sindhitutorials\/\"],\"url\":\"https:\/\/sindhitutorials.com\/blog\/author\/sadiqodho\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Spring Security JWT token authentication in Spring boot - SindhiTutorials","description":"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/","og_locale":"en_US","og_type":"article","og_title":"Spring Security JWT token authentication in Spring boot - SindhiTutorials","og_description":"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client","og_url":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/","og_site_name":"SindhiTutorials","article_publisher":"https:\/\/www.facebook.com\/sindhitutorials\/","article_author":"https:\/\/www.facebook.com\/sindhitutorials\/","article_published_time":"2019-05-11T10:34:26+00:00","article_modified_time":"2019-05-11T10:57:15+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg","type":"image\/jpeg"}],"author":"sadiqodho","twitter_card":"summary_large_image","twitter_creator":"@SindhiTutorials","twitter_site":"@SindhiTutorials","twitter_misc":{"Written by":"sadiqodho","Est. reading time":"19 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/","url":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/","name":"Spring Security JWT token authentication in Spring boot - SindhiTutorials","isPartOf":{"@id":"https:\/\/sindhitutorials.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage"},"image":{"@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage"},"thumbnailUrl":"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg","datePublished":"2019-05-11T10:34:26+00:00","dateModified":"2019-05-11T10:57:15+00:00","author":{"@id":"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/0643c170d77d3d0db865c1e7f6f56169"},"description":"In this post we are going to setup Spring Security JWT token authentication in Spring boot. Finally all front end tests will be done using postman client","breadcrumb":{"@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#primaryimage","url":"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg","contentUrl":"https:\/\/sindhitutorials.com\/blog\/wp-content\/uploads\/2019\/05\/Spring-Framework.jpg","width":1200,"height":628,"caption":"Spring Framework"},{"@type":"BreadcrumbList","@id":"https:\/\/sindhitutorials.com\/blog\/spring-security-jwt-token-authentication-in-spring-boot\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/sindhitutorials.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Spring Security JWT token authentication in Spring boot"}]},{"@type":"WebSite","@id":"https:\/\/sindhitutorials.com\/blog\/#website","url":"https:\/\/sindhitutorials.com\/blog\/","name":"SindhiTutorials","description":"A Platform for learning","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/sindhitutorials.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/0643c170d77d3d0db865c1e7f6f56169","name":"sadiqodho","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/sindhitutorials.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c25afbd4104cdbe5c36d38acbb81619f?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c25afbd4104cdbe5c36d38acbb81619f?s=96&r=g","caption":"sadiqodho"},"description":"I am passionate about teaching and learning","sameAs":["http:\/\/sindhitutorials.com\/","https:\/\/www.facebook.com\/sindhitutorials\/"],"url":"https:\/\/sindhitutorials.com\/blog\/author\/sadiqodho\/"}]}},"_links":{"self":[{"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/posts\/706","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/comments?post=706"}],"version-history":[{"count":39,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/posts\/706\/revisions"}],"predecessor-version":[{"id":782,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/posts\/706\/revisions\/782"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/media\/784"}],"wp:attachment":[{"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/media?parent=706"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/categories?post=706"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sindhitutorials.com\/blog\/wp-json\/wp\/v2\/tags?post=706"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}