stateless_Spring Stateless State Security第3部分:JWT +社会认证

stateless

我的Stateless Spring Security系列文章的第三部分也是最后一部分是关于将基于JWT令牌的身份验证与spring-social-security混合在一起的。 这篇文章直接建立在它的基础上,并且主要集中在已更改的部分上。 想法是使用基于OAuth 2的“使用Facebook登录”功能来替换基于用户名/密码的登录,但是此后仍使用相同的基于令牌的身份验证。

登录流程

客户端

用户单击“使用Facebook登录”按钮,这是指向“ / auth / facebook”的简单链接,SocialAuthenticationFilter注意到缺少其他查询参数,并触发了将您的网站用户重定向到Facebook的重定向。 他们使用用户名/密码登录,然后重定向回“ / auth / facebook”,但这一次指定了“?code =…&state =…”参数。 (如果用户以前登录过facebook并设置了cookie,facebook甚至会立即重定向回该用户,而根本不向用户显示任何facebook屏幕。)有趣的是,您可以按照浏览器网络日志中的说明进行操作。所有操作均使用纯HTTP 302重定向完成。 (HTTP响应中的“ Location”标头用于告诉浏览器下一步要去哪里)

服务器端

从facebook重定向到“ / auth / facebook?code =…&state =…”之后,SocialAuthenticationFilter现在将看到适当的参数,并将触发两个服务器调用Facebook。 第一个是获取已登录用户的访问令牌,第二个是通过使用访问令牌获取用户详细信息来测试整个过程是否成功。 完成所有这些操作后,就可以认为用户已登录,并且可以使用另一个302重定向(到“ /”)将他重定向回到应用程序的根目录。

关于Spring社交的一些话

Spring Social是用于处理社交网络的完整框架,其范围远远超出了仅登录场景。 除了不同的社交网络适配器之外,还有一个名为Spring Social Security的小型集成库,该库以与Spring Security更好地集成的方式实现了社交身份验证用例。 它带有一个映射到“ / auth”的SocialAuthenticationFilter,这就是我们将要使用的。

因此,设置社交身份验证需要使用简洁的Spring Social Security库配置Spring Social本身以及Spring Security

Spring社交

配置它基本上涉及扩展SocialConfigurerAdapter。 首先,您告诉它要支持哪些社交网络:

将facebook添加为提供者

@Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
	cfConfig.addConnectionFactory(new FacebookConnectionFactory(
			env.getProperty("facebook.appKey"),
			env.getProperty("facebook.appSecret")));
}

它还需要知道如何获取当前用户的用户ID:

检索UserId

@Override
public UserIdSource getUserIdSource() {
	//retrieve the UserId from the UserAuthentication in security context
	return new UserAuthenticationUserIdSource();
}

最后,它需要一个UsersConnectionRepository。 基本上负责用户及其与社交网络的连接之间的关系。 Spring Social带有自己的两个实现(jdbc或内存中)。 我选择自己动手,因为我想重用基于Spring Data JPA的UserDetailsS​​ervice。

自定义UsersConnectionRepository

@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
	SimpleUsersConnectionRepository usersConnectionRepository =
			new SimpleUsersConnectionRepository(userService, connectionFactoryLocator);
	
	// if no local user record exists yet for a facebook's user id
	// automatically create a User and add it to the database
	usersConnectionRepository.setConnectionSignUp(autoSignUpHandler);
	
	return usersConnectionRepository;
}

Spring安全

如上一篇博客文章所述,对其进行配置基本上涉及扩展WebSecurityConfigurerAdapter。 除了配置和公开AuthenticationManager和UserDetailsS​​ervice之类的常用内容外,它现在还需要配置和插入SocialAuthenticationFilter。 由于SpringSocialConfigurer完成了大部分工作,因此这基本上只涉及很少的代码。 它可能很简单:

@Override
protected void configure(HttpSecurity http) throws Exception {
	// apply the configuration from the socialConfigurer 
	// (adds the SocialAuthenticationFilter)
	http.apply(new SpringSocialConfigurer());
}

考虑到我想插入基于令牌的身份验证,我自己的succesHandler和userIdSource; 我必须进行一些配置更改:

@Autowired private SocialAuthenticationSuccessHandler successHandler;
@Autowired private StatelessAuthenticationFilter jwtFilter;
@Autowired private UserIdSource userIdSource;

@Override
protected void configure(HttpSecurity http) throws Exception {

// Set a custom successHandler on the SocialAuthenticationFilter (saf)
final SpringSocialConfigurer sc = new SpringSocialConfigurer();
sc.addObjectPostProcessor(new ObjectPostProcessor<...>() {
	@Override
	public <...> O postProcess(O saf) {
		saf.setAuthenticationSuccessHandler(successHandler);
		return saf;
	}
});

http.

...

// add custom authentication filter for stateless JWT based authentication
.addFilterBefore(jwtFilter, AbstractPreAuthenticatedProcessingFilter.class)

// apply the configuration from the SocialConfigurer
.apply(sc.userIdSource(userIdSource));
}

如果您愿意,还可以继承SpringSocialConfigurer的子类,并为自定义的successHandler提供更优雅的设置器…

过去的样板(在这里赞誉您)

现在是时候关注一些更有趣的地方了。

建立与Facebook的初始成功连接后,立即触发自定义ConnectionSignUp:

@Override
@Transactional
public String execute(final Connection<?> connection) {
    //add new users to the db with its default roles
    final User user = new User();
    final String firstName = connection.fetchUserProfile().getFirstName();
    user.setUsername(generateUniqueUserName(firstName));
    user.setProviderId(connection.getKey().getProviderId());
    user.setProviderUserId(connection.getKey().getProviderUserId());
    user.setAccessToken(connection.createData().getAccessToken());
    grantRoles(user);
    userRepository.save(user);
    return user.getUserId();
}

如您所见,我的版本只是将用户的连接数据持久化为单个JPA对象。 故意仅支持用户与Facebook上的身份之间的一对一关系。

请注意,我最终从用户生成的实际令牌中排除了连接属性。 就像我之前排除了密码字段(该字段不再是User对象的一部分)一样:

@JsonIgnore
private String accessToken;

走这条路线确实意味着对facebook API的任何调用都需要数据库查询其他连接字段。 稍后将对此进行更多讨论。

在用户通过身份验证之后,立即触发自定义AuthenticationSuccessHandler:

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) {

	// Lookup the complete User object from the database
	final User user = userService.loadUserByUsername(auth.getName());

	// Add UserAuthentication to the response
	final UserAuthentication ua = new UserAuthentication(user);
	tokenAuthenticationService.addAuthentication(response, ua);
	super.onAuthenticationSuccess(request, response, auth);
}

这看起来很像以前博客文章中的代码,但是我不得不在TokenAuthenticationService中进行一些更改。 由于客户端是在重定向后加载的,因此要在此之前在客户端保留令牌,必须将其作为cookie发送给客户端:

public void addAuthentication(HttpServletResponse response, UserAuthentication authentication) {
  final User user = authentication.getDetails();
  user.setExpires(System.currentTimeMillis() + TEN_DAYS);
  final String token = tokenHandler.createTokenForUser(user);

  // Put the token into a cookie because the client can't capture response
  // headers of redirects / full page reloads. 
  // (this response triggers a redirect back to "/")
  response.addCookie(createCookieForToken(token));
}

最终成为最终重定向响应的一部分,如下所示:

成功登录后,最终重定向到客户端

成功登录后,最终重定向到客户端

成功登录后,最终重定向到客户端

最后也是最好的部分是所有代码结合在一起形成一个非常漂亮的API。 由于Spring Social已经负责创建用户特定的请求范围的ConnectionRepository,因此可以通过将以下bean代码添加到SocialConfigurerAdapter来创建其特定于连接的API:

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repo) {
Connection<Facebook> connection = repo.findPrimaryConnection(Facebook.class);
	return connection != null ? connection.getApi() : null;
}

此用户特定的facebook bean可以在控制器中使用,如下所示:

@Autowired
Facebook facebook;

@RequestMapping(value = "/api/facebook/details", method = RequestMethod.GET)
public FacebookProfile getSocialDetails() {
	return facebook.userOperations().getUserProfile();
}

客户端实施

如前所述,令牌现在作为Cookie传递给客户端。 但是,就像以前一样,服务器端仍然只接受发送到特殊HTTP标头中的令牌。 承认这是相当随意的,您可以让它简单地接受cookie。 我宁愿不要这样做,因为它可以防止CSRF攻击。 (因为无法指示浏览器将正确的身份验证令牌自动添加到请求中。)

因此,在获取当前用户详细信息之前,前端的init方法现在首先尝试将cookie移至本地存储:

$scope.init = function () {
	var authCookie = $cookies['AUTH-TOKEN'];
	if (authCookie) {
		TokenStorage.store(authCookie);
		delete $cookies['AUTH-TOKEN'];
	}
	$http.get('/api/user/current').success(function (user) {
		if (user.username) {
			$rootScope.authenticated = true;
			$scope.username = user.username;
			
			// For display purposes only
			$scope.token = JSON.parse(atob(
			    TokenStorage.retrieve().split('.')[0]));
		}
	});
};

自定义HTTP标头的放置在与上次相同的http拦截器中进行处理。

实际的“使用Facebook登录”按钮只是触发整个重定向狂潮的链接:

<a href="/auth/facebook"><button>Login with Facebook</button></a>

为了检查实际的Facebook API是否有效,我添加了另一个按钮,用于在登录后显示来自facebook的用户详细信息。

最后的话(建议)

将我的自定义版本的JWT与社交身份验证集成在一起是一个很大的旅程。 有些部分不那么琐碎。 就像在将数据库调用卸载到JWT令牌之间找到一个很好的平衡。 最终,我选择不与客户端共享Facebook的访问令牌,因为只有在使用Facebook的API时才需要它。 这意味着对Facebook的任何查询都需要数据库调用来获取令牌。 实际上,这意味着对任何具有@Autowired Facebook服务的控制器的任何REST API调用都会导致获取请求令牌的过程非常热烈,这是请求范围的Bean创建的一部分。 但是,通过使用专用控制器进行Facebook调用可以轻松缓解这种情况,但这绝对是需要注意的。

如果您打算实际使用此代码并进行Facebook API调用,请确保您的JWT令牌在facebook令牌之前过期(当前有效期为60天)。 最好在检测到故障时实施强制重新登录,因为任何重新登录都会自动将新获取的facebook令牌存储在数据库中。

您可以在github上找到完整的工作示例。 也可以在此处找到有关如何运行它的详细信息。 我已经包含了Maven和Gradle构建文件。

翻译自: https://www.javacodegeeks.com/2015/01/stateless-spring-security-part-3-jwt-social-authentication.html

stateless

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值