2013-02-28 3 views
2

Я пытаюсь добавить логин facebook в свой проект Spring. Я могу добавить пользователя в базу данных, но мне все равно нужно аутентифицировать его с помощью моей безопасности Spring. Кто-нибудь знает, как это сделать, или вы знаете хороший учебник?Facebook login with spring-security

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 в мой контроллер

@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: Это наша весна-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> 

+0

http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html – nav0611

+0

http://static.springsource.org/spring-security/site/docs/3.1.x/reference /springsecurity.html – nav0611

+1

Если вам нужно позвонить Facebook прямо из java (не из JavaScript), посмотрите на [Spring Social] (http://www.springsource.org/spring-social) и [Spring Social Facebook] (http://static.springsource.org/spring-social-facebook/docs/1.0.x/reference/html/) (но он будет более тяжелым, чем ваше текущее решение). –

ответ

4

Если вы хотите только проверку подлинности пользователя, то просто сделать

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); 

и убедитесь, что текущие и все последующие запросы HTTP покрыты фильтрами пружинной безопасности. Если вся информация о пользователе поступает из Facebook, то пользователю БД не нужно.

+0

Как вы это понимаете? Я добавил код к контроллеру, но, похоже, не помогает. Не все пользователи из Facebook. У вас есть возможность сделать свой собственный пользователь или войти в систему с помощью facebook. –

+0

Настройте этот код для ваших нужд. Добавьте пропущенный «ROLE_USER» в каждый список объектов GrantedAuthority. –

+0

Все те же. Я редактировал мой код выше, чтобы вы могли видеть, что я делаю. –