Add custom UserDetailsService to Spring Security OAuth2 app

后端 未结 4 1980
囚心锁ツ
囚心锁ツ 2020-12-16 16:57

How do I add the custom UserDetailsService below to this Spring OAuth2 sample?

The default user with default password is def

4条回答
  •  孤街浪徒
    2020-12-16 17:25

    My requirement was to get a database object off the back of the oauth2 email attribute. I found this question as I assumed that I need to create a custom user details service. Actually I need to implment the OidcUser interface and hook into that process.

    Initially I thought it was the OAuth2UserService, but I've set up my AWS Cognito authentication provider so that it's open id connect..

    //inside WebSecurityConfigurerAdapter
    
    http
    .oauth2Login()
    .userInfoEndpoint()
    .oidcUserService(new CustomOidcUserServiceImpl());
    
    ...
    
    public class CustomOidcUserServiceImpl implements OAuth2UserService {
    
        private OidcUserService oidcUserService = new OidcUserService();
    
        @Override
        public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
            OidcUser oidcUser = oidcUserService.loadUser(userRequest);
            return new CustomUserPrincipal(oidcUser);
        }
    }
    
    ...
    
    public class CustomUserPrincipal implements OidcUser {
    
        private OidcUser oidcUser;
    
        //forward all calls onto the included oidcUser
    }
    

    The custom service is where any bespoke logic can go. I plan on implementing UserDetails interface on my CustomUserPrincipal so that I can have different authentication mechanisms for live and test to facilitate automated ui testing.

提交回复
热议问题