在开发时,您可以在 package.json 文件中输入以下内容:
"proxy": "http://localhost:8080/"
至于Java Web应用程序,您可以提供自定义身份验证请求匹配器和身份验证入口点:
@Autowired
RestAuthEntryPoint restAuthEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("ADMIN")
.and()
.exceptionHandling()
.authenticationEntryPoint(restAuthEntryPoint) <- to support REST
.and()
.formLogin().loginProcessingUrl("/fooLogin"); <- credentials checked here
}
支持 REST 并处理未经授权的访问:
@Component
public class RestAuthEntryPoint implements AuthenticationEntryPoint{
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// send error response to the client (401 unauthorized)
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}
}
React中的登录表单提交(基本):
axios({
method:'post',
url:'//fooLogin',
params:{
username: this.state.email,
password: this.state.password
},
config: { headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
})
.then(
//authentication success...
})
.catch(error=>{
var errResp = error.response;
if(errResp.status === 401){
//Ex: show login page again...
}
})