加载资源失败:服务器响应状态为 404 () Spring boot with JWT
Posted
技术标签:
【中文标题】加载资源失败:服务器响应状态为 404 () Spring boot with JWT【英文标题】:Failed to load resource: the server responded with a status of 404 () Spring boot with JWT 【发布时间】:2021-10-21 18:35:55 【问题描述】:您好,我正在使用 Jwt 安全性创建 Spring Boot 项目来为用户生成令牌。 但我有错误 此应用程序没有 /error 的显式映射,因此您将其视为后备。
2021 年 8 月 20 日星期五 10:02:00 EEST 出现意外错误(类型=未找到,状态=404)。
项目结构如图。
pom.xml
<?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 https://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.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.esdt</groupId>
<artifactId>delivery</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>delivery</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
用户服务
@Service
public class UserService
@Autowired
private UserRepository userRepository;
public List<user> listAll()
return userRepository.findAll();
public void save(user user)
userRepository.save(user);
public user get(UUID id)return userRepository.findById(id).get();
public void delete(UUID id)
userRepository.deleteById(id);
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
if ("delivery".equals(username))
return new User("delivery", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6",
new ArrayList<>());
else
throw new UsernameNotFoundException("User not found with username: " + username);
用户存储库:
@Repository
public interface UserRepository extends JpaRepository<user, UUID>
用户实体:
@Data
@AllArgsConstructor
@Entity
public class user implements Serializable
private static final long serialVersionUID = 5926468583005150707L;
@Id
@GeneratedValue
private UUID userId;
private String username;
private String email;
private String password;
private Integer phoneNumber;
private UUID countryId;
private String firstName;
private String lastName;
private String address;
private UUID tenantId;
private String token;
public user()
public user(String username, String password)
this.username = username;
this.password = password;
public UUID getUserId()
return userId;
public void setUserId(UUID userId)
this.userId = userId;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getEmail()
return email;
public void setEmail(String email)
this.email = email;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public Integer getPhoneNumber()
return phoneNumber;
public void setPhoneNumber(Integer phoneNumber)
this.phoneNumber = phoneNumber;
public UUID getCountryId()
return countryId;
public void setCountryId(UUID countryId)
this.countryId = countryId;
public String getFirstName()
return firstName;
public void setFirstName(String firstName)
this.firstName = firstName;
public String getLastName()
return lastName;
public void setLastName(String lastName)
this.lastName = lastName;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
public UUID getTenantId()
return tenantId;
public void setTenantId(UUID tenantId)
this.tenantId = tenantId;
public String getToken()
return token;
public void setToken(String token)
this.token = token;
Jwt 响应:
public class JwtResponse implements Serializable
private static final long serialVersionUID = -8091879091924046844L;
private final String jwttoken;
public JwtResponse(String jwttoken)
this.jwttoken = jwttoken;
public String getToken()
return this.jwttoken;
用户控制器:
@RestController
@RequestMapping("/api")
public class UserController
@Autowired
private UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserService userDetailsService;
@GetMapping("/users")
public List<user> list()
return userService.listAll();
@GetMapping("/users/id")
public ResponseEntity<user> get(@PathVariable UUID id)
try
user customer = userService.get(id);
return new ResponseEntity<user>(customer, HttpStatus.OK);
catch(NoSuchElementException e)
return new ResponseEntity<user>(HttpStatus.NOT_FOUND);
@PostMapping("/user")
public void add(@RequestBody user user)
userService.save(user);
@PutMapping("/user/id")
public ResponseEntity<?> update(@RequestBody user user,
@PathVariable UUID id)
try
user existuser = userService.get(id);
userService.save(user);
return new ResponseEntity<user>(user, HttpStatus.OK);
catch(NoSuchElementException e)
return new ResponseEntity<user>(HttpStatus.NOT_FOUND);
@DeleteMapping("/user/id")
public void delete(@PathVariable UUID id)
userService.delete(id);
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody user authenticationRequest) throws Exception
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtResponse(token));
private void authenticate(String username, String password) throws Exception
try
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
catch (DisabledException e)
throw new Exception("USER_DISABLED", e);
catch (BadCredentialsException e)
throw new Exception("INVALID_CREDENTIALS", e);
用户应用程序:
@SpringBootApplication(exclude = SecurityAutoConfiguration.class )
public class DeliveryCoreApplication
public static void main(String[] args)
SpringApplication.run(DeliveryCoreApplication.class, args);
配置:
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable
private static final long serialVersionUID = -7858869558953243875L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
public class JwtRequestFilter extends OncePerRequestFilter
@Autowired
private UserService jwtUserDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@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 "))
jwtToken = requestTokenHeader.substring(7);
try
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
catch (IllegalArgumentException e)
System.out.println("Unable to get JWT Token");
catch (ExpiredJwtException e)
System.out.println("JWT Token has expired");
else
logger.warn("JWT Token does not begin with Bearer String");
// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null)
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
// 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);
chain.doFilter(request, response);
@Component
public class JwtTokenUtil implements Serializable
private static final long serialVersionUID = -2550185165626007488L;
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;
@Value("$jwt.secret")
private String secret;
//retrieve username from jwt token
public String getUsernameFromToken(String token)
return getClaimFromToken(token, Claims::getSubject);
//retrieve expiration date from jwt token
public Date getExpirationDateFromToken(String token)
return getClaimFromToken(token, Claims::getExpiration);
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver)
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
//for retrieveing any information from token we will need the secret key
private Claims getAllClaimsFromToken(String token)
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
//check if the token has expired
private Boolean isTokenExpired(String token)
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
//generate token for user
public String generateToken(UserDetails userDetails)
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
//while creating the token -
//1. Define claims of the token, like Issuer, Expiration, Subject, and the ID
//2. Sign the JWT using the HS512 algorithm and secret key.
//3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
//compaction of the JWT to a URL-safe string
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 * 1000))
.signWith(SignatureAlgorithm.HS512, secret).compact();
//validate token
public Boolean validateToken(String token, UserDetails userDetails)
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private UserDetailsService jwtUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate").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);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
【问题讨论】:
项目在描述中。您的网址不是,代码也不是。您到底希望我们做什么? 好的,检查更新 【参考方案1】:检查您使用的 HTTP 方法(POST、PUT 等)是否与您发送的请求匹配,我建议使用类似 Postman 的工具,调试控制器中的 createAuthenticationToken 方法以及 JWT 过滤器类中的 doFilterInternal。我可以准确地说出发生了什么,但这是缩小问题范围的指南
【讨论】:
@Marwa 这个工作吗?如果是,您可以接受它,这样您就可以增加获得更多答案的机会以上是关于加载资源失败:服务器响应状态为 404 () Spring boot with JWT的主要内容,如果未能解决你的问题,请参考以下文章
Apache Cordova:“加载资源失败:服务器响应状态为 404(未找到)”