我正在使用:
用户可以登录我的web应用程序
(A)或使用Facebook登录(在javascript中实现)或
(B)通过普通用户名/密码表单。
如果(B),我用字段填写一份表格:
j_username
j_password
to /j_spring_security_check (Spring Security)这个很好用。
但如果是(A),在用户通过FB登录(前端)之后,
要让Security为用户创建会话,我需要做什么?
我只有facebook用户的电子邮件在这一点上,服务器是不知道这个登录在前端。
发布于 2016-05-02 07:51:56
在使用Face成功登录后,您应该向后端API发出AJAX请求,并为用户输入关于Face身份验证的数据库条目。
1)您需要从Security实现UserDetailsService
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String userEmail) throws UsernameNotFoundException {
// check for Facebook authentication(DB Entry)
// fetch user details and roles from db using e-mail
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roles);
UserDetails usd = new User(userId, userId, grantedAuths);
return usd;
}
}2)实现自定义身份验证提供程序。
@Component("customAuthenticationProvider")
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userId = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails userFromDB = customUserDetailsService.loadUserByUsername(userId);
if (userFromDB != null) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
for (GrantedAuthority auth : userFromDB.getAuthorities()) {
grantedAuths.add(auth);
}
if (grantedAuths.size() != 0) {
System.out.println("user:" + userId + " got auth from custom auth provider");
return new UsernamePasswordAuthenticationToken(userFromDB, password, grantedAuths);
} else {
throw new DisabledException("No roles assigned");
}
}
throw new DisabledException("User or password incorrect");
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}3)登录控制器
@Controller
public class LoginController {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@RequestMapping(value = "/login", )
public ResponseEntity<Object> fbLogin(@RequestParam String userEmail, HttpServletRequest request) {
UserDetails userDetails=customUserDetailsService.loadUserByUsername(userid);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, userid);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = this.customAuthenticationProvider.authenticate(token);
}
}4) Spring安全控制
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
}https://stackoverflow.com/questions/26173920
复制相似问题