java - 检查经过身份验证的用户是否可以访问 URL

标签 java spring-boot spring-security

我已经使用 spring-security-4.2.2 设置了 spring-boot-1.5.3 应用程序,并根据权限配置了受限路径。这些限制看起来与此类似:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/accounts/**", "/roles/**")
                    .hasAuthority(ADMINISTRATOR)
                    .and()
                .antMatchers("/**")
                    .hasAuthority(USER)
                    .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .and()
            .csrf()
                .disable();
    }
}

简而言之 - 我希望拥有权限 USER 的用户能够访问除 /accounts/**/roles/** 路径之外的整个 Web 应用程序。此配置工作正常,如果我尝试在没有适当权限的情况下访问这些页面,我会收到预期的错误(403)。

对于具有 USER 权限的用户,我想隐藏一些 URL,以便他们不会发出这些请求并收到 403 错误。 如何检查是否允许用户访问某个 URL

到目前为止,我已经尝试注入(inject) WebInitationPrivilegeEvaluator 并调用其 isAllowed 方法,尽管这似乎不起作用。例如:

// Helper class that returns authentication instance.
Authentication auth = AuthUtils.getAuthentication();

// Don't have permission to access /users, expect to get false result.
boolean res = webInvocationPrivilegeEvaluator.isAllowed("/users", auth );

assert res == false; // fails

最佳答案

而是使用方法来检查用户是否有权限。

SecurityContextHolderAwareRequestWrapper.isUserInRole(String role)

关于java - 检查经过身份验证的用户是否可以访问 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44203765/

相关文章:

Spring Boot Actuator端点配置似乎没有按预期工作

spring-security - Spring Security 3 中的组权限只是将多个角色组合为一个的快捷方式吗?

spring - 根据特定条件添加 http 或 https

java - 按特定顺序仅使用 5 个线程打印从 1 到 10 的整数

spring-boot - 如何解决 openapi-generator-maven-plugin 使用不推荐使用的类?

java - 带有连接池的 spring boot 应用程序中的 SQLServerDataSource

grails - 如何使用IS_AUTHENTICATED_FULLY IN grails 3 spring-security

java - 如何水平打印 jframe 或为其赋予打印属性?

java - 在 AppEngine 上使用谷歌云端点

构造函数中带有枚举的java枚举