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

无法实现对Spring-Boot API的基于角色的访问

葛玉堂
2023-03-14

我是Spring-Boot的新手。我想创建一个API,它将具有基于角色的访问权限和基于JWT令牌的身份验证。但是,无法实现。

我没有使用JPA

安全配置

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

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .csrf().disable()

   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
          .and()
          .addFilter(new JwtAuthorizationFilter(authenticationManager()))
          .authorizeRequests()
          .anyRequest().authenticated()
          .antMatchers("api/management/reports").hasRole("Supervisor");
    }

控制器

@RestController
@RequestMapping("api")
@CrossOrigin
public class MyController {

    @PreAuthorize("hasRole('Supervisor')")
    @GetMapping("username")
    public String reports(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return securityContext.getAuthentication().getName();
    }
}

授权过滤器

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

String header = request.getHeader(JwtProperties.HEADER_STRING);
if (header == null || !header.startsWith(JwtProperties.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        Authentication authentication = getUsernamePasswordAuthentication(request,header);
        SecurityContextHolder.getContext().setAuthentication(authentication);


        chain.doFilter(request, response);
}
private Authentication getUsernamePasswordAuthentication(HttpServletRequest request, String header) {
        try {
String token = header.replace(JwtProperties.TOKEN_PREFIX,"");
String userName = JWT.require(HMAC512(JwtProperties.SECRET.getBytes()))
                        .build()
                        .verify(token)
                        .getSubject();
List<User> searchedUserList = getUserDetailsDAO().getUserDetails(userName);


    if (null !=searchedUserList && searchedUserList.size()>0) {

        User searchedUser = new User();
        searchedUser = searchedUserList.get(0);
        List<RoleAccess> roleAccessList = new ArrayList<RoleAccess>();
    XrefUsrRole oXrefUsrRole = new XrefUsrRole();
    oXrefUsrRole.setUserName(searchedUser.getUsername());
    roleAccessList = getRoleAccessDAO().getAccessDetails(oXrefUsrRole);
    List<GrantedAuthority> authorities = uildUserAuthority(roleAccessList);

    org.springframework.security.core.userdetails.User newUser = buildUserForAuthentication(searchedUser, authorities);

UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(newUser, null,authorities);
                    return auth;
                }
                return null;
            }
            return null;
        } catch (IOException e) {
            return null;
        }

private org.springframework.security.core.userdetails.User buildUserForAuthentication(User searchedUser, List<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(searchedUser.getUsername(), searchedUser.getPassword(), true, true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(List<RoleAccess> roleAccessList) {
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (RoleAccess userRole : roleAccessList) {
            setAuths.add(new SimpleGrantedAuthority("ROLE_"+userRole.getModifiedBy()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }

在这种情况下,除了具有主管角色的用户之外,不应访问api/username。

共有1个答案

丌官飞章
2023-03-14

您有ROLE_“ userRole.getModifiedBy()),这意味着您正在授予具有ROLE_NAME的角色,并且在预授权中,您有导致问题的主管。您可以将角色存储为ROLE_SUPERVISOR在数据库中,然后按如下方式使用它

    // Build user's authorities
    for (RoleAccess userRole : roleAccessList) {
        setAuths.add(new SimpleGrantedAuthority("ROLE_"+userRole.getModifiedBy()));
    }

@PreAuthorize("hasRole('ROLE_SUPERVISOR')")
.antMatchers("api/management/reports").hasRole("SUPERVISOR");
 类似资料:
  • 问题内容: 是否可以使用任何基于角色的开源访问控制系统? 问题答案: 布兰登·萨维奇(Brandon Savage)在他的PHP软件包“ ApplicationACL ” 上做了一个演示,该演示可能会或可能不会完成基于角色的访问。PHPGACL可能也能正常工作,但是我不能肯定地告诉您。 但是,我可以告诉您的是Zend Framework 的Zend_ACL组件将执行基于角色的设置(但是您必须子类化

  • 角色定义 [role_definition] 是RBAC角色继承关系的定义。 Casbin 支持 RBAC 系统的多个实例, 例如, 用户可以具有角色及其继承关系, 资源也可以具有角色及其继承关系。 这两个 RBAC 系统不会互相干扰。 此部分是可选的。 如果在模型中不使用 RBAC 角色, 则省略此部分。 [role_definition] g = _, _ g2 = _, _ 上述角色定义表

  • 以下内容是 xingzhou 对 kubernetes 官方文档的翻译,原文地址 https://k8smeetup.github.io/docs/admin/authorization/rbac/ 基于角色的访问控制(Role-Based Access Control, 即”RBAC”)使用”rbac.authorization.k8s.io” API Group实现授权决策,允许管理员通过Ku

  • 一个更友好的域内基于角色的访问控制的API。 这个API是Management API的子集。 RBAC用户可以使用这个API来简化代码。 参考 全局变量 e 是 Enforcer 实例。GoNode.jsPHP.NETRust e, err := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") const

  • 基本上,我已经花了几天的时间试图找出如何在我为朋友开发的网站上添加简单的管理员和成员角色。(我正在使用ASP.NET Framework 5.2.7.0)。我知道Microsoft内置了一个很好的基于角色的访问功能,它允许您在控制器的顶部放置类似于的内容;但是我根本无法让它工作,我找到的大多数资源都是用于ASP.NET Core的。 我试着修改我的网页。配置文件以启用基于角色的访问(并希望将角色等

  • 我对Spring靴还不熟悉。我需要在spring boot中实现基于角色的授权。我有不同的角色,多个用户将映射到每个角色。每当调用api时,我都会设置不同的访问权限(读取、添加、删除、编辑),需要检查访问权限并允许权限。我计划使用拦截器调用具有查询的方法,以从DB获取访问权限,并拒绝或访问api。有没有其他更好的方法我可以用同样的方法?