当前位置: 首页 > 知识库问答 >
问题:

为什么这个spring oauth配置从未未经授权返回401?

洪浩
2023-03-14

我按照这里的教程尝试开始使用spring OAuth。但是,没有页面返回未经授权的401,即使我没有通过服务器验证(本教程中的配置示例应该禁用匿名访问。本教程中与此问题相关的唯一注释只有一个响应,即授权尚未启用,但我在其中一个配置类上有@enableAuthorizationServer

所有配置类

应用:

@SpringBootApplication
@EnableTransactionManagement
@EnableAutoConfiguration(exclude = {RepositoryRestMvcAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    private static String REALM = "EXAMPLE_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler handler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
               .withClient("trusted-client")
               .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
               .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
               .scopes("read", "write", "trust")
               .secret("secret")
               .accessTokenValiditySeconds(300)//invalid after 5 minutes.
               .refreshTokenValiditySeconds(600);//refresh after 10 minutes.
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(handler)
                 .authenticationManager(authManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM + "/client");
    }
}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "SPRING_REST_API";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable()
            .requestMatchers().anyRequest()
            .and().authorizeRequests()
            .anyRequest().access("hasRole('ADMIN')")
            .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

“安全”:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ClientDetailsService clientService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("javabycode").password("123456").roles("USER")
            .and()
            .withUser("admin").password("admin123").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("/oauth/token").permitAll();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientService));
        handler.setClientDetailsService(clientService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }
}

可能不相关,但也有:

@Configuration
@EnableWebMvc
@EnableWebSecurity
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

在通读了教程的完整源代码后,我添加了

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

最后,这个项目的build.gradle,因为我在使用Spring时经常遇到特定版本依赖关系的问题:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE")
        classpath('com.h2database:h2:1.4.193')
        classpath('org.hibernate:hibernate-core:5.0.12.Final')
        classpath('org.springframework.boot:spring-boot-starter-security:1.5.2.RELEASE')
    }
}

apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
sourceCompatibility = 1.8
targetCompatibility = 1.8

String appVersion = "1.0.0"

war{
    baseName="cubscout-rest"
    version=appVersion
    doFirst {
        manifest {
            attributes("Implementation-Title": 'cubscout-rest', "Implementation-Version": appVersion, "Implementation-Timestamp": new Date())
        }
    }
}

repositories {
    jcenter()
}

dependencies {
    compile project(':core')

    compile 'org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE'
    compile 'org.springframework.boot:spring-boot-starter-web:1.5.1.RELEASE'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.5.1.RELEASE'
    //compile 'org.springframework.integration:spring-integration-core:4.3.7.RELEASE'
    //compile 'org.springframework.batch:spring-batch-core:3.0.7.RELEASE'
    compile 'org.springframework.data:spring-data-jpa:1.11.0.RELEASE'
    compile 'org.springframework.data:spring-data-rest-webmvc:2.6.0.RELEASE'
    compile 'org.springframework.security:spring-security-web:4.2.1.RELEASE'
    //compile 'org.springframework.boot:spring-boot-starter-security:1.5.2.RELEASE'
    compile 'org.springframework.security.oauth:spring-security-oauth2:2.1.0.RELEASE'
    compile 'org.hibernate:hibernate-core:5.0.12.Final'
    compile 'com.h2database:h2:1.4.193'
    compile 'org.springframework.boot:spring-boot-starter-tomcat:1.5.1.RELEASE'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-all:1.10.19'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:1.5.1.RELEASE'
}

共有1个答案

程亦
2023-03-14

Spring Boot的自动配置之一是干扰。变化

@SpringBootApplication
@EnableTransactionManagement
@EnableAutoConfiguration(exclude = {RepositoryRestMvcAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {

@SpringBootApplication
@EnableTransactionManagement
@EnableAutoConfiguration(exclude = {RepositoryRestMvcAutoConfiguration.class, OAuth2AutoConfiguration.class})
public class Application extends SpringBootServletInitializer {

允许我的配置正常运行。

 类似资料:
  • 我正在尝试用JWT保护我的Quarkus API。提供了JWT(代码段:)。 两个endpoint(和)都返回一个HTTP(未经授权)。 你知道为什么吗?我以为允许每一个请求?即使我的令牌证明我有所需的角色: 编辑:发现MicroProfile规范说

  • 所以,我试图用Tweepy喜欢一个推文,但是这个错误正在发生: 有什么想法吗?

  • 我正在使用postman,并尝试通过http://localhost:8180/auth/admin/realms/demo/users/{userID}更新用户的配置文件,但收到响应。 通过http://localhost:8180/auth/admin/realms/demo/users/{userID}发送带有Json内容类型和用户信息的Put请求。 不幸的是,我已经连续收到了401个回复。

  • 我们正在使用AWS Lambda授权器和API网关来保护我们的下游API。 下面是我们基于Java的lambda授权程序的代码片段 我们需要401(“未经授权”)作为一个回应,有人能请帮助如何做这一点吗?我们有用Java编写的lambda授权器。

  • 在这个留档Spring Security MVC Test中描述了如何使用Spring Security测试安全的ressource。我遵循了提供的所有步骤,但访问受保护的ressource仍然会返回错误代码401(未经授权)。 这是我的测试课 我的资源服务器配置: 如果你想看看整个项目,你可以在这里找到。我已经尝试了不同的测试运行程序和教程中描述的所有内容,但我找不到一个解决方案,如何在测试期间

  • 问题内容: 我从Nexus存储库中检出了代码。我更改了帐户密码,并在文件中正确设置了密码。在执行时,我收到错误消息,说明它尝试从该存储库下载文件。 任何想法如何解决此错误?我在Maven 3.04中使用Windows 7 问题答案: 这里的问题是所使用的密码出现错字错误,由于密码中使用了字符/字母,因此很难识别。