将Spring Security与Facebook登录集成 [英] Integrate Spring Security with Facebook Login
问题描述
我创建控制器使用Facebook登录:
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(/ login /)
public class LoginController {
String fb_app_id =my_client_id;
String redirect_url =localhost:8888;
String state =public_profile,email,user_friends;
String key =my_client_secret;
@RequestMapping(/ facebook)
public String login(ModelMap model){
String url =https://www.facebook.com/对话/ OAuth的/?
+client_id =+ fb_app_id
+& redirect_uri =+ redirect_url
+& scope = email,publish_stream,user_about_me,friends_about_me
+& state =+ key
+& display = page
+& response_type = code;
returnredirect:+ url;
}
}
我认为因为当我尝试连接时,我可以用Javascript显示我的名字:
function testAPI(){
console.log('Welcome!Fetching your information ....');
FB.api('/ me',function(response){
console.log('Good to see you,'+ response.name +'。');
document.getElementById ('status')。innerHTML ='很高兴见到你'+
response.name;
});
}
但是我仍然会混淆如何将其与Spring Security集成。如果有人有任何例子,我会欣赏...
这是我的spring-security.xml
<?xml version =1.0encoding =UTF-8?>
< beans:beans xmlns =http://www.springframework.org/schema/security
xmlns:beans =http://www.springframework.org/schema/beansxmlns :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.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/安全/弹簧安全3.1.xsd>
< http pattern =/ common / *security =none/>
< http auto-config =true>
< intercept-url pattern =/ maintenance / *access =ROLE_USER/>
< intercept-url pattern =/ _ ah / *access =ROLE_USER/>
< intercept-url pattern =/ predict / *access =ROLE_USER/>
< form-login login-page ='/'default-target-url ='/ predict / list'
login-processing-url =/ login_checkauthentication-failure- url =/ index?login_error = 2
always-use-default-target =true/>
< logout logout-url =/ logoutlogout-success-url =/ index/>
<! - < custom-filter ref =socialAuthenticationFilterbefore =PRE_AUTH_FILTER/> - >
<! - < custom-filter before =FORM_LOGIN_FILTER
ref =facebookAuthenticationFilter/> - >
< / http>
< authentication-manager>
< authentication-provider ref =gaeAuthenticationProvider/>
<! - < authentication-provider ref =authenticationProviderFacebook>
< / authentication-provider> - >
< / authentication-manager>
< beans:bean id =gaeAuthenticationProvider
class =com.games.predictor.security.AuthenticationProvider/>
< / beans:beans>
我有自己的类来验证用户数据与JPA ...
package com.games.predictor.security;
import java.util.List;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import com.games.predictor.UserDAO;
public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
{
// private SecurityDao securityDao;
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException
{
final String password = authentication.getCredentials ()的ToString();
System.out.println(username +====+ password);
//用于使用数据库验证用户的行
boolean isValidUser = UserDAO.INSTANCE.isValidUser(username,password);
if(isValidUser)
{
final List< SimpleGrantedAuthority> authority = UserDAO.INSTANCE.getAuthoritiesByUser(username);
//用户u =新用户(用户名,密码);
返回新用户(username,password,true,true,true,true,authority);
}
else
{
authentication.setAuthenticated(false);
抛出新的BadCredentialsException(用户名/密码不匹配
+ authentication.getPrincipal());
}
}
@Override
protected void additionalAuthenticationChecks(UserDetails arg0,
UsernamePasswordAuthenticationToken arg1)
throws AuthenticationException {
// TODO自动生成的方法存根
}
}
$ b $我最近几天做了一些研究,但仍然停滞不前。
我的项目堆栈:Java,Spring MVC,Spring Security,Google App Engine,Google Data Store,JPA。 (Spring Social Core and Spring Social Facebook Added)
我不认为你应该手动处理Facebook。您可以使用一个非常简单的图书馆: https://github.com/pac4j/spring-security-pac4j 为OAuth(Facebook,Twitter,Google ...),CAS,SAML,OpenID(Connect)和GAE进行身份验证。请参阅演示: https://github.com/pac4j/spring-security-pac4j-demo
I use Spring MVC and Spring Security for my project.. This using my own user data for authentication. But now i trying to integrate with Facebook. i have created app on Facebook means i got Client ID and client Secret.. I also read some questions in SO and some documents but still stuck...
i create controller to Login with Facebook :
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/login/")
public class LoginController {
String fb_app_id="my_client_id";
String redirect_url="localhost:8888";
String state="public_profile,email,user_friends";
String key="my_client_secret";
@RequestMapping("/facebook")
public String login( ModelMap model) {
String url="https://www.facebook.com/dialog/oauth/?"
+ "client_id=" + fb_app_id
+ "&redirect_uri=" + redirect_url
+ "&scope=email,publish_stream,user_about_me,friends_about_me"
+ "&state=" + key
+ "&display=page"
+ "&response_type=code";
return "redirect:"+url;
}
}
i think it works because when i try to connect, i can show my name with Javascript below:
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
document.getElementById('status').innerHTML = 'Good to see you, ' +
response.name;
});
}
But i still confuse how to integrate it with Spring Security. If anyone have any examples i will appreciate...
This is my spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/common/*" security="none" />
<http auto-config="true">
<intercept-url pattern="/maintenance/*" access="ROLE_USER" />
<intercept-url pattern="/_ah/*" access="ROLE_USER" />
<intercept-url pattern="/predict/*" access="ROLE_USER" />
<form-login login-page='/' default-target-url='/predict/list'
login-processing-url="/login_check" authentication-failure-url="/index?login_error=2"
always-use-default-target="true" />
<logout logout-url="/logout" logout-success-url="/index" />
<!-- <custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" /> -->
<!-- <custom-filter before="FORM_LOGIN_FILTER"
ref="facebookAuthenticationFilter" /> -->
</http>
<authentication-manager>
<authentication-provider ref="gaeAuthenticationProvider" />
<!-- <authentication-provider ref="authenticationProviderFacebook">
</authentication-provider>-->
</authentication-manager>
<beans:bean id="gaeAuthenticationProvider"
class="com.games.predictor.security.AuthenticationProvider" />
</beans:beans>
i have my own class to Authenticate to userdata with JPA...
package com.games.predictor.security;
import java.util.List;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import com.games.predictor.UserDAO;
public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
{
//private SecurityDao securityDao;
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException
{
final String password = authentication.getCredentials().toString();
System.out.println(username+"===="+password);
//This line for validating user with database
boolean isValidUser = UserDAO.INSTANCE.isValidUser(username, password);
if (isValidUser)
{
final List<SimpleGrantedAuthority> authorities = UserDAO.INSTANCE.getAuthoritiesByUser(username);
//User u=new User(username,password,);
return new User(username, password, true, true, true, true, authorities);
}
else
{
authentication.setAuthenticated(false);
throw new BadCredentialsException("Username/Password does not match for "
+ authentication.getPrincipal());
}
}
@Override
protected void additionalAuthenticationChecks(UserDetails arg0,
UsernamePasswordAuthenticationToken arg1)
throws AuthenticationException {
// TODO Auto-generated method stub
}
}
I did some research in last few days but still stuck.
My Project Stack : Java, Spring MVC, Spring Security, Google App Engine, Google Data Store, JPA. (Spring Social Core and Spring Social Facebook Added)
I don't think you should deal with Facebook manually. You can a really easy library: https://github.com/pac4j/spring-security-pac4j to authenticate for OAuth (Facebook, Twitter, Google...), CAS, SAML, OpenID (Connect) and GAE. See the demo: https://github.com/pac4j/spring-security-pac4j-demo
这篇关于将Spring Security与Facebook登录集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!