Quantcast
Channel: Spring Community Forums - Social
Viewing all articles
Browse latest Browse all 145

spring security 3 + facebook authentication

$
0
0
Hi, I'm trying to implement Facebook with my Spring Security app. I can get one acces token valid and get the user information but i can't active the Spring to make the Facebook Login work

Here is my method for facebook authentication:

Code:

public void autenticarSpringComFacebook() {

                try {
                        connectionFactory = new FacebookConnectionFactory(Paginas.APP_ID,
                                        Paginas.APP_SECRET);
                        OAuth2Operations oauthOperations = connectionFactory
                                        .getOAuthOperations();
                        OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
                        oAuth2Parameters
                                        .setScope("user_about_me,user_birthday,user_likes,user_status,publish_stream, email");
                        oAuth2Parameters.add("display", "popup");
                        oAuth2Parameters
                                        .setRedirectUri("http://localhost:8080/Pegadas/index.ifpr");
                        String authorizeUrl = oauthOperations.buildAuthorizeUrl(
                                        GrantType.AUTHORIZATION_CODE, oAuth2Parameters);
                        FacesUtils.getExternalContext().redirect(authorizeUrl);

                } catch (Exception ex) {
                        System.out.println(ex.getMessage());
                }

        }

        @SuppressWarnings("finally")
        public String processLoginFacebook() throws IOException, ServletException {
                if (i == 0) {
                        try {

                                Map<String, String> paramMap = FacesContext
                                                .getCurrentInstance().getExternalContext()
                                                .getRequestParameterMap();
                                String code = paramMap.get("code");

                                if (code != null && !code.isEmpty()) {

                                        FacebookConnectionFactory connFactory = new FacebookConnectionFactory(
                                                        Paginas.APP_ID, Paginas.APP_SECRET);
                                        String serverPath = FacesUtils.getApplicationURI();
                                        System.out.println("SERVERPATH: " + serverPath);

                                        AccessGrant accessGrant = connFactory.getOAuthOperations()
                                                        .exchangeForAccess(code, serverPath, null);
                                        System.out.println("ACCESS TOKEN: "
                                                        + accessGrant.getAccessToken());

                                        try {
                                                JSONObject resp = new JSONObject(
                                                                IOUtil.urlToString(new URL(
                                                                                "https://graph.facebook.com/me?access_token="
                                                                                                + accessGrant.getAccessToken())));
                                                String email = resp.getString("email");

                                                try {
                                                        facebook = new FacebookTemplate(
                                                                        accessGrant.getAccessToken());

                                                        if (facebook.isAuthorized()) {

                                                                FacesContext ctx = FacesContext
                                                                                .getCurrentInstance();
                                                                ctx.getExternalContext()
                                                                                .dispatch(
                                                                                                "http://localhost:8080/Pegadas/j_spring_security_check");
                                                                try {

                                                                } catch (Exception ex) {
                                                                        ex.printStackTrace();
                                                                }
                                                        }

                                                } catch (Exception e) {
                                                        e.printStackTrace();
                                                }
                                                if (usuarioDao.findByEmail(email) != null) {
                                                        usuario = usuarioDao.findByEmail(email);
                                                }

                                                else {
                                                        criaNovoUsuarioFace(accessGrant, resp);
                                                }
                                        } catch (Exception ev) {
                                                ev.printStackTrace();
                                        }
                                }

                        } finally {
                                return "index";
                        }
                }
                return "index";
        }

And here is my applicationContext:

Code:

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:oauth="http://www.springframework.org/schema/security/oauth"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">

        <http auto-config="false" entry-point-ref="authenticationEntryPoint">
                <intercept-url pattern="/animais/animais**" access="ROLE_ADMIN, ROLE_MOD" />
                <intercept-url pattern="/necessidades/necessidades**"
                        access="ROLE_ADMIN, ROLE_MOD" />
                <intercept-url pattern="/usuarios/usuarios**" access="ROLE_ADMIN, ROLE_MOD" />
                <intercept-url pattern="/publicacoes/publicacoes**"
                        access="ROLE_ADMIN, ROLE_MOD" />
                <intercept-url pattern="/eventos/eventos**" access="ROLE_ADMIN, ROLE_MOD" />
                <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
                <intercept-url pattern="/animais/novoAnimal**" access="IS_AUTHENTICATED_FULLY" />

                <custom-filter before="FORM_LOGIN_FILTER" ref="facebookAuthenticationFilter" />
                <logout invalidate-session="true" logout-success-url="/index.ifpr" />


                <form-login login-page="/login.xhtml" default-target-url="/index.ifpr"
                        authentication-failure-url="/index.ifpr?erro=true" />

        </http>


        <beans:bean id="dataSource"
                class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <beans:property name="url" value="jdbc:mysql://localhost:3306/ifpr" />
                <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
                <beans:property name="username" value="root" />
                <beans:property name="password" value="**" />
        </beans:bean>

        <authentication-manager alias="authenticationManager">
                <authentication-provider>
                        <password-encoder hash="md5" />
                        <jdbc-user-service data-source-ref="dataSource"
                                users-by-username-query="SELECT username, password, 'true' as enable FROM tbUsuarios WHERE username=?"
                                authorities-by-username-query="SELECT username, authority FROM tbUsuarios WHERE username=?" />
                </authentication-provider>
                <authentication-provider ref="authenticationProviderFacebook">
                </authentication-provider>

        </authentication-manager>





        <!-- Spring com facebook -->

        <beans:bean id="authenticationFilter"
                class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
                p:authenticationManager-ref="customAuthenticationManager"
                p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
                p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler"
                p:postOnly="true" />

        <beans:bean id="customAuthenticationManager" class="usuario.filtros.CustomAuthenticationManager" />
        <beans:bean id="customAuthenticationFailureHandler"
                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
                p:defaultFailureUrl="/app/login.xhtml?erro=true" />

        <beans:bean id="customAuthenticationSuccessHandler"
                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler"
                p:defaultTargetUrl="/Pegadas/index.ifpr" />

        <beans:bean id="authenticationEntryPoint"
                class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
                p:loginFormUrl="/Pegadas/login.xhtml" />

        <!-- -->


        <beans:bean id="authenticationProviderFacebook"
                class="org.springframework.security.facebook.FacebookAuthenticationProvider">
                <beans:property name="roles" value="ROLE_USER, ROLE_MOD, ROLE_ADMIN" />
        </beans:bean>

        <beans:bean id="authenticaionEntryPoint"
                class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
                <beans:property name="loginFormUrl" value="/Pegadas/login.xhtml" />
        </beans:bean>

        <beans:bean id="facebookAuthenticationFilter" name="facebookAuthenticationFilter"
                class="org.springframework.security.facebook.FacebookAuthenticationFilter">
                <beans:property name="authenticationManager" ref="authenticationManager" />
                <beans:property name="authenticationSuccessHandler">
                        <beans:bean
                                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
                                <beans:property name="defaultTargetUrl" value="/Pegadas/index.ifpr" />
                                <beans:property name="alwaysUseDefaultTargetUrl"
                                        value="true" />
                        </beans:bean>
                </beans:property>
                <beans:property name="authenticationFailureHandler">
                        <beans:bean
                                class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                                <beans:property name="defaultFailureUrl" value="/Pegadas/index.ifpr" />
                        </beans:bean>
                </beans:property>
        </beans:bean>

        <beans:bean id="facebookHelper"
                class="org.springframework.security.facebook.FacebookHelper">
                <beans:property name="apiKey" value="" />
                <beans:property name="secret" value="" />
        </beans:bean>

</beans:beans>

But when I dispatch the j_spring_security_check it returns the following error:

Code:

Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: Authentication method not supported: GET
22:35:42,316 INFO  [stdout] (http--127.0.0.1-8080-1) 2013-08-22 22:35:42,316 DEBUG web.authentication.UsernamePasswordAuthenticationFilter  -> Updated SecurityContextHolder to contain null Authentication
22:35:42,316 INFO  [stdout] (http--127.0.0.1-8080-1) 2013-08-22 22:35:42,316 DEBUG web.authentication.UsernamePasswordAuthenticationFilter  -> Delegating to authentication failure handlerorg.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@509dd43b
22:35:42,316 INFO  [stdout] (http--127.0.0.1-8080-1) 2013-08-22 22:35:42,316 DEBUG web.authentication.SimpleUrlAuthenticationFailureHandler  -> Redirecting to /index.ifpr?erro=true


Viewing all articles
Browse latest Browse all 145

Latest Images

Trending Articles



Latest Images