【问题标题】:Spring Boot Security - Postman gives 401 UnauthorizedSpring Boot Security - Postman 给出 401 Unauthorized
【发布时间】:2019-07-12 12:30:55
【问题描述】:

我正在 Spring Boot 中开发其他 API。我能够进行 CRUD 操作并且邮递员给出了正确的响应,但是当我添加 Spring Security 用户名和密码时,邮递员给出 401 Unauthorized。

我已经提供了一个 Spring Boot 安全用户名和密码,如下所示。

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

我已经完成了基本的身份验证,用户名是 root,密码是 root。 预览请求提供了成功更新标头的消息:

编辑 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();

}

【问题讨论】:

  • 请为此请求删除 Postman 的 cookie,然后重试。
  • kamlesh pandey 我已经删除了 cookie 但仍然面临同样的问题

标签: java spring spring-boot spring-security postman


【解决方案1】:

如果spring boot需要授权,根配置类下面的注解。

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

下面的依赖也需要添加

<dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>

【讨论】:

    【解决方案2】:
    @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()
        }
    }
    

    您需要配置 Spring Security,默认情况下所有路由都为授权保护。

    请查看Link 处的 JWT 令牌实现。

    【讨论】:

    • Nishant 谢谢你的回答,但仍然面临这个问题,我已经用 WenSecurityConfiguration 更新了我的问题。请看一看。
    • 你现在遇到什么问题??
    • Nishant,当我使用 GET 方法时,我得到了详细信息,但是当我尝试使用 POST、PUT 或 DELETE 时,邮递员给出 401 Unauthorized/403 Forbidden
    • @Romil 根据更新后的代码,仅 /login 不会为您提供 401。请查看更新后的答案并 permitAll() 您不需要任何身份验证的 API...此外,您可以为 API 使用 JWT 令牌,这是保护 API 的最佳方式之一...
    • 感谢@Nishant .antMatchers(HttpMethod.POST,"/admin/**").permitAll() 解决问题。我去看看 JWT。
    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2021-08-21
    • 2018-06-20
    • 2017-06-25
    • 1970-01-01
    • 2020-09-10
    • 2019-03-25
    相关资源
    最近更新 更多