阅读 170

SpringCloud+SpringSecurity+Oauth2实现角色权限四种方案

Springcloud+oauth2+SpringSecurity动态角色权限设置有四种方式

方式一:硬编码

@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
复制代码

方式二:HttpSecurity动态增加

 protected void configure(HttpSecurity http) throws Exception {
        List<Permission> permissions = permissionMapper.findAllPermission();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests
          = http.authorizeRequests();
        permissions.forEach(permission ->
        {
            authorizeRequests.antMatchers(permission.getUrl()).hasAnyAuthority(permission.getPermTag());
        });
        authorizeRequests.
                antMatchers("/login").permitAll().
                antMatchers("/**").
                fullyAuthenticated().
                and().
                formLogin()
                .loginPage("/login").
                and().csrf().disable();
    }
复制代码

方式三:@authService.canAccess

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login/**","/logout/**")
                .permitAll()
                .anyRequest().access("@authService.canAccess(request,authentication)");
}

@Component
public class AuthService {
 
    public boolean canAccess(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if(principal == null){
            return false;
        }
 
        if(authentication instanceof AnonymousAuthenticationToken){
            //check if this uri can be access by anonymous
            //return
        }
 
        Set<String> roles = authentication.getAuthorities()
                .stream()
                .map(e -> e.getAuthority())
                .collect(Collectors.toSet());
        String uri = request.getRequestURI();
        //check this uri can be access by this role
 
        return true;
 
    }
复制代码

建议选择方式三:@authService.canAccess。

方式四: WebFluxSecurity方式实现ReactiveAuthorizationManager

 authorities = authorities.stream().map(i -> i = AuthConstant.AUTHORITY_PREFIX + i).collect(Collectors.toList());
        //认证通过且角色匹配的用户可访问当前路径
        return mono
                .filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                .any(authorities::contains)
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false)); 
复制代码

可参见此文章:

微服务权限终极解决方案,Spring Cloud Gateway + Oauth2 实现统一认证和鉴权!

文章分类
后端
文章标签