Вывод: мне не удается заставить JWT работать с доступом на основе ролей. JWT сам по себе работает нормально. Я просмотрел несколько существующих ответов на переполнение стека, но еще не нашел нужной мне информации.
Я использую почтальона для аутентификации, который возвращает мой JWT. Затем я копирую этот токен в заголовок get localhost:8080/hello. Запрос не запускает фильтр запросов JWT security.config. Кажется, это не так далеко.
Вопросы по претензиям: (ссылка: JwtTokenUtil)
Когда я получаю данные пользователя с предоставленными полномочиями, он возвращает только одну строку. При создании объекта утверждений JWT кажется, что это пара ключ-значение. Что входит в пару ключ-значение? Прямо сейчас я добавляю имя пользователя и полномочия.
Поскольку в моем файле конфигурации безопасности повсюду используются роли, а не полномочия, и в моей базе данных хранятся роли, а не полномочия, нужно ли загружать роли в объект утверждений? Или весенняя безопасность ищет специально власти? Другими словами, роль без добавления «ROLE_».
Безопасность: первый шаг: изначально безопасность Spring использовала доступ на основе ролей. Я создал стандартные таблицы пользователей и полномочий. Для полномочий я использовал ROLE_xxx вместо привилегий. В файле конфигурации безопасности я использовал сопоставление муравьев для предоставления доступа на основе ролей.
Второй этап безопасности: я преобразовал приложение для использования JWT. Я следил за этой статьей с большим успехом. https://www.javainuse.com/spring/boot-jwt Без какой-либо роли на основе конечных точек доступа.
Третий шаг безопасности. Используя postman, я могу аутентифицироваться, но не могу получить доступ к конечной точке /hello. Если я добавлю конечную точку /hello в список разрешений для всех и добавлю токен в свой запрос заголовка, я получу действительный ответ. Если я попытаюсь использовать 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.";
}
}
2.1.1.RELEASE
, выпущенный в 2018 году, поэтому он устарел. Также я бы не стал использовать JWT в качестве замены сеанса, поскольку jwts подвержены XSS-атакам, если они реализованы неправильно. developer.okta.com/blog/ 17.08.2017/ - person Toerktumlare   schedule 18.06.2021