Spring Boot JWT 声明内容加载

如何解决Spring Boot JWT 声明内容加载

总结:我无法让 JWT 使用基于角色的访问。 JWT 本身运行得很好。我查看了几个现有的堆栈溢出响应,但还没有找到我需要的信息。

我正在使用邮递员来验证哪个返回我的 JWT。然后我将该令牌复制到我的 get localhost:8080/hello 标头中。该请求不会触发 security.config JWT 请求过滤器。似乎没有那么远。

索赔问题:(参考:JwtTokenUtil)

  1. 当我获得具有授予权限的用户详细信息时,它只返回单个字符串。在创建 JWT 声明对象时,它似乎是一个键值对。什么进入键值对?现在我正在添加用户名和权限。

  2. 由于我的安全配置文件始终使用角色而不是权限,并且我的数据库存储角色而不是权限,我是否将角色加载到声明对象中?还是 Spring Security 专门寻找权威?换句话说,没有附加“ROLE_”的角色。

安全第一步: 最初,spring security 使用基于角色的访问。我创建了标准的用户和权限表。对于权限,我使用 ROLE_xxx 而不是特权。在安全配置文件中,我使用蚂蚁匹配来提供基于角色的访问。

安全第二步: 我将应用程序转换为使用 JWT。我非常成功地关注了这篇文章。 https://www.javainuse.com/spring/boot-jwt 没有任何基于角色的访问端点。

安全第三步: 使用邮递员,我能够进行身份验证但无法访问 /hello 端点。如果我将 /hello 端点添加到 permit all 列表,并将令牌添加到我的标头请求中,那么我会得到一个有效的响应。如果我尝试将 hasAnyRole 用于 /hello,并在标头请求中使用令牌,则它不起作用。

在身份验证后尝试访问端点时,出现以下错误。没有异常或日志转储。

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

数据库配置:

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 配置:

    <?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 安全配置:

    @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 请求过滤器:

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

端点:

@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.";
    }
}   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res