Spring oauth2login oidc根据用户信息授予访问权限

e0bqpujr  于 2022-12-26  发布在  Spring
关注(0)|答案(2)|浏览(141)

我正在尝试根据本教程设置身份验证:特别是第7部分。
我已经填充了属性并配置了如下过滤器链:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
      .authorizeRequests(authorizeRequests -> authorizeRequests
        .anyRequest().authenticated())
      .oauth2Login(oauthLogin -> oauthLogin.permitAll());
    return http.build();
}

这是可行的,但现在所有来自oidc的用户都可以连接登录。我想根据userinfo限制访问。例如,添加一些逻辑,如:

if(principal.getName() == "admin") {
//allow authentication
}

有什么办法吗?
我试着创建客户提供商,如这里建议:Add Custom AuthenticationProvider to Spring Boot + oauth +oidc
但是它失败了,并且异常地说主体为空。

2eafrhcq

2eafrhcq1#

您可以在身份验证成功时检索用户信息,并基于用户信息执行进一步检查。以下是清除安全上下文并重定向请求的示例代码:

@Component
public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        if(authentication instanceof OAuth2AuthenticationToken) {
            OAuth2AuthenticationToken token =  (OAuth2AuthenticationToken) authentication;
            // OidcUser or OAuth2User
            // OidcUser user = (OidcUser) token.getPrincipal();
            OAuth2User user = token.getPrincipal();
            if(!user.getName().equals("admin")) {
                SecurityContextHolder.getContext().setAuthentication(null);
                SecurityContextHolder.clearContext();
                redirectStrategy.sendRedirect(request, response, "login or error page url");
            }
        }
    }
}
gzszwxb4

gzszwxb42#

是否确实要保护的内容不包括@RestController或带有@ResponseBody的@Controller?如果是,则表示您引用的客户端配置不适用:您需要为此端点设置资源服务器配置。
我编写a tutorial是为了编写带有两个过滤器链的应用程序:一个用于资源服务器,另一个用于客户机端点。
上面链接的complete set of tutorials解释了如何在资源服务器上实现高级访问控制,由于resource-server_with_ui中配置了userAuthoritiesMapper,您可以在客户端控制器方法上编写基于角色的安全表达式,就像我在资源服务器方法上所做的那样。

相关问题