Giter Site home page Giter Site logo

bfwg / springboot-jwt-starter Goto Github PK

View Code? Open in Web Editor NEW
741.0 45.0 277.0 248 KB

A Spring Boot JWT starter kit for stateless and token-based authentication apps.

Home Page: https://jwt.fanjin.io

License: MIT License

Java 83.71% HTML 5.48% JavaScript 10.00% Dockerfile 0.81%
spring-boot jwt angularjs java spring spring-security jwt-authentication

springboot-jwt-starter's People

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

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?

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

null refresh token

localhost:8080/auth/refresh

got the bellow response:

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

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.

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);
    }

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.

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>

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

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?

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.