Skip to content

Mercateo/spring-security-jwt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status Coverage Status Codacy Badge MavenCentral

com.mercateo.spring.spring-security-jwt

Example usage

How to add JWT support to your project.

Simple Example

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaHR0cHM6Ly90ZXN0Lm9yZy9mb28iOiJiYXIiLCJpYXQiOjE1MTYyMzkwMjJ9.Ujx0Lo-2PjRMXd3xBh1kyf7XEOmGK2LttJJPDL1A4J4

contains payload

{
  "sub": "1234567890",
  "https://test.org/foo": "bar",
  "iat": 1516239022
}

see e.g. https://jwt.io/

Import the config and add a configuration bean

@Configuration
@Import(JWTSecurityConfiguration.class)
public class MyConfiguration {

    ...
    
    @Bean
    public JWTSecurityConfig securityConfig() {
        return JWTSecurityConfig.builder() //
                .addAnonymousPaths("/admin/app_health") //
                .addAnonymousMethods(HttpMethod.OPTIONS) //
                .addRequiredClaims("https://test.org/foo") //
                .addTokenAudiences("https://test.org/api") //
                .withTokenLeeway(300) //
                .build();
    }

    ...
}

Access the principal object to get claims from the token:

        final JWTPrincipal principal = JWTPrincipal.fromContext();

        log.info("principal foo {} with scopes '{}'",
              principal.getClaim("https://test.org/foo"),
              principal.getAuthorities());

Example with token verification

@Configuration
@Import(JWTSecurityConfiguration.class)
public class MyConfiguration {

    ...
    
    @Bean
    public JWTSecurityConfig securityConfig() {
        return JWTSecurityConfig
            .builder()
            .addAnonymousPaths("/admin/app_health")
            .addAnonymousMethods(HttpMethod.OPTIONS)
            .jwtKeyset(new Auth0JWTKeyset(auth0Domain))
            .addRequiredClaims("https://test.org/foo")
            .addRequiredClaims("https://test.org/bar")
            .addTokenAudiences("https://test.org/api")
            .withTokenLeeway(300)
            .build();
    }

    ...
}

Roles / scopes integration

The content of the scope claim is parsed into the list of granted authorities.

Usage

Add the dependency to your maven

    <dependency>
      <groupId>com.mercateo.spring</groupId>
      <artifactId>spring-security-jwt</artifactId>
      <version>2.1.0</version>
    </dependency>

Integrates in Spring Security.

Changelog:

2.1.1:

  • removed public reference about vavr

2.1.0:

  • refactored packaging
  • token handling improvements

2.0.1:

  • breaking change to the previous versions 1.x.y
  • updated dependencies
  • updated parent pom oss-parent-pom to version 1.0.9.
  • the public dependency on io.vavr is removed

What's next?

  • remove the dependency to io.vavr
  • add module-info for better compatibility with java 9 and later