gpt4 book ai didi

java - 使用用户角色和 Spring Security 保护 URL

转载 作者:行者123 更新时间:2023-12-01 19:18:20 24 4
gpt4 key购买 nike

我的 Java 应用程序中有多个用户角色。这是我的代码:

private String userAccess[] = new String[]{"/dashboard/**"};
private String dataAccess[] = new String[]{"/dashboard/**", "/data/**"};
private String adminAccess[] = new String[]{"/dashboard/**", "/data/**", "/admin/**"};

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(publicResources).permitAll()
.antMatchers(userAccess).hasRole("USER").anyRequest().authenticated()
.antMatchers(dataAccess).hasRole("DATA").anyRequest().authenticated()
.antMatchers(adminAccess).hasRole("ADMIN").anyRequest().authenticated()

错误:

2019-12-18T12:00:34.059+0000 DEBUG Secure object: FilterInvocation: URL: /dashboard; Attributes: hasAnyRole('ROLE_ADMIN') 2019-12-18T12:00:34.059+0000 DEBUG Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@62aad9e7: Principal: userdetails.CustomUserDetails@2228ff0d; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_DATA 2019-12-18T12:00:34.059+0000 DEBUG Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6925373, returned: -1 2019-12-18T12:00:34.062+0000 DEBUG Access is denied (user is not anonymous); delegating to AccessDeniedHandler org.springframework.security.access.AccessDeniedException: Access is denied

抱歉,似乎无法在此处的“代码”标记中显示异常:(

现在的问题是当我使用 ADMIN 登录时一切正常 100%。但是当我使用 USER 或 DATA 登录时,我收到一个异常,说我试图访问未经授权的页面。

所以发生的情况是,它加载了用户 DATA 的 URL 访问权限,但是当最后一行执行时,它会将/dashboard URL 更改为具有 ADMIN 访问权限。我的角色仍然是 DATA 角色,因此无权访问/dashboard URL。

所以看起来最后一行覆盖了其他行。再次查看 URL 权限,如果我删除“/dashboard”,那么当涉及“/data”URL 时我会遇到同样的问题。

是否有更好的方法来做到这一点,或者也许有办法让我解决这个问题?

谢谢

最佳答案

如果不重复角色的端点怎么办

private String userAccess[] = new String[]{"/dashboard/**"};
private String dataAccess[] = new String[]{"/data/**"};
private String adminAccess[] = new String[]{"/admin/**"};

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(publicResources).permitAll()
.antMatchers(userAccess).hasAnyRole("USER", "DATA", "ADMIN").anyRequest().authenticated()
.antMatchers(dataAccess).hasAnyRole("DATA", "ADMIN").anyRequest().authenticated()
.antMatchers(adminAccess).hasRole("ADMIN").anyRequest().authenticated();
}

关于java - 使用用户角色和 Spring Security 保护 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59392255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com