0
Follow
17
View

Spring-Security with OAuth2Login & CustomAuthenticationProvider

luyeku55 注册会员
2022-11-20 14:01

现在我自己解决了我的问题。

问题是,

@Autowired
private KeycloakAuthenticationSuccessHandler successHandler;

http.oauth2Login().successHandler(successHandler);
的配置提供了它自己的
@Component
public class KeycloakAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
    @Value("${logging.groupId}")
    private String location;

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        var persistedAuth = (OAuth2AuthenticationToken) authentication;
        var user = new DefaultOAuth2User(persistedAuth.getAuthorities(), persistedAuth.getPrincipal().getAttributes(), "name");

        /*
         * Sets new OAuth2AuthenticationToken with mapped authorities
         */
        SecurityContextHolder.getContext()
                .setAuthentication(new OAuth2AuthenticationToken(user, mapAuthorities(persistedAuth.getPrincipal().getAttributes()), persistedAuth
                        .getAuthorizedClientRegistrationId()));

        /*
         * Redirecting to the index page of website
         */
        var redirectUri = requestCache.getRequest(request, response).getRedirectUrl();
        redirectStrategy.sendRedirect(request, response, redirectUri);
    }

    @SuppressWarnings("unchecked")
    private Collectionextends GrantedAuthority> mapAuthorities(Map<String, Object> attributes)
    {
        var resourceRoles = new ArrayList<>();
        var resourceAccess = (Map<String, List<String>>) attributes.get("resource_access");
        if (resourceAccess.containsKey(location))
        {
            resourceRoles.addAll(((Map<String, List<String>>) resourceAccess.get(location)).get("roles"));
        }
        return resourceRoles.isEmpty() ? emptySet() : resourceRoles.stream().map(r -> new SimpleGrantedAuthority(valueOf(r))).collect(toSet());
    }
}
,这没有被http.oauth2Login()覆盖

我的解决方案是添加一个AuthenticationProviderAuthenticationManagerBuilder

它有重做和设置由auto-config创建的现有身份验证的任务

下面是我的代码:

@Autowired
private KeycloakAuthenticationSuccessHandler successHandler;

http.oauth2Login().successHandler(successHandler);

and my successHandler:

@Component
public class KeycloakAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
    @Value("${logging.groupId}")
    private String location;

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        var persistedAuth = (OAuth2AuthenticationToken) authentication;
        var user = new DefaultOAuth2User(persistedAuth.getAuthorities(), persistedAuth.getPrincipal().getAttributes(), "name");

        /*
         * Sets new OAuth2AuthenticationToken with mapped authorities
         */
        SecurityContextHolder.getContext()
                .setAuthentication(new OAuth2AuthenticationToken(user, mapAuthorities(persistedAuth.getPrincipal().getAttributes()), persistedAuth
                        .getAuthorizedClientRegistrationId()));

        /*
         * Redirecting to the index page of website
         */
        var redirectUri = requestCache.getRequest(request, response).getRedirectUrl();
        redirectStrategy.sendRedirect(request, response, redirectUri);
    }

    @SuppressWarnings("unchecked")
    private Collectionextends GrantedAuthority> mapAuthorities(Map<String, Object> attributes)
    {
        var resourceRoles = new ArrayList<>();
        var resourceAccess = (Map<String, List<String>>) attributes.get("resource_access");
        if (resourceAccess.containsKey(location))
        {
            resourceRoles.addAll(((Map<String, List<String>>) resourceAccess.get(location)).get("roles"));
        }
        return resourceRoles.isEmpty() ? emptySet() : resourceRoles.stream().map(r -> new SimpleGrantedAuthority(valueOf(r))).collect(toSet());
    }
}

Btw:感谢Marcus,通过提示和调试器,我找到了解决方案!