简体   繁体   中英

Spring: BasicHttp doesn't work with jdbcAuthentication when hitting requests from Postman

I am trying to implement jdbcAuthentication in my project. The problem is that it works when I make requests from browser but when I make requests from Postman it doesn't work, I mean authentication doesn't happen and even random credentials work.

However if I use inMemoryAuthentication it works fine for both browser and Postman. This is my code inside SecurityConfig .

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery("select username, role from user_roles where username=?");    

   // This works -->    auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().csrf().disable();
    }

In postman I make a POST request.

In Authorization type I select basic auth and enter the credentials which are then populated in the Authorization header below

These are the headers

Content-Type:application/json
X-XSRF-TOKEN:{{X-CSRF-TOKEN}}
Authorization:Basic ajhsjajywshhshshsssss

If I comment the jdbcAUthentication part and uncomment the inMomeryAuthentication code, authentication works from both broswer and postman. Can someone please help me, why is this happening? Am I missing something? Thanks !!

You are using .authenticated() , this means the user is already authenticated and you want to allow users that are already authenticated (aka "remembered").

http.authorizeRequests().anyRequest()
    .authenticated().and().httpBasic().and().csrf().disable();

But actually, what you want to do is to authenticate for first time, so for this you need to change it to fullyAuthenticated

http.authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and().httpBasic()
            .and().csrf().disable();

If you check the AuthorizedUrl documentation you will find:

authenticated() : Specify that URLs are allowed by any authenticated user.

fullyAuthenticated() : Specify that URLs are allowed by users who have authenticated and were not "remembered".

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM