spring 401错误提示:

7hiiyaii  于 2023-02-18  发布在  Spring
关注(0)|答案(3)|浏览(173)

我得到未经授权的错误,甚至允许所有网址。
这是我的安全配置文件:

@EnableWebSecurity
public class SecurityConfig {

    @Value("${auth0.audience}")
    private String audience;

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuer;

    @Bean
    JwtDecoder jwtDecoder() {

        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
         
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("api/public").permitAll())
            .authorizeHttpRequests()
                .requestMatchers("/api/private" ).authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt();

        DefaultSecurityFilterChain dsfc = http.build();
        return dsfc;
            
    }
    
    @Bean(name = "mvcHandlerMappingIntrospector")
    public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
        return new HandlerMappingIntrospector();
    }
}

这是我的验证器文件:

class AudienceValidator implements OAuth2TokenValidator<Jwt> {
    private final String audience;

    AudienceValidator(String audience) {
        this.audience = audience;
    }

    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
        
        if (jwt.getAudience().contains(audience)) {
            return OAuth2TokenValidatorResult.success();
        }
        return OAuth2TokenValidatorResult.failure(error);
    }
}

这些是日志文件

[2m2023-02-17T03:18:10.232+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/logout', method=POST}
[2m2023-02-17T03:18:10.233+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36mathPatternParserServerWebExchangeMatcher[0;39m [2m:[0;39m Request 'GET /api/public/allergy' doesn't match 'POST /logout'
[2m2023-02-17T03:18:10.233+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m No matches found
[2m2023-02-17T03:18:10.233+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36ma.DelegatingReactiveAuthorizationManager[0;39m [2m:[0;39m Checking authorization on '/api/public/allergy' using org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager@120362e9
[2m2023-02-17T03:18:10.233+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36mebSessionServerSecurityContextRepository[0;39m [2m:[0;39m No SecurityContext found in WebSession: 'org.springframework.web.server.session.InMemoryWebSessionStore$InMemoryWebSession@10c12b8f'
[2m2023-02-17T03:18:10.233+05:30[0;39m [32mDEBUG[0;39m [35m24360[0;39m [2m---[0;39m [2m[     parallel-3][0;39m [36mo.s.s.w.s.a.AuthorizationWebFilter      [0;39m [2m:[0;39m Authorization failed: Access Denied

我试图pemit所有的公共网址和验证所有的私人网址。但即使我允许的公共网址,我得到401错误。

0aydgbwb

0aydgbwb1#

Spring Security 6默认为拒绝,因此如果您没有显式引用URL或提供通配符,它将拒绝访问。

.requestMatchers("api/public/**").permitAll())
koaltpgm

koaltpgm2#

您提供的引用是一个特定的引用。您需要提供一个通用的引用,以便spring security接受或拒绝属于该路径的apis。请尝试以下操作:instead of "api/public" or api/private use "api/public/*" and "api/private/*"

d4so4syb

d4so4syb3#

如果您使用的是Spring Security 6.x,您的SecurityConfig上可能缺少一个@Configuration。我添加了一个注解,解释日志和配置之间的差异,因此如果缺少注解是您的问题,您可能会在以后面临进一步的配置问题。
有关详细信息,请参阅5.8迁移指南(升级到6.0时应使用)。

相关问题