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

让Spring Security“JWT登录示例”与角色一起使用

邵俊才
2023-03-14

我正在尝试将之前的一个示例改写为基于Springs new authorization server的简化版本,该示例使用JWT的自定义JWT过滤器构建,该示例如下:https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/jwt/login

该示例使用单个用户设置InMemoryUserDetailsManager→ 用户、密码和“应用程序”权限,所以我假设它是为处理角色/权限而设计的?

如果我使用提供的SecurityFilterChain,一切正常(如示例README中所述)但如果我更改此:

...
http.authorizeHttpRequests((authorize) -> authorize
    .anyRequest().authenticated()
)

进入这个

...
http.authorizeHttpRequests((authorize) -> authorize
    .antMatchers("/").hasRole("app")
    //.antMatchers("/").hasAuthority("app")
    .anyRequest().authenticated()
)

我恢复了403状态,权限按预期添加到JWT中,如下所示:

  ..
  "scope": "app"
}

除了上面给出的antMatcher之外,我的代码与Spring Security示例的克隆完全一样

我错过了什么?

共有2个答案

顾俊哲
2023-03-14

要使用hasRole,您需要具有以ROLE_开头的权限。您可以做的是注册一个转换器,该转换器将从JWT读取角色并将它们添加为Granted授权

public class RolesClaimConverter implements Converter<Jwt, AbstractAuthenticationToken> {

    private final JwtGrantedAuthoritiesConverter wrappedConverter;

    public RolesClaimConverter(JwtGrantedAuthoritiesConverter conv) {
        wrappedConverter = conv;
    }

    @Override
    public AbstractAuthenticationToken convert(@NonNull Jwt jwt) {
        // get authorities from wrapped converter
        var grantedAuthorities = new ArrayList<>(wrappedConverter.convert(jwt));
        // get role authorities
        var roles = (List<String>) jwt.getClaims().get("roles");
        if (roles != null) {
            for (String role : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
            }
        }

        return new JwtAuthenticationToken(jwt, grantedAuthorities);
    }
}

然后在安全配置中注册转换器

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .oauth2ResourceServer(resourceServer -> resourceServer
            .jwt()
            .jwtAuthenticationConverter(
                 new RolesClaimConverter(
                     new JwtGrantedAuthoritiesConverter()
                 )
            )
        )
        // other configuration
    ;
    return http.build();
}

就这样。您现在需要做的就是在创建JWT时传递一个角色列表作为声明,您可以使用。蚂蚁匹配器(“/”)。hasRole(“应用程序”)和预授权(“hasRole(“应用程序”)”)。

景远航
2023-03-14

好的,请阅读规格;-)符合https://docs.spring.io/spring-security/reference/reactive/oauth2/resource-server/jwt.html权限以作用域为前缀_

因此,这部分解决了问题。蚂蚁匹配器(“/”)。hasAuthority(“SCOPE\u app”)

我还没有弄清楚如何使用hasRoles?

 类似资料:
  • 我试图在一个带有spring security和KeyClope的java应用程序中同时使用领域和资源角色。不幸的是,KeyClope只会返回一个或另一个,具体取决于: 您仍然可以通过自定义代码获得这两种方法,但它会弄乱@PreAuthorize或spring boot方法等注释。isUserInRole,这会导致难看的代码。 有没有办法覆盖@PreAuthorize方法或JSON令牌Keyclo

  • 本文向大家介绍Springboot+SpringSecurity+JWT实现用户登录和权限认证示例,包括了Springboot+SpringSecurity+JWT实现用户登录和权限认证示例的使用技巧和注意事项,需要的朋友参考一下 如今,互联网项目对于安全的要求越来越严格,这就是对后端开发提出了更多的要求,目前比较成熟的几种大家比较熟悉的模式,像RBAC 基于角色权限的验证,shiro框架专门用于

  • 用户已作为用户角色登录,我想以员工身份登录而不提交登录表单,但身份验证失败, 请查一下密码,帮帮我 @requestmapping(value=“/home”)public ModelAndView userHomePage(Model Model,HttpServletRequest request,HttpServletResponse response,Principal Principal

  • 本文展示了如何根据不同的用户角色,在登录之后来重定向到不同的页面。 在 method-security项目的基础上,我们构建了一个role-base-login项目。 build.gradle 修改 build.gradle 文件,让我们的role-base-login项目成为一个新的项目。 修改内容也比较简单,修改项目名称及版本即可。 jar { baseName = 'role-bas

  • 登录帧 菜单框架

  • 您好,我正在使用平均堆栈和jwt登录,我想限制一些数据只有userRole'admin'这是我的user.js 这就是我验证jwt令牌的方法 这是我希望使用verifyToken函数仅为'admin'角色限制的数据 我的问题是,我如何访问当前登录的用户信息,并仅使管理员可读的/特殊的