如何解决Spring Boot JWT 声明内容加载
总结:我无法让 JWT 使用基于角色的访问。 JWT 本身运行得很好。我查看了几个现有的堆栈溢出响应,但还没有找到我需要的信息。
我正在使用邮递员来验证哪个返回我的 JWT。然后我将该令牌复制到我的 get localhost:8080/hello 标头中。该请求不会触发 security.config JWT 请求过滤器。似乎没有那么远。
索赔问题:(参考:JwtTokenUtil)
-
当我获得具有授予权限的用户详细信息时,它只返回单个字符串。在创建 JWT 声明对象时,它似乎是一个键值对。什么进入键值对?现在我正在添加用户名和权限。
-
由于我的安全配置文件始终使用角色而不是权限,并且我的数据库存储角色而不是权限,我是否将角色加载到声明对象中?还是 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 举报,一经查实,本站将立刻删除。