代码之家  ›  专栏  ›  技术社区  ›  Kshitiz Bathwal

SpringSecurity提供错误401错误凭据

  •  0
  • Kshitiz Bathwal  · 技术社区  · 7 年前

    我对springsecurity是个新手,正在创建一个简单的应用程序来检查身份验证和授权。我正在使用内存数据库。即使我提供了正确的登录凭据,我也会收到错误401“错误凭据”错误。 我还在一些rest端点上使用permitAll()函数,但在这些端点上也会得到一个登录提示。我试图清除浏览器历史记录和缓存也没有成功。请帮忙。我附上密码。

    安全配置.java

        package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    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
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        //Authentication using In Memory Database
        public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder)throws Exception{
            authenticationManagerBuilder.inMemoryAuthentication()
            .withUser("user").password("{noop}pass123").authorities("ROLE_USER")
            .and()
            .withUser("admin").password("{noop}pass123").authorities("ROLE_USER","ROLE_ADMIN");        
        }
    
        //Authorization
        @Override //Overriding configure to use HttpSecurity for web based HTTP requests
        public void configure(HttpSecurity httpSecurity)throws Exception{
            httpSecurity.
            authorizeRequests()
            .antMatchers("/protectedbyuserrole*").hasRole("USER")
            .antMatchers("/protectedbyadminrole*").hasRole("ADMIN")
            .antMatchers("/","/notprotected").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic();    
        }
    }
    

    SpringSecurityApplication.Java

        package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Import;
    
    @SpringBootApplication
    @ComponentScan({"com.example.demo","controller"})
    @Import({SecurityConfig.class})
    public class SpringSecurityApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringSecurityApplication.class, args);
        }
    }
    

        package com.example.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestSecurityController {
        @RequestMapping("/")
        public String Hello() {
            return "Hello World!! ";
        }
    
        @RequestMapping("/notprotected")
        public String HelloAgain() {
            return "Hello from a non protected user!! ";
        }
    
        @RequestMapping("/protectedbyuserrole")
        public String HelloUser() {
            return "Hello User Role!! ";
        }
    
        @RequestMapping("/protectedbyadminrole")
        public String HelloAdmin() {
            return "Hello Admin Role!! ";
        }
    }
    

    POM.xml文件

        <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.19.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>SpringSecurity-1</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>SpringSecurity-1</name>
        <description>SpringSecurity for Authentication and Authorization</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    查询

    我应该在.antmatchers()中使用单*或**星号吗

    我也用Postman和Firefox试过了。到处都是同样的错误。 POSTMAN SCREENSHOT

    0 回复  |  直到 7 年前
        1
  •  1
  •   Romil Patel    7 年前

    在RequestMapping中指定特定的方法(GET、POST等)是您可能需要遵循的一个好实践。

    我分享了一个我过去做过的基本例子。 如果你还面临这个问题,让我知道你的邮递员截图

      @Override
            public void configure(AuthenticationManagerBuilder auth) 
              throws Exception {
    
                auth.inMemoryAuthentication()
                    .withUser("myusername")
                    .password("mypassword")
                    .roles("USER");
            }
    

    @Override
            protected void configure(HttpSecurity http) throws Exception{
    
                 http
                 .csrf().disable()
                 .authorizeRequests().antMatchers("/login","/home","/failure").permitAll()
                 .antMatchers(HttpMethod.POST,"/admin/**").hasRole("ADMIN") 
                 .antMatchers(HttpMethod.PUT,"/admin/**").hasRole("ADMIN")
                 .antMatchers(HttpMethod.GET,"/admin/**").hasRole("ADMIN")
                 .antMatchers(HttpMethod.GET,"/user/**").hasAnyRole("ADMIN","USER")
                 .antMatchers(HttpMethod.POST,"/user/**").hasAnyRole("ADMIN","USER")
                 .anyRequest().authenticated();
    
        }
    

    编辑

    映射使用以下规则匹配URL:

    • ? 匹配一个字符

    • **匹配路径中的零个或多个目录

    Refer Path Matcher Here

     @RequestMapping(value="/protectedbyuser",method=RequestMethod.GET)
            public String Hello() {
                return "Hello Protected By User!! ";
            }