我正在创建一个应用程序,用户可以通过用户名和密码登录,也可以通过带有spring社交的facebook登录。我举了一个例子 this tutorial,但它是为Spring MVC而不是为REST配置的。
Author创建特殊的UserDetailsService并将其分配给身份验证管理器构建器。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
此时我觉得一切都还好。 UserDetailsService具有按用户ID查找用户的方法。
在安全配置类的http配置中,我应该将'form login'更改为http'基本身份验证'如果我想拥有REST应用程序? 如果我改变了这个,我应该为每个请求添加正确的http授权标头吗?或者我可以使用标准登录的令牌身份验证(通过用户名和密码,而不是社交)?基于令牌的身份验证将与Spring社交登录配合(还有令牌)?
@Configuration
@EnableSocial
public class SocialContext implements SocialConfigurer {
@Autowired
private DataSource dataSource;
@Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
cfConfig.addConnectionFactory(new FacebookConnectionFactory(
env.getProperty("facebook.app.id"),
env.getProperty("facebook.app.secret")
));
}
@Override
public UserIdSource getUserIdSource() {
return new AuthenticationNameUserIdSource();
}
@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new JdbcUsersConnectionRepository(
dataSource,
connectionFactoryLocator,
Encryptors.noOpText()
);
}
@Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
return new ConnectController(connectionFactoryLocator, connectionRepository);
}
}
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authenticate")
.failureUrl("/login?error=bad_credentials")
//Configures the logout function
.and()
.logout()
.deleteCookies("JSESSIONID")
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
//Configures url based authorization
.and()
.authorizeRequests()
//Anyone can access the urls
.antMatchers(
"/auth/**",
"/login",
"/signup/**",
"/user/register/**",
"/greeting"
).permitAll()
//The rest of the our application is protected.
.antMatchers("/**").hasRole("USER")
//Adds the SocialAuthenticationFilter to Spring Security's filter chain.
.and()
.apply(new SpringSocialConfigurer())
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
@Bean
public SocialUserDetailsService socialUserDetailsService() {
return new AppSocialUserDetailsService(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return new AppUserDetailsService(userRepository);
}
}