简体   繁体   中英

Facebook login with spring-security

I am trying to add facebook login to my Spring project. I am able to add the user to the database but I still need to authenticate him with my Spring security. Does anybody know how to do this or do you know a good tutorial?

FBLogin.js

$(document).ready(function () {
function postFunction(type, username, typeUsername, firstname, lastname, id){
    $.post(location.protocol + '//' + location.host + '/ProjectTeamF-     1.0/user/addSocial.html', {
        type:type,
        userName:username,
        typeUserName:typeUsername,
        firstName:firstname,
        lastName:lastname,
        id:id
    }, function (data) {

        window.location = "http://localhost:8080/ProjectTeamF-1.0/" + data;
    });
}

FB.Event.subscribe('auth.login', function (response) {
    login();
});

FB.Event.subscribe('auth.logout', function (response) {
    logout();
});

function login() {
    var fbFirstName;
    var fbLastName;
    var fbId;
    var fbUserName;
    var fbScreenName;

    FB.api('/me', function (response) {
        if (response.username == null) {
            fbScreenName = response.first_name + response.last_name;
            fbUserName = response.first_name + response.last_name;
        } else {
            fbScreenName = response.username;
            fbUserName = response.username;
        }
        fbFirstName = response.first_name;
        fbLastName = response.last_name;
        fbId = response.id;
        postFunction('Facebook',fbUserName, fbScreenName, fbFirstName, fbLastName, fbId);
    });


}

function logout() {

}

})

AddSocialUser method in my controller

@RequestMapping(value = "/user/addSocial", method = RequestMethod.POST)
public
@ResponseBody
String addSocialContact(HttpServletRequest request, HttpSession session) {
    User user = new User();

    if (userService.findUser(request.getParameter("userName")) == null) {
        user.setUsername(request.getParameter("userName"));
        user.setPassword(request.getParameter("id"));
        user.setFirstName((request.getParameter("firstName")));
        user.setLastName(request.getParameter("lastName"));

        userService.addUser(user);


    } else {
        user = userService.findUser(request.getParameter("userName"));
    }

   List<GrantedAuthority> gaList = new ArrayList<GrantedAuthority>();
    gaList.add(new GrantedAuthorityImpl("ROLE_USER"));
    org.springframework.security.core.userdetails.User usersec = new  org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, gaList);
    Authentication auth = new UsernamePasswordAuthenticationToken(usersec, user.getPassword(), gaList);
    org.springframework.security.core.context.SecurityContext sc = new SecurityContextImpl();
    sc.setAuthentication(auth);
    org.springframework.security.core.context.SecurityContextHolder.setContext(sc);

    return "/ProjectTeamF-1.0/j_spring_security_check";
}

Edit: This is our spring-security.xml

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

<http auto-config="true">
    <intercept-url pattern="/user/admincp-*.html" access="ROLE_USER" />
    <intercept-url pattern="/TripParticipants/*.html" access="ROLE_USER" />
    <intercept-url pattern="/editUserequipment/*.html" access="ROLE_USER" />
    <intercept-url pattern="/TripCategorie/*.html" access="ROLE_USER" />
    <intercept-url pattern="/StopPlaats/*.html" access="ROLE_USER" />
    <intercept-url pattern="/trip/join/*.html" access="ROLE_USER" />
    <intercept-url pattern="/trip/addTrip.html" access="ROLE_USER" />
    <form-login login-page="/general/login.html" default-target-url="/general/index.html"
                authentication-failure-url="/user/loginfailed.html" />
    <logout logout-success-url="/" />
</http>

<authentication-manager >
       <authentication-provider >
           <password-encoder hash="plaintext"/>
        <jdbc-user-service data-source-ref="dataSource"

          users-by-username-query="
          select username,password ,true
          from t_user where username=?"
          authorities-by-username-query="
          select username, 'ROLE_USER' from t_user where username=? "/>
    </authentication-provider>
</authentication-manager>

If you want only authenticate your user then just do

org.springframework.security.core.userdetails.User user = new User(login, password, true, true, true, true, new ArrayList<GrantedAuthority>());
Authentication auth = new UsernamePasswordAuthenticationToken(user, password, new ArrayList<GrantedAuthority>());
org.springframework.security.core.context.SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(auth);
org.springframework.security.core.context.SecurityContextHolder.setContext(sc);

and make sure that current and all subsequent http requests are covered by spring security filters. If all user info come from Facebook then DB user is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM