Coder Social home page Coder Social logo

bezkoder / spring-boot-security-login Goto Github PK

View Code? Open in Web Editor NEW
116.0 5.0 54.0 145 KB

Spring Boot + Spring Security: Login and Registration example with JWT, H2 Database and HttpOnly Cookie

Java 100.00%
spring-boot spring-security jwt login registration jwt-authentication jwt-token jwt-auth authentication authorization

spring-boot-security-login's Introduction

Spring Boot Security Login example with JWT and H2 example

  • Appropriate Flow for User Login and Registration with JWT and HttpOnly Cookie
  • Spring Boot Rest Api Architecture with Spring Security
  • How to configure Spring Security to work with JWT
  • How to define Data Models and association for Authentication and Authorization
  • Way to use Spring Data JPA to interact with H2 Database

User Registration, Login and Authorization process.

spring-boot-security-login-jwt-flow

Spring Boot Server Architecture with Spring Security

You can have an overview of our Spring Boot Server with the diagram below:

spring-boot-security-login-jwt-architecture

For more detail, please visit:

Spring Boot Security Login example with JWT and H2 example

For MySQL/PostgreSQL

For MongoDB

Working with Front-end:

Angular 12 / Angular 13 / Angular 14 / Angular 15 / Angular 16 / Angular 17

React / React Redux

Dependency

– If you want to use PostgreSQL:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <scope>runtime</scope>
</dependency>

– or MySQL:

<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <scope>runtime</scope>
</dependency>

Configure Spring Datasource, JPA, App properties

Open src/main/resources/application.properties

  • For PostgreSQL:
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=postgres
spring.datasource.password=123

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update

# App Properties
bezkoder.app.jwtSecret= ======================BezKoder=Spring===========================
bezkoder.app.jwtExpirationMs= 86400000
  • For MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update

# App Properties
bezkoder.app.jwtSecret= ======================BezKoder=Spring===========================
bezkoder.app.jwtExpirationMs= 86400000

Run Spring Boot application

mvn spring-boot:run

Run following SQL insert statements

INSERT INTO roles(name) VALUES('ROLE_USER');
INSERT INTO roles(name) VALUES('ROLE_MODERATOR');
INSERT INTO roles(name) VALUES('ROLE_ADMIN');

Refresh Token

Spring Boot JWT Refresh Token example

More Practice:

Spring Boot File upload example with Multipart File

Exception handling: @RestControllerAdvice example in Spring Boot

Spring Boot Repository Unit Test with @DataJpaTest

Spring Boot Rest Controller Unit Test with @WebMvcTest

Spring Boot Pagination & Sorting example

Validation: Spring Boot Validate Request Body

Documentation: Spring Boot and Swagger 3 example

Caching: Spring Boot Redis Cache example

Associations:

JPA/Hibernate One To Many example in Spring Boot

JPA/Hibernate Many To Many example in Spring Boot

JPA/Hibernate One To One example in Spring Boot

Deployment:

Deploy Spring Boot App on AWS – Elastic Beanstalk

Docker Compose Spring Boot and MySQL example

Fullstack Authentication

Spring Boot + Vue.js JWT Authentication

Spring Boot + Angular 8 JWT Authentication

Spring Boot + Angular 10 JWT Authentication

Spring Boot + Angular 11 JWT Authentication

Spring Boot + Angular 12 JWT Authentication

Spring Boot + Angular 13 JWT Authentication

Spring Boot + Angular 14 JWT Authentication

Spring Boot + Angular 15 JWT Authentication

Spring Boot + Angular 16 JWT Authentication

Spring Boot + Angular 17 JWT Authentication

Spring Boot + React JWT Authentication

Fullstack CRUD App

Vue.js + Spring Boot + H2 Embedded database example

Vue.js + Spring Boot + MySQL example

Vue.js + Spring Boot + PostgreSQL example

Angular 8 + Spring Boot + Embedded database example

Angular 8 + Spring Boot + MySQL example

Angular 8 + Spring Boot + PostgreSQL example

Angular 10 + Spring Boot + MySQL example

Angular 10 + Spring Boot + PostgreSQL example

Angular 11 + Spring Boot + MySQL example

Angular 11 + Spring Boot + PostgreSQL example

Angular 12 + Spring Boot + Embedded database example

Angular 12 + Spring Boot + MySQL example

Angular 12 + Spring Boot + PostgreSQL example

Angular 13 + Spring Boot + H2 Embedded Database example

Angular 13 + Spring Boot + MySQL example

Angular 13 + Spring Boot + PostgreSQL example

Angular 14 + Spring Boot + H2 Embedded Database example

Angular 14 + Spring Boot + MySQL example

Angular 14 + Spring Boot + PostgreSQL example

Angular 15 + Spring Boot + H2 Embedded Database example

Angular 15 + Spring Boot + MySQL example

Angular 15 + Spring Boot + PostgreSQL example

Angular 16 + Spring Boot + H2 Embedded Database example

Angular 16 + Spring Boot + MySQL example

Angular 16 + Spring Boot + PostgreSQL example

Angular 17 + Spring Boot + H2 Embedded Database example

Angular 17 + Spring Boot + MySQL example

Angular 17 + Spring Boot + PostgreSQL example

React + Spring Boot + MySQL example

React + Spring Boot + PostgreSQL example

React + Spring Boot + MongoDB example

Run both Back-end & Front-end in one place:

Integrate Angular with Spring Boot Rest API

Integrate React.js with Spring Boot Rest API

Integrate Vue.js with Spring Boot Rest API

spring-boot-security-login's People

Contributors

tienbku avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

spring-boot-security-login's Issues

Cannot send push request

Hi, I found out that I cannot send post requests using AuthController, but get requests are working using TestController. Can you help find an issue?

After sending any GET/POST request at AuthController, I'm getting: Unauthorized error: Full authentication is required to access this resource

Even requesting function returning simple string.

Signup POST role must be an Array

This is not a bug, just a slight oversight in the directions and perhaps some naivety on my part. The image merely implies posting the required parameters appearing to be {username, email, role, password} I was seeing the error

JSON parse error: Cannot construct instance of `java.util.HashSet` . . .  to deserialize from String value ('ROLE_ADMIN')<EOL>

Then it occurred to me surely a user can have all the roles so it must require an array

// My mistake "role" : "ROLE_ADMIN"
{
    "username": "greg",
    "email": "[email protected]",
    "role": ["ROLE_ADMIN"],
    "password": "4bangads"
}

I am only posting in case anyone else sees the issue. Thank your for this great example and your time on this!

Dynamically Role

Your tutorial was so easy and amazing. i don't need a lot of time to implement your tutorial.
But how about make dynamically role with create Role CRUD and set user to that role with some privillage?

principal details are provided from cookies instead of automatically collecting them

cookies are maintaining token information and username and password informatino,
So, principal user details are obtained from the cookie information
a clever user can easily manipulate the cookie information and claim as another user
also can edit authorities information in the cookie and can claim additional accesses.

Also, multiple users can have same role.
role specific accesses keep restrictions on the columns in a table
row wise filterin is supposed to be handled by Prncipal details.
Although the word Principal is used many places but functionally it is just retrieving this information from cookies instead of token.

Also, authentication server is not implemented as an independent spring boot application and keeping the controller web accesses in a separate application

generic authorities like read_all add_all etc are not handled altogether compromising on usability of the application.

it slows down drastically when number of users are more than 100 and
number of controller classes and number of authorities more than 500.
Usually for micro controller architecture this count is high and no efficiency considerations are addressed

It seems, requires lots of changes and require a new solution altogether to address all above issues

Access Content doesn't work

I did the tutorial on this link to Spring Boot 3. Everything is fine with register and auth. I got the cookie but when I tried access /api/test/mod I got 401 ever. I tried with postman, exactly like the tutorial and with python lib requests.

Register
image

Login
image

Get Mod content
cookie
image
request
image

Unauthorized when entering h2-console

Hey, this is my filterChain:

   @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeHttpRequests().requestMatchers("/api/auth/**").permitAll()
                .requestMatchers("/api/test/**").permitAll()
                .requestMatchers(h2ConsolePath + "/**").permitAll()
                .anyRequest().authenticated();

        // fix H2 database console: Refused to display ' in a frame because it set 'X-Frame-Options' to 'deny'
        http.headers().frameOptions().sameOrigin();

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

And I get this error, even though I permitted the h2-console:
{"path":"/h2-ui","error":"Unauthorized","message":"Full authentication is required to access this resource","status":401}

I also get 401 response when I want to signup via postman.

Can someone help me please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.