Integrate Spring Security OAuth2 and Spring Social

前端 未结 4 1191
终归单人心
终归单人心 2020-12-07 21:07

I\'m working with a Spring Boot + Spring Security OAuth2 application that I believe was inspired by examples from Dave Syer. The application is configured to be an OAuth2 au

相关标签:
4条回答
  • 2020-12-07 21:13

    I was starting with the good answer of above (https://stackoverflow.com/a/33963286/3351474) however with my version of Spring Security (4.2.8.RELEASE) this fails. The reason is that in org.springframework.security.access.intercept.AbstractSecurityInterceptor#authenticateIfRequired the PreAuthenticatedAuthenticationToken of the answer is not authenticated. Some GrantedAuthorities have to be passed. In addition sharing the token in an URL parameter is not good, it should always be hidden in an HTTPs payload or header. Instead a HTML template is loaded and the token value is inserted into a ${token} placeholder field.

    Here the revised version:

    NOTE: The used UserDetails here is implementing org.springframework.security.core.userdetails.UserDetails

    @Component
    public class SocialAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    
        @Autowired
        private OAuth2TokenStore tokenStore;
    
        @Qualifier("tokenServices")
        @Autowired
        private AuthorizationServerTokenServices authTokenServices;
    
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            IClient user = ((SocialUserDetails) authentication.getPrincipal()).getUser();
            // registration is not finished, forward the user, a marker interface 
            // IRegistration is used here, remove this if there no two step approach to 
            // create a user from a social network
            if (user instanceof IRegistration) {
                response.sendRedirect(subscriberRegistrationUrl + "/" + user.getId());
            }
            OAuth2AccessToken token = loginUser(user);
            // load a HTML template from the class path and replace the token placeholder within, the HTML should contain a redirect to the actual page, but must store the token in a safe place, e.g. for preventing CSRF in the `sessionStorage` JavaScript storage.
            String html = IOUtils.toString(getClass().getResourceAsStream("/html/socialLoginRedirect.html"));
            html = html.replace("${token}", token.getValue());
            response.getOutputStream().write(html.getBytes(StandardCharsets.UTF_8));
        }
    
        private OAuth2Authentication convertAuthentication(Authentication authentication) {
            OAuth2Request request = new OAuth2Request(null, authentication.getName(),
                    authentication.getAuthorities(), true, null,
                    null, null, null, null);
            // note here the passing of the authentication.getAuthorities()
            return new OAuth2Authentication(request,
                    new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(), "N/A",  authentication.getAuthorities())
            );
        }
    
        /**
         * Logs in a user.
         */
        public OAuth2AccessToken loginUser(IClient user) {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            UserDetails userDetails = new UserDetails(user);
            Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "N/A", userDetails.getAuthorities());
            securityContext.setAuthentication(authentication);
            OAuth2Authentication oAuth2Authentication = convertAuthentication(authentication);
            // delete the token because the client id in the DB is calculated as hash of the username and client id (here also also identical to username), this would be identical to the
            // to an existing user. This existing one can come from a user registration or a previous user with the same name.
            // If a new entity with a different ID is used the stored token hash would differ and the the wrong token would be retrieved 
            tokenStore.deleteTokensForUserId(user.getUsername());
            OAuth2AccessToken oAuth2AccessToken = authTokenServices.createAccessToken(oAuth2Authentication);
            // the DB id of the created user is returned as additional data, can be 
            // removed if not needed
            ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(new HashMap<>());
            oAuth2AccessToken.getAdditionalInformation().put("userId", user.getId());
            return oAuth2AccessToken;
        }
    
    }
    

    Example socialLoginRedirect.html:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Example App</title>
        <meta http-equiv="Refresh" content="0; url=/index.html#/home"/>
    </head>
    <script>
         window.sessionStorage.setItem('access_token', '${token}');
    </script>
    <body>
    <p>Please follow <a href="/index.html#/home">this link</a>.</p>
    </body>
    </html>
    

    The configuration wiring in a WebSecurityConfigurerAdapter:

    @Configuration
    @EnableWebSecurity
    @EnableWebMvc
    @Import(WebServiceConfig.class)
    public class AuthenticationConfig extends WebSecurityConfigurerAdapter {
    
        @Value("${registrationUrl}")
        private String registrationUrl;
    
        @Autowired
        private SocialAuthenticationSuccessHandler socialAuthenticationSuccessHandler;
    
        @Value("${loginUrl}")
        private String loginUrl;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            List<String> permitAllUrls = new ArrayList<>();
            // permit social log in
            permitAllUrls.add("/auth/**");
            http.authorizeRequests().antMatchers(permitAllUrls.toArray(new String[0])).permitAll();
    
            SpringSocialConfigurer springSocialConfigurer = new SpringSocialConfigurer();
            springSocialConfigurer.signupUrl(registrationUrl);
            springSocialConfigurer.postFailureUrl(loginUrl);
            springSocialConfigurer
                    .addObjectPostProcessor(new ObjectPostProcessor<SocialAuthenticationFilter>() {
                        @SuppressWarnings("unchecked")
                        public SocialAuthenticationFilter postProcess(SocialAuthenticationFilter filter){
                            filter.setAuthenticationSuccessHandler(socialAuthenticationSuccessHandler);
                            return filter;
                        }
                    });
            http.apply(springSocialConfigurer);
    
            http.logout().disable().csrf().disable();
    
            http.requiresChannel().anyRequest().requiresSecure();
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    
    0 讨论(0)
  • 2020-12-07 21:20

    I implemented spring oauth2 to secure my rest services and additionally add social login and implicit signup for first time login . for user user you can generate the token using username and password only problem with generate the token for social user . for that you have to implement the Filter that will intercept your /oauth/token request before processing . here if you want to generate the the token for social user pass the username and facebook token , here you can use facebook token as password and generate the token for facebook user also . if facebook token updated then you have to write a db trigger also to update you token in user table .... may be it will help you

    0 讨论(0)
  • 2020-12-07 21:26

    First, I would strongly recommend you to move away from the password grant for such a use case.
    Public clients (JavaScript, installed applications) cannot keep their client secret confidential, that's why they MUST NOT be assigned one : any visitor inspecting your JavaScript code can discover the secret, and thus implement the same authentication page you have, storing your users passwords in the process.

    The implicit grant has been created exactly for what you are doing.
    Using a redirection-based flow has the advantage of leaving the authentication mechanism up to the authorization server, instead of having each of your applications have a piece of it : that's mostly the definition of Single Sign On (SSO).

    With that said, your question is tightly related to this one I just answered : Own Spring OAuth2 server together with 3rdparty OAuth providers

    To sum up the answer :

    In the end, it's about how your authorization server secures the AuthorizationEndpoint : /oauth/authorize. Since your authorization server works, you already have a configuration class extending WebSecurityConfigurerAdapter that handles the security for /oauth/authorize with formLogin. That's where you need to integrate social stuff.

    You simply cannot use a password grant for what you're trying to achieve, you must have your public client redirect to the authorization server. The authorization server will then redirect to the social login as its security mechanism for the /oauth/authorize endpoint.

    0 讨论(0)
  • 2020-12-07 21:28

    I had a similar problem on a JHipster-generated web application. Finally I decided to go with the SocialAuthenticationFilter option from Spring Social (via the SpringSocialConfigurer). After a successful social login, the server automatically generates and returns the "own" access token via redirection to the client app.

    Here's my try:

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter implements EnvironmentAware {
    
        //...
    
        @Inject
        private AuthorizationServerTokenServices authTokenServices;
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
    
            SpringSocialConfigurer socialCfg = new SpringSocialConfigurer();
            socialCfg
                .addObjectPostProcessor(new ObjectPostProcessor<SocialAuthenticationFilter>() {
                    @SuppressWarnings("unchecked")
                    public SocialAuthenticationFilter postProcess(SocialAuthenticationFilter filter){
                        filter.setAuthenticationSuccessHandler(
                                new SocialAuthenticationSuccessHandler(
                                        authTokenServices,
                                        YOUR_APP_CLIENT_ID
                                )
                            );
                        return filter;
                    }
                });
    
            http
                //... lots of other configuration ...
                .apply(socialCfg);
        }        
    }
    

    And the SocialAuthenticationSuccessHandler class:

    public class SocialAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    
        public static final String REDIRECT_PATH_BASE = "/#/login";
        public static final String FIELD_TOKEN = "access_token";
        public static final String FIELD_EXPIRATION_SECS = "expires_in";
    
        private final Logger log = LoggerFactory.getLogger(getClass());
        private final AuthorizationServerTokenServices authTokenServices;
        private final String localClientId;
    
        public SocialAuthenticationSuccessHandler(AuthorizationServerTokenServices authTokenServices, String localClientId){
            this.authTokenServices = authTokenServices;
            this.localClientId = localClientId;
        }
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                HttpServletResponse response, Authentication authentication)
                        throws IOException, ServletException {
            log.debug("Social user authenticated: " + authentication.getPrincipal() + ", generating and sending local auth");
            OAuth2AccessToken oauth2Token = authTokenServices.createAccessToken(convertAuthentication(authentication)); //Automatically checks validity
            String redirectUrl = new StringBuilder(REDIRECT_PATH_BASE)
                .append("?").append(FIELD_TOKEN).append("=")
                .append(encode(oauth2Token.getValue()))
                .append("&").append(FIELD_EXPIRATION_SECS).append("=")
                .append(oauth2Token.getExpiresIn())
                .toString();
            log.debug("Sending redirection to " + redirectUrl);
            response.sendRedirect(redirectUrl);
        }
    
        private OAuth2Authentication convertAuthentication(Authentication authentication) {
            OAuth2Request request = new OAuth2Request(null, localClientId, null, true, null,
                    null, null, null, null);
            return new OAuth2Authentication(request,
                    //Other option: new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "N/A", authorities)
                    new PreAuthenticatedAuthenticationToken(authentication.getPrincipal(), "N/A")
                    );
        }
    
        private String encode(String in){
            String res = in;
            try {
                res = UriUtils.encode(in, GeneralConstants.ENCODING_UTF8);
            } catch(UnsupportedEncodingException e){
                log.error("ERROR: unsupported encoding: " + GeneralConstants.ENCODING_UTF8, e);
            }
            return res;
        }
    }
    

    This way your client app will receive your web app's access token via redirection to /#/login?access_token=my_access_token&expires_in=seconds_to_expiration, as long as you set the corresponding REDIRECT_PATH_BASE in SocialAuthenticationSuccessHandler.

    I hope it helps.

    0 讨论(0)
提交回复
热议问题