java使用ReactJS在Sprint引导中实现Spring安全性
我正在尝试使用Spring Boot和ReactJS,通过Spring Security实现用户名和密码的基本登录身份验证。我试着在网上用几个例子来做这件事,但大部分都是关于JSP的,而不是关于ReactJS的。我可以用Spring Security的默认登录来运行它,但是当我尝试使用ReactJS来创建自定义登录页面时。我找不到做这件事的方法。非常感谢您的帮助或指点
**login.html**
var App = React.createClass({
getInitialState: function () {
return {
username: "",
password: ""
};
},
_onSubmit: function (event) {
event.preventDefault();
var data = {
username: this.state.username,
password: this.state.password
}
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "POST",
url: "/login",
data: JSON.stringify(data),
success: function(data){
}.bind(this),
error:function(data)
{
alert(data.responseJSON.message);
}
});
},
_onUserNameChange: function (event) {
this.setState({username: event.target.value});
},
_onPasswordChange: function (event) {
this.setState({password: event.target.value});
},
render: function() {
return (
<Grommet.App>
<Box pad='medium' align='center' >
<Box pad={{ vertical: 'medium', horizontal: 'medium', between: 'medium' }} align='center'>
</Box>
<Box size='large' pad='medium'>
<Section align='center' pad='small' separator='top'>
<Label margin='none' uppercase={true}>Tool</Label>
</Section>
</Box>
<Form pad='medium'>
<FormField label='User Name' error={this.state.usernameError}>
<input type='text' value={this.state.username} onChange={this._onUserNameChange} />
</FormField>
<FormField label='Password' value={this.state.password} onChange={this._onPasswordChange} error={this.state.passwordError}>
<input type='password' />
</FormField>
<Footer pad={{ vertical: 'medium' }} direction='column'>
<Button label='Login' primary={true} fill={true} onClick={this._onSubmit} type="submit" name="submit" />
</Footer>
</Form>
</Box>
</Grommet.App>
);
}
});
var element = document.getElementById('content');
ReactDOM.render(React.createElement(App), element);
**SecurityConfig.java**
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Override
public void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.authorizeRequests()
.antMatchers("/*").hasRole("USER")
.and()
.formLogin()
.loginProcessingUrl("/login.html");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
# 1 楼答案
问题是登录处理URL的路径:您正在将凭证从ReactJS发布到/LoginURL,但在spring安全配置中,您正在收听/Login。html
只需将配置更改为:
我想会没事的。 祝你好运