Spring Boot Security - Postman gives 401 Unauthorized
Asked Answered
I

3

17

I am developing rest APIs in Spring Boot. I am able to do CRUD operations and postman gives correct responses, but when I add Spring Security username and password Postman gives 401 Unauthorized.

I have provided a spring boot security username and password as below.

application.proptries

spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/pal?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.security.user.name=root
spring.security.user.password=root

I have done basic auth with username as root and password as root. Preview request gives headers updated successfully message :

enter image description here

EDIT I have deleted the cookies in postman but still facing the same issue

SecurityConfing.java
My Security Configuration are as below. 
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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;

@Configuration
@EnableWebSecurity
@Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter{


    public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {

        authenticationMgr.jdbcAuthentication().dataSource(dataSource())
          .usersByUsernameQuery(
           "select email,password from user where email=? and statusenable=true")
          .authoritiesByUsernameQuery(
           "select email,role from user where email=? and statusenable=true");

        System.out.println(authenticationMgr.jdbcAuthentication().dataSource(dataSource())
          .usersByUsernameQuery(
           "select email,password from user where email=? and statusenable=true")
          .authoritiesByUsernameQuery(
           "select email,role from user where email=? and statusenable=true"));
    }

    @Bean(name = "dataSource")
     public DriverManagerDataSource dataSource() {
         DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
         driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
         driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/pal");
         driverManagerDataSource.setUsername("root");
         driverManagerDataSource.setPassword("");
         return driverManagerDataSource;
     }

    @Override
     protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .authorizeRequests().antMatchers("/login").permitAll()
    .anyRequest().authenticated()
    .and()
    .formLogin().loginPage("/login").permitAll()
    .and()
    .authorizeRequests().antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN","ROLE_USER").anyRequest().permitAll()
    .and()
    .authorizeRequests().antMatchers("/user/**").hasAnyRole("ROLE_USER").anyRequest().permitAll();

}
Indemnification answered 19/2, 2019 at 4:29 Comment(2)
Please delete the cookies of Postman for this request and try again.Reena
kamlesh pandey I have deleted the cookies but still facing the same issueIndemnification
S
17
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http.csrf().disable().authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers(HttpMethod.POST,"/newuser").permitAll()
        .antMatchers(HttpMethod.POST, "/login").permitAll()
        .antMatchers(HttpMethod.POST,"/newuser/*").permitAll()
        .antMatchers(HttpMethod.GET,"/master/*").permitAll()
         .antMatchers(HttpMethod.GET,"/exploreCourse").permitAll()
        .anyRequest().authenticated()
    }
}

You need to configure Spring Security, by default all routes all secured for authrorization.

Please have a look JWT Token implementation at this Link.

Schenk answered 19/2, 2019 at 7:41 Comment(9)
Nishant Thank you for your answer but still facing the issue, I have updated the question with my with WenSecurityConfiguration. Please have a look.Indemnification
What issue you are getting now??Schenk
Nishant, I get the details when I use GET Method but when I try to use POST, PUT or DELETE postman gives 401 Unauthorized/403 ForbiddenIndemnification
@Romil as per the updated code only /login will not gives you 401. Please have a look at updated answer and permitAll() your APIs for which you dont need any authentication...Moreover you can use JWT Token for APIs which is one of the best way for securing APIs...Schenk
Thanks @Nishant .antMatchers(HttpMethod.POST,"/admin/**").permitAll() solve the issue. I will take a look on JWT.Indemnification
Any other reason why this problem could happen? I ask because I have mine exactly like yours and I still keep receiving 401 for the POST endPoint on .permitAll(), for the GET It works well, the problem is for the POST.Acidulous
@FranciscoSouza have you fixed the issue ? I'm facing the sameAmylopsin
Facing same issue. the same code that I have is working on colleague's systemEdgeworth
I saw that on using csrf().disable() the POST, PUT operations started working in Postman tool. Why is it so? If I don't use then I get 401 errorCampstool
L
3

Just exclude the SecurityAutoConfiguration class

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class BackendApplication {

  public static void main(String[] args) {
     SpringApplication.run(BackendApplication.class, args);
  }
}
Lint answered 3/3 at 6:5 Comment(0)
R
1

If Authorization needed in spring boot, the below annotation at root configuration class.

@EnableAuthorizationServer
( and other required annotations)
public class Application{
....
....
}

Below dependency also needed to be added

<dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>
Rigby answered 14/1, 2021 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.