I'm developing an application with spring as backend and angular2 as frontend , The Backend side is secured (with Spring security ), and I have the default login form when I run it. I want to log in from the client side to the server side but when I try to pass the credentials I have these errors in the browser console
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and().withUser("user")
.password("user").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/etudiant/list").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<div class="login jumbotron center-block"> <h1>Login</h1> <form role="form" (submit)="login(username.value, password.value)"> <div class="form-group"> <label for="username">Username</label> <input type="text" #username class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" #password class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div>
I would create an @Injectable()
AuthService with the following method called by the form.
login(usercreds) {
const headers = new Headers();
const creds = 'name=' + usercreds.username + '&password=' + usercreds.password;
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return new Promise((resolve) => {
this.http.post('http://localhost:3333/authenticate', creds, {headers: headers}).subscribe((data) => {
if (data.json().success) {
// window.localStorage.setItem('auth_key', data.json().token);
this.userId = data.json().userId;
this.isAuthenticated = true;
}
resolve(this.isAuthenticated);
});
});
}
Do not forget to declare this component as provider in the app.module.ts
file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.