小结:我无法让jwt使用基于角色的访问。jwt本身运行良好。我已经查看了几个现有的堆栈溢出响应,但是还没有找到我需要的信息。
我正在使用 Postman 验证返回jwt的邮件。然后,我将该令牌复制到get localhost:8080/hello头中。请求未触发security.config jwt请求筛选器。它似乎没有走那么远。
索赔问题:(参考:jwttokenutil)
当我获得授予权限的用户详细信息时,它只返回单个字符串。创建jwt声明对象时,它似乎是一个键值对。键值对是什么?现在我正在添加用户名和权限。
由于我的安全配置文件在整个数据库中使用角色而不是权限,并且我的数据库存储角色而不是权限,所以我是否将角色加载到claims对象中?或者spring security是专门寻找权威机构的吗?换句话说,没有附加“角色”的角色。
安全第一步:最初,Spring Security 使用基于角色的访问。我创建了标准的用户和权限表。对于当局,我使用角色_而不是特权。在安全配置文件中,我使用ant匹配来提供基于角色的访问。
安全性第二步:我将应用程序转换为使用jwt。我很成功地阅读了这篇文章。https://www.javainuse.com/spring/boot-jwt 没有任何基于角色的访问端点。
安全性第三步:使用postman,我可以进行身份验证,但不能访问/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.";
}
}
暂无答案!
目前还没有任何答案,快来回答吧!