2

I have an angular 7 frontend and Spring backend.

My goal is to make a custom login using JSON form. The plan: send the username/password from frontend to backend in json form. Do the authentication in backend, and send back the result to frontend. My problem: after sending the data from frontend, I can't see the data in backend (username and password are empty) (in my CustomAuthenticationProvider.java)

My login page function:

let credential = {username: this.loginForm.value.username, password: this.loginForm.value.password};

if(this.loginForm.value.username != null && this.loginForm.value.password != null) {
     this.http.post("auth", JSON.stringify(credential)).subscribe(
           response => {
                if(response.status == 200 && response.ok == true) {
                   this.globals.loggeduser = this.loginForm.value.username;
                   //and routing
                } else {
                     alert("Bad credential");
           } 
     );
}
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    public CustomAuthenticationProvider() {
        super();
    }

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        final String username = authentication.getName();
        final String password = authentication.getCredentials().toString();

 //THE PROBLEM: username and password are empty here

            if (/* some custom auth here */) {
                final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
                final UserDetails principal = new User(username, password, grantedAuths);
                final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
             
                return auth;
            }

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET,"/login", "/index*", "/static/**", "/*.js", 
                                        "/*.json", "/*.ico", "/*.sccs", "/*.woff2", "/*.css").permitAll()
            .anyRequest()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/auth")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .failureHandler(failureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    private AuthenticationSuccessHandler successHandler() {
       ...
    }

    private AuthenticationFailureHandler failureHandler() {
       ...
    }
}

When I print out the authentication after adding values to username and password, I get this (Principal and credentials are empty):

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b37b: Principal: ; Credentials: [PROTECTED];
Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364:
RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities

Using not JSON format works fine, but I need to use JSON format. I read this and this (I tried these solutions, didn't work). These are a bit outdated and not good (too complex and/or in xml format) I read about that I have to write a custom UsernamePasswordAuthenticationFilter / using Beans, but I would like to do a nice and clean java solution without reworking the whole thing / using xml. Can I get some help/hints please?

Edit: using this format (instead of let credential = ... ), it is working (but it is not JSON unfortunately):

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', this.loginForm.value.username );
urlSearchParams.append('password', this.loginForm.value.password );
Shephard
  • 117
  • 1
  • 14

1 Answers1

0

I found a solution.

I added a CustomAuthenticationFilter, credits go to @oe.elvik's answer in this question. (note: LoginRequest is a class with 2 variables: username and password) After that, I added this into my securityConfig, and everything is working:

@Bean
public CustomAuthenticationFilter customAuthenticationFilter() throws Exception{
    CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter();
    customAuthenticationFilter.setAuthenticationManager(authenticationManager());
    customAuthenticationFilter.setFilterProcessesUrl("/auth");
    customAuthenticationFilter.setAuthenticationSuccessHandler(successHandler());
    customAuthenticationFilter.setAuthenticationFailureHandler(failureHandler());

    return customAuthenticationFilter;
}
Shephard
  • 117
  • 1
  • 14