Giter Club home page Giter Club logo

springboot-jwt-starter's Introduction

[中文版]

                _             _                 _       _          _         _             _
 ___ _ __  _ __(_)_ __   __ _| |__   ___   ___ | |_    (_)_      _| |_   ___| |_ __ _ _ __| |_ ___ _ __
/ __| '_ \| '__| | '_ \ / _` | '_ \ / _ \ / _ \| __|   | \ \ /\ / / __| / __| __/ _` | '__| __/ _ \ '__|
\__ \ |_) | |  | | | | | (_| | |_) | (_) | (_) | |_    | |\ V  V /| |_  \__ \ || (_| | |  | ||  __/ |
|___/ .__/|_|  |_|_| |_|\__, |_.__/ \___/ \___/ \__|  _/ | \_/\_/  \__| |___/\__\__,_|_|   \__\___|_|
    |_|                 |___/                        |__/

npm Build Status License MIT

A Springboot token-based security starter kit featuring AngularJS and Springboot (JSON Web Token)

If you're looking for using Angular 4 for frontend implementation, please checkout angular-spring-starter, a fullstack starter kit featuring Angular 4, Router, Forms, Http, Services, Spring boot, Json Web Token

Springboot JWT Starter

Authentication is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

-- Auth0

Quick start

Make sure you have Maven and Java 1.7 or greater

# clone our repo
# --depth 1 removes all but one .git commit history
git clone --depth 1 https://github.com/bfwg/springboot-jwt-starter.git

# change directory to our repo
cd springboot-jwt-starter

# install the repo with mvn
mvn install

# start the server
mvn spring-boot:run

# the app will be running on port 8080
# there are two built-in user accounts to demonstrate the differing levels of access to the endpoints:
# - User - user:123
# - Admin - admin:123

Run with docker

docker-compose up --build -d

File Structure

springboot-jwt-starter/
 ├──src/                                                        * our source files
 │   ├──main
 │   │   ├──java.com.bfwg
 │   │   │   ├──config
 │   │   │   │   └──WebSecurityConfig.java                      * config file for filter, custom userSerivce etc.
 │   │   │   ├──model
 │   │   │   │   ├──Authority.java
 │   │   │   │   ├──UserTokenState.java                         * JWT model
 │   │   │   │   └──User.java                                   * our main User model
 │   │   │   ├──repository                                      * repositories folder for accessing database
 │   │   │   │   └──UserRepository.java
 │   │   │   ├──rest                                            * rest endpoint folder
 │   │   │   │   ├──AuthenticationController.java               * auth related REST controller, refresh token endpoint etc.
 │   │   │   │   └──UserController.java                         * REST controller to handle User related requests
 │   │   │   ├──security                                        * Security related folder(JWT, filters)
 │   │   │   │   ├──auth
 │   │   │   │   │   ├──JwtAuthenticationRequest.java           * login request object, contains username and password
 │   │   │   │   │   ├──RestAuthenticationEntryPoint.java       * handle auth exceptions, like invalid token etc.
 │   │   │   │   │   ├──TokenAuthenticationFilter.java          * the JWT token filter, configured in WebSecurityConfig
 │   │   │   │   │   └──TokenBasedAuthentication.java           * this is our custom Authentication class and it extends AbstractAuthenticationToken
 │   │   │   │   └──TokenHelper.java                            * token helper class
 │   │   │   ├──service
 │   │   │   │   ├──impl
 │   │   │   │   │   ├──CustomUserDetailsService.java           * custom UserDetailsService implementation, tells formLogin() where to check username/password
 │   │   │   │   │   └──UserServiceImpl.java
 │   │   │   │   └──UserService.java
 │   │   │   └──Application.java                                * Application main class
 │   │   └──recources
 │   │       ├──static                                          * static assets are served here (Angular and html templates)
 │   │       ├──application.yml                                 * application variables are configured here
 │   │       └──import.sql                                      * h2 database query (table creation)
 │   └──test                                                    * Junit test folder
 └──pom.xml                                                     * what maven uses to manage its dependencies and configuration

Table of Contents

Configuration

  • WebSecurityConfig.java: The server-side authentication configurations.
  • application.yml: Application level properties i.e the token expire time, token secret etc. You can find a reference of all application properties here.
  • JWT token TTL: JWT Tokens are configured to expire after 10 minutes, you can get a new token by signing in again.
  • Using a different database: This Starter kit is using an embedded H2 database that is automatically configured by Spring Boot. If you want to connect to another database you have to specify the connection in the application.yml in the resource directory. Here is an example for a MySQL DB:
spring:
  jpa:
    hibernate:
      # possible values: validate | update | create | create-drop
      ddl-auto: create-drop
  datasource:
    url: jdbc:mysql://localhost/myDatabase
    username: myUser
    password: myPassword
    driver-class-name: com.mysql.jdbc.Driver

Hint: For other databases like MySQL sequences don't work for ID generation. So you have to change the GenerationType in the entity beans to 'AUTO' or 'IDENTITY'.

JSON Web Token

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. for more info, checkout https://jwt.io/

Contributing

I'll accept pretty much everything so feel free to open a Pull-Request

This project is inspried by


License

MIT

springboot-jwt-starter's People

Contributors

bfwg avatar mcicolella avatar mirkoperillo avatar slimming-fat 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  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

springboot-jwt-starter's Issues

failureHandler doesn't work

I overwrite the SimpleUrlAuthenticationFailureHandler onAuthenticationFailure method,but it doesn't work

@Component
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "认证失败啦");
        // super.onAuthenticationFailure(request, response, exception);
    }
}
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers("/test").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new LoginFilter("/login", authenticationManager()),
                        UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new AuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .failureHandler(authenticationFailureHandler);
    }

update to angular4

Hi,
Could you please update the starter to angular4? which is different largely to angular 1.x, Thanks.

access login end point from angular with CORS activated

Hi,

When I launch this http request with postman, the api rest works perfect.

http://localhost:8080/auth/login
POST
json application
{"username":"user","password":"123"}

But when I try the same action from angular application returns 404 error.

I have study to have the api rest in http://localhost:8080 and the frontend in http://localhost:4200 and this makes a problem with CORS (cross origin) when the call is from a browser.

You have solved this in angular starter jwt kit with uses a proxy, but this is a solution for dev mode, but not for production mode.

The api rest (spring boot source code) should have CORS enabled.

I have make this in AuthenticationController.java:

  @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/login", method = RequestMethod.POST)

And in angular.component.ts


import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  results = '';
  constructor(private http: HttpClient){
  }
  ngOnInit(): void {

    let body       = {"username":"user","password":"123"};
    //let options    = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };

    this.http.post('http:/localhost:8080/auth/login', body)
      .subscribe(data => {
      console.log(data);
      }
    );
  }
}

But not works, can you help me?

Thanks so much!!

Xavier.

Endpoint to refresh the JWT token

Summary

As a user, I want to be able to extend my SSO.

Requirement

Implement an endpoint that extend the TTL of the JWT when the JWT is valid.

Multipart Upload Error

unable to upload file. can you add multipart uploading using rest apis.
using multipart/form-data from postman i got error like
Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

what to do for AnonAuthentication class?

There is a class "TokenBasedAuthentication" extends AbstractAuthenticationToken, "AnonAuthentication" also extends AbstractAuthenticationToken. what difference of the two? why need 2 class extends AbstractAuthenticationToken? Is it for Anonymous?

Why even though I configured SecurityConfig and allowed access to the /text path, does it not work when I test it?

I am new to Security, and this issue is confusing me.

TestController

@RestController
public class Test {
    @GetMapping("/test")
    public ResponseEntity<String > test(){
        System.out.println("Response body: " + "hello");
        return ResponseEntity.ok(" hello ");
    }
}

My console is not printing any statements. What should I do next to solve this

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    public static final String[] EXCLUDE_PATH = {
            "/webjars/**",
            "/favicon.ico",
            "/captcha",
            "/user/login",
            "/user/logout",
            "/test"
    };
    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    @Autowired
    private UserDetailsService customUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }


    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.cors().and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).and()

                .authorizeRequests()
                .antMatchers(EXCLUDE_PATH).permitAll() 
                .anyRequest().authenticated()

             
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        ;

        return http.build();
    }


    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return webSecurity -> {
            webSecurity.ignoring().antMatchers(EXCLUDE_PATH);
        };
    }
}

image

null refresh token

localhost:8080/auth/refresh

got the bellow response:

{
"access_token": null,
"expires_in": null
}

login page cannot display after updated to angular 1.6.4

when click login, no any response, also no any message in chrome console. no any request was sent to the backend. The following is my pom.xml.


4.0.0

<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-security-jwt</name>
<description>Demo project for Spring Boot</description>

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.2.RELEASE</version>
	<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	<dependency>
		<groupId>io.jsonwebtoken</groupId>
		<artifactId>jjwt</artifactId>
		<version>0.7.0</version>
	</dependency>

	<dependency>
		<groupId>joda-time</groupId>
		<artifactId>joda-time</artifactId>
	</dependency>
	<dependency>
		<groupId>com.h2database</groupId>
		<artifactId>h2</artifactId>
		<scope>runtime</scope>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
	</dependency>

	<dependency>
		<groupId>org.webjars.bower</groupId>
		<artifactId>angular</artifactId>
		<version>1.6.4</version>
	</dependency>
	<dependency>
		<groupId>org.webjars.bower</groupId>
		<artifactId>angular-cookies</artifactId>
		<version>1.6.4</version>
	</dependency>
	<dependency>
		<groupId>org.webjars.bower</groupId>
		<artifactId>angular-route</artifactId>
		<version>1.6.4</version>
	</dependency>
	<dependency>
		<groupId>org.webjars</groupId>
		<artifactId>bootstrap</artifactId>
		<version>3.3.7</version>
	</dependency>

	<dependency>
		<groupId>org.webjars.bower</groupId>
		<artifactId>jquery</artifactId>
		<version>1.11.1</version>
	</dependency>

	<dependency>
		<groupId>org.webjars.bower</groupId>
		<artifactId>material-design-lite</artifactId>
		<version>1.3.0</version>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>io.rest-assured</groupId>
		<artifactId>spring-mock-mvc</artifactId>
		<version>3.0.0</version>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

Authorization header is not checked after user login

I use postman to test backend part right now. If I didn't authenticate, it return 403, which is correct. But once I submit the post request with login username and password, return back the token, then I call /whoami, it will still return response to me without verify the header contains the jwt token or not.

In my understanding, for every request that need privilege, like trying to get the response from /whoami, it need to authenticate first, get the jwt token, and then verify the token in the header?

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.