Spring Boot REST API authentication best practices using JWT

Overview

banner.png

Spring Boot REST API authentication best practices using JWT

Token based API authentication with Spring Security and JWT (JSON web Token)

Overview

This repository is made to share source code of my blog post Spring Boot + JWT where I have explained how to do token based authentication for your Spring boot REST API using JSON web tokens(JWT).

Output

  • Handling unauthorized access to protected routes with error 401:

image.png

  • Get token in response of register request

image.png

  • Invalid credentials response when wrong username password is supplied:

image.png

  • Show content from protected route when Auth token is provided in header.

image.png

You might also like...

Spring Boot & MongoDB Login and Registration example with JWT, Spring Security, Spring Data MongoDB

Spring Boot & MongoDB Login and Registration example with JWT, Spring Security, Spring Data MongoDB

Spring Boot Login and Registration example with MongoDB Build a Spring Boot Auth with HttpOnly Cookie, JWT, Spring Security and Spring Data MongoDB. Y

Dec 30, 2022

Build your own Minecraft authentication system with Mojang authentication server support.

Build your own Minecraft authentication system with Mojang authentication server support. A fork of yushijinhun/authlib-injector.

Dec 17, 2022

Vaadin Flow example with JWT authentication

Example how to enable JWT based authentication with Vaadin Flow and Spring Security

Sep 12, 2022

The Quotation Management application is a API REST created using Spring Boot framework.

The Quotation Management application is a API REST  created using Spring Boot framework.

✅ Quotation Management API - Done ✅ About • Features • Setup • Technologies • Author • License 💻 About The Quotation Management application is a API

Apr 29, 2022

See how simple it is to build a REST API with a database using Java and Spring Boot

See how simple it is to build a REST API with a database using Java and Spring Boot

Seu primeiro projeto Java Web no Spring Boot 2022 Veja como é simples construir uma API REST com banco de dados usando Java e Spring Boot Realização D

Dec 26, 2022

Spring-boot project using open-api, docker, maven, REST

library-service spring-boot project using open-api, docker, maven, REST I used docker to run the project, as well as open-api to generate basic GET an

Nov 27, 2022

Spring JPA Many To Many example with Hibernate and Spring Boot CRUD Rest API - ManyToMany annotation

Spring JPA Many To Many example with Hibernate and Spring Boot CRUD Rest API - ManyToMany annotation

Dec 28, 2022

Rate limiting private REST APIs using Java Spring-boot, spring-security and bucket4j

Rate limiting REST APIs using Spring-security filter and Bucket4J Deployed Application (Swagger-ui on heroku) Inspired from: Baeldung Article Applicat

Jul 18, 2022

Spring Boot Security Login example with JWT and H2 example

 Spring Boot Security Login example with JWT and H2 example

Spring Boot Security Login example with JWT and H2 example Appropriate Flow for User Login and Registration with JWT and HttpOnly Cookie Spring Boot R

Dec 21, 2022
Comments
  • null pointer during user registration

    null pointer during user registration

    Hi, in your code there is an error: java.lang.NullPointerException: Cannot invoke "com.example.api.model.User.getUserName()" because "user" is null at com.example.api.service.JwtUserDetailsService.loadUserByUsername(JwtUserDetailsService.java:29) ~[classes/:na] at com.example.api.controller.AuthenticationController.saveUser(AuthenticationController.java:94) ~[classes/:na]

    curl --location --request POST 'http://localhost:8080/auth/register'
    --form 'first_name="bob"'
    --form 'last_name="my_lastname"'
    --form 'user_name="jjj199"'
    --form 'email="[email protected]"'
    --form 'password="thepassword"'

    the controller

    @PostMapping("/register")
    public ResponseEntity<?> saveUser(@RequestParam("first_name") String firstName,
                                      @RequestParam("last_name") String lastName,
                                      @RequestParam("user_name") String userName, @RequestParam("email") String email
            , @RequestParam("password") String password) {
        Map<String, Object> responseMap = new HashMap<>();
        User user = new User();
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setEmail(email);
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user.setRole("USER");
        user.setUserName(userName);
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        String token = jwtTokenUtil.generateToken(userDetails);
        userRepository.save(user);
        responseMap.put("error", false);
        responseMap.put("username", userName);
        responseMap.put("message", "Account created successfully");
        responseMap.put("token", token);
        return ResponseEntity.ok(responseMap);
    }
    

    The function calls userDetailsService.loadUserByUsername(userName);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.example.api.model.User user = userRepository.findUserByUsername(username);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority("USER_ROLE"));
        return new User(user.getUserName(), user.getPassword(), authorityList);
    }
    

    But "com.example.api.model.User user" is null because the user does not exist... user.getPassword() NULLPOINTER

    good first issue 
    opened by codelithic 2
Owner
Prafful Lachhwani
23 | Full Stack | Android | Blockchain Developer | Winner of Smart India Hackathon 2018
Prafful Lachhwani
Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

control_financial Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

Vinicius Cassaro 1 May 27, 2022
Spring Boot JWT Authentication example with Spring Security & Spring Data JPA

Spring Boot JWT Authentication example with Spring Security & Spring Data JPA

null 1 Jan 26, 2022
Spring Boot Refresh Token using JWT example - Expire and Renew JWT Token

Spring Boot Refresh Token with JWT example Build JWT Refresh Token in the Java Spring Boot Application. You can know how to expire the JWT, then renew

null 152 Dec 28, 2022
Event promoted by DevSuperior to improve the best practices of Spring with Java and has React JS as an additional.

Semana-Spring-React (sds3.0) Introduction SDS3 is an event promoted by DevSuperior which aims to help students and programming professionals to enter

Gilson Vieira de Souza 5 Oct 25, 2021
Squadio-App is a Users-Accounts financial system. exposes Rest APIs with JWT authentication/Authorization process .

squadio-app Description Squadio-App is a Users-Accounts financial system. exposes Rest APIs with JWT authentication/Authorization process . How to Run

Bashar Othman 1 Jan 29, 2022
Implementing JWT authentication with spring boot.

Jwt-SpringBoot Implementing JWT authentication with spring boot. Normally you would create an endpoint to create the credentials(token), then this tok

@#aeyarm 2 May 7, 2022
ReactJS, Spring Boot JWT Authentication Example

springboot-reactjs-jwt-authentication ReactJS - SpringBoot - JWT - Flow Local setup Step 1: Download or clone the source code from GitHub to a local m

Sibin Rasiya 16 Dec 2, 2022
该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的线上博客项目/企业大型商城系统/前后端分离实践项目等,摆脱各种 hello world 入门案例的束缚,真正的掌握 Spring Boot 开发。

Spring Boot Projects 该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的前

十三 4.5k Dec 30, 2022
Spring Boot JdbcTemplate example with SQL Server: CRUD Rest API using Spring Data JDBC, Spring Web MVC

Spring Boot JdbcTemplate example with SQL Server: Build CRUD Rest API Build a Spring Boot CRUD Rest API example that uses Spring Data Jdbc to make CRU

null 7 Dec 20, 2022
循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

mrbird 24.8k Jan 6, 2023