how to do Authentication in Spring security using custom user detail service and angular js 2 as front end

278 Views Asked by At

this is my security configuration file

    package com.data.topic;


 @EnableWebSecurity
 @ComponentScan(basePackageClasses = CustomUserDetailService.class)
 public class Security extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/node_modules").permitAll()


                .antMatchers("/topic/**").hasRole("user")           
                .and()
            .formLogin().loginPage("/sch_signin")

                .usernameParameter("username")
                .passwordParameter("password")
                .successForwardUrl("/")
                .failureUrl("/login-error")
                .and().csrf().disable();

    }

 @Autowired
 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {    
     auth.userDetailsService(userDetailsServiceBean());
 } 

 @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return new CustomUserDetailService();
    }

   }

i want to know how should i send username and password using angular2 i tried this method on submit

 onSubmit(){

let url="http://localhost:8080/sch_signin";
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

console.log(this.user);
 this.http.post(url,JSON.stringify(this.user),options);
 console.log('data submited');

 }

i don't get any error and neither i get authenticated

please help me understand how spring intercept the authentication request

1

There are 1 best solutions below

0
On

I got the solution after some research. I was posting the form in wrong way the right way to post a form in Angular2.

let url="http://localhost:8080/sch_signin";
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers });

this.http.post(url,body.toString(),options).subscribe((data)=>console.log(data));

First the content type should be application/x-www-form-urlencoded and second you have to send the data in request body so Spring Security can read it.