使用ReactJs向Spring Security提交JWT Token的步骤如下:
npm install axios
import axios from 'axios';
const login = async (username, password) => {
try {
const response = await axios.post('http://your-spring-security-login-endpoint', {
username: username,
password: password
}, {
headers: {
Authorization: 'Bearer ' + YOUR_JWT_TOKEN
}
});
// 处理登录成功的逻辑
} catch (error) {
// 处理登录失败的逻辑
}
}
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = obtainUsername(request);
String password = obtainPassword(request);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
return authenticationManager.authenticate(authenticationToken);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
// 生成JWT Token
String jwtToken = generateJwtToken(authResult);
// 将JWT Token添加到响应头中
response.addHeader("Authorization", "Bearer " + jwtToken);
}
private String generateJwtToken(Authentication authentication) {
// 生成JWT Token的逻辑
// ...
return jwtToken;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
这样,当用户在ReactJs中提交登录表单时,ReactJs会将用户名和密码发送到Spring Security的登录接口,并将JWT Token作为请求头的一部分。Spring Security会验证用户名和密码,并生成一个JWT Token返回给ReactJs。
领取专属 10元无门槛券
手把手带您无忧上云