Spring Security 忽略角色

camsedfj  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(288)

我有一个控制器:

@RestController
public class NumbersController {

    @PreAuthorize("hasRole('ROLE_ONE')")
    @GetMapping("/one")
    private String one(){
        return "This is one.";
    }

    @PreAuthorize("hasRole('ROLE_TWO')")
    @GetMapping("/two")
    private String two(){
        return "This is two.";
    }
}

以及此安全配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth
                .inMemoryAuthentication()
                .withUser("user").password(encoder.encode("password")).roles("ONE");
        auth
                .inMemoryAuthentication()
                .withUser("user2").password(encoder.encode("password2")).roles("TWO");
    }

}

在运行时,我的两个用户都可以访问这两个资源。我想要的只是 user 能够访问 /one 而且只为 user2 访问 /two . 我也试过用 @Secured("ONE") 同样的结果。
控制台输出:

2021-01-14 16:10:20.026  INFO 4376 --- [           main] security.security.SecurityApplication    : Starting SecurityApplication on Ivan-PC with PID 4376 (D:\Z\security\target\classes started by Ivan in D:\Z\security)
2021-01-14 16:10:20.041  INFO 4376 --- [           main] security.security.SecurityApplication    : No active profile set, falling back to default profiles: default
2021-01-14 16:10:24.363  INFO 4376 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-01-14 16:10:24.378  INFO 4376 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-01-14 16:10:24.378  INFO 4376 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-14 16:10:24.565  INFO 4376 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-01-14 16:10:24.565  INFO 4376 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4321 ms
2021-01-14 16:10:25.221  INFO 4376 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-14 16:10:25.860  INFO 4376 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@57a48985, org.springframework.security.web.context.SecurityContextPersistenceFilter@17740dae, org.springframework.security.web.header.HeaderWriterFilter@14bf57b2, org.springframework.security.web.csrf.CsrfFilter@48535004, org.springframework.security.web.authentication.logout.LogoutFilter@3cee53dc, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@67440de6, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@35835e65, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@1ab6718, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7ce7e83c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@345cf395, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7144655b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3910fe11, org.springframework.security.web.session.SessionManagementFilter@14379273, org.springframework.security.web.access.ExceptionTranslationFilter@cfbc8e8, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@49293b43]
2021-01-14 16:10:25.969  INFO 4376 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-14 16:10:25.985  INFO 4376 --- [           main] security.security.SecurityApplication    : Started SecurityApplication in 6.771 seconds (JVM running for 8.031)
2021-01-14 16:10:29.847  INFO 4376 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-01-14 16:10:29.848  INFO 4376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-01-14 16:10:29.870  INFO 4376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 22 ms

要求 Postman http://localhost:8080/two 以及使用授权字段。

xjreopfe

xjreopfe1#

如果有用的话检查一下,
我们可以像配置多个块一样配置多个httpsecurity示例。关键是多次扩展WebSecurity配置器适配器。例如,下面是一个对以/api/开头的url进行不同配置的示例。

@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Bean                                                             
    public UserDetailsService userDetailsService() throws Exception {
        // ensure the passwords are encoded properly
        UserBuilder users = User.withDefaultPasswordEncoder();
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(users.username("user").password("password").roles("USER").build());
        manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
        return manager;
    }
@Configuration
@Order(1)                                                        
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/api/**")                               
            .authorizeRequests(authorize -> authorize
                .anyRequest().hasRole("ADMIN")
            )
            .httpBasic(withDefaults());
    }
}

@Configuration                                                   
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .formLogin(withDefaults());
    }
}
}

将身份验证配置为正常创建包含@order的WebSecurityConfigureAdapter示例,以指定应首先考虑哪个WebSecurityConfigureAdapter。antmatcher声明这个httpsecurity将只适用于以/api/创建另一个websecurityconfigureradapter示例开头的url。如果url不是以/api/开头,则将使用此配置。此配置在apiwebsecurityconfigurationadapter之后考虑,因为它的@order值在1之后(没有@order默认为last)。

wztqucjr

wztqucjr2#

在你的房间里试试这个 SecurityConfig

@EnableGlobalMethodSecurity(
      prePostEnabled = true,  
      jsr250Enabled = true)

preprestenabled属性启用spring security pre/post注解
jsr250enabled属性允许我们使用@roleallowed注解

相关问题