0

Summary: I am unable to get JWT to work with role based access. JWT by itself runs just fine. I have looked at several existing stack overflow responses but have yet to find the information I need.

I am using postman to authenticate which returns my JWT. I then copy that token into my get localhost:8080/hello header. The request is not triggering the security.config JWT request filter. It does not seem to get that far.

Claims Questions: (Ref: JwtTokenUtil)

  1. When I get the user details with the granted authorities, it returns just the single string. When creating the JWT claims object, it seems to be a key value pair. What goes into the key value pair? Right now I am adding the username and authority.

  2. Since my security config file uses roles throughout and not authorities, and my database stores roles, not authorities, do I load the roles into the claims object? Or is spring security looking specifically for authorities? In other words, the role without the appended “ROLE_”.

Security First Step: Initially, spring security was using role based access. I created the standard user and authorities tables. For the authorities, I used ROLE_xxx instead of privileges. Within the security configuration file, I used ant matching to provide role based access.

Security Second Step: I converted the application to use JWT. I followed this article with great success. https://www.javainuse.com/spring/boot-jwt Without any role based access endpoints.

Security Third Step: Using postman, I am able to authenticate but not access the /hello endpoint. If I add the /hello endpoint to the permit all list, and add the token into my header request, then I get a valid response. If I try to use the hasAnyRole for /hello, with the token in the header request, it does not work.

When attempting to access the endpoint after authentication, I get the following error. There is no exception or log dump.

Error Returned in Postman:

{
    "timestamp": "2021-06-18T14:59:15.995+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/hello"
}

JwtTokenUtil

    public String generateToken(UserDetails userDetails) 
    {
        if(userDetails == null) {
            logger.error("userDetails was null...");
            return "";
        }

        //Add granted authorities into claims
        Map<String, Object> claims = new HashMap<String, Object>();
        for(GrantedAuthority indexGrantedAuthority : userDetails.getAuthorities()) {
          logger.info("Added granted authority (" + indexGrantedAuthority.getAuthority() +") for user (" +
                  userDetails.getUsername() + ") to JWT claims...");
          claims.put(userDetails.getUsername(), indexGrantedAuthority); 
        }

        return doGenerateToken(claims, userDetails.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) 
    {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
                .signWith(key)
                .compact();
    }

Database Configuration:

DROP TABLE IF EXISTS `authorities`;
CREATE TABLE `authorities` (
  `username` VARCHAR(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `authority` VARCHAR(50) COLLATE utf8mb4_bin NOT NULL,
  UNIQUE KEY `authorities_idx_1` (`username`,`authority`),
  CONSTRAINT `authorities_ibfk_1` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Spring Security Authority aka Role Table';


DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `username` VARCHAR(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' UNIQUE,
  `password` VARCHAR(70) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
  `enabled` TINYINT(1) NOT NULL DEFAULT 0,
  `customer_id` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'Related ID to customer',
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Spring Security Users Table';

POM Configuration:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.myapp</groupId>
    <artifactId>myapp</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
    <name>myapp</name>

    <properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <jjwt.version>0.11.2</jjwt.version>
        <graphql.spring.boot.starter.version>11.0.0</graphql.spring.boot.starter.version>
        <graphql.java.tools.version>11.0.1</graphql.java.tools.version>
    </properties>

    <dependencies>
        <!-- Web Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Tomcat and JSP Requirements -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- https://stackoverflow.com/questions/20602010/jsp-file-not-rendering-in-spring-boot-web-application -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- Security Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>
        <!-- JWT -->
        <!-- https://stackoverflow.com/questions/63346655/jjwt-dependency-confusion -->
        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>${jjwt.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>${jjwt.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-jackson -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>${jjwt.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!-- Database Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- GraphQL Services -->
        <!-- https://mvnrepository.com/artifact/com.graphql-java-kickstart/graphql-spring-boot-starter -->
        <dependency>     
            <groupId>com.graphql-java-kickstart</groupId>
            <artifactId>graphql-spring-boot-starter</artifactId>
            <version>${graphql.spring.boot.starter.version}</version>
        </dependency> 
        <!-- https://mvnrepository.com/artifact/com.graphql-java-kickstart/graphql-java-tools -->
        <dependency>     
           <groupId>com.graphql-java-kickstart</groupId>
            <artifactId>graphql-java-tools</artifactId>     
            <version>${graphql.java.tools.version}</version> 
        </dependency>
        <!-- GRAPHIQL not graphql -->
        <!-- https://mvnrepository.com/artifact/com.graphql-java-kickstart/graphiql-spring-boot-starter -->
        <dependency>
            <groupId>com.graphql-java-kickstart</groupId>
            <artifactId>graphiql-spring-boot-starter</artifactId>
            <version>${graphql.spring.boot.starter.version}</version>
        </dependency>
        <!-- Email Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!-- Monitoring Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Development Runtime Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- Test Services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

Spring Security Configuration:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
    {
logger.info("*** Checking the jwt request filter...");
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
logger.info("*** Got past the jwt request filter...");  

        // Disable Spring CSRF checks so connections to the GraphQL API are not prevented
        httpSecurity.csrf().disable();

        httpSecurity.authorizeRequests()
            .antMatchers("/hello").hasAnyRole(RoleCon.getRole(RoleCon.USER))
            .antMatchers("/accessDenied", "/authenticate", "/registration/*", "/types", "/graphql", "/graphiql", "/actuator/*").permitAll()
            // all other requests need to be authenticated
            .anyRequest()
                .authenticated()
                .and()
                // make sure we use stateless session; session won't be used to store user's state.
                .exceptionHandling()
                    .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                    .and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

JWT Request Filter:

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException 
    {
        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            logger.debug("JWT Token is being stripped of the Bearer string.");
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                logger.error("Unable to get JWT Token...");
            } catch (ExpiredJwtException e) {
                logger.error("JWT Token has expired...");
            }
        } else {
            logger.debug("JWT Token does not begin with Bearer string.");
        }

        // Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);
            
logger.info("***Checking user details for authorities.");
for(GrantedAuthority indexGrantedAuthority : userDetails.getAuthorities()) {
    logger.info("***Has granted authority (" + indexGrantedAuthority.getAuthority() 
        +") for user (" + userDetails.getUsername() + ") to the JWT filter...");
}

            // if token is valid configure Spring Security to manually set authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = 
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify that the current user is authenticated. 
                // So it passes the Spring Security Configurations successfully.
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            } else {
logger.info("**** Was not a valid token");
            }
        }
        chain.doFilter(request, response);
    }

Endpoint:

@RestController
public class MiscController 
{
    //DATA MEMBERS///////////////////////////////////////
    final static Logger logger = LoggerFactory.getLogger(MiscController.class);

    //PUBLIC METHODS//////////////////////////////////////////////
    /**
     * Base message.
     *
     * @return the string
     */
    @GetMapping("/")
    public String baseMessage() {
        return "The local time is " + LocalDateTime.now();
    }

    /**
     * Hello REST.
     *
     * @return the string
     */
    @GetMapping("/hello")
    public String helloREST() 
    {
        logger.info("*** HIT THE HELLO REST>>>");
        return "hello REST this is a simple endpoint check.";
    }
}   

Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
Bill Snee
  • 119
  • 1
  • 11
  • i would suggest you use the built in jwtfilter instead of writing a custom one. https://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2resourceserver-jwt-architecture and then you implement a granted authorities mapper, to map claims to roles https://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2login-advanced-map-authorities-grantedauthoritiesmapper – Toerktumlare Jun 18 '21 at 18:51
  • the article you linked is using spring boot `2.1.1.RELEASE` which was released 2018 so it is old and outdated. Also i would avoid using JWTs as session replacement as jwts are suciptable for XSS attacks if implemented incorrectly. https://developer.okta.com/blog/2017/08/17/why-jwts-suck-as-session-tokens – Toerktumlare Jun 18 '21 at 18:57

0 Answers0