我需要使用 oauth2 服务创建授权。我需要从中获取令牌,而不是在访问资源(REST 服务)时使用此令牌。我怎样才能做到这一点?起点是什么?看到例子会很棒。
2 回答
这里有大量样本:https ://github.com/spring-projects/spring-security-oauth/tree/master/samples和这里:https ://github.com/spring-projects/spring-security-oauth/tree /master/tests/annotation。
当您在 Google 中键入 SpringMVC OAuth 时,第一个 SOF 问题就是这个问题,现有的答案不是很详细(一切都是通过注释完成的......没有幕后的细节),尽管这个问题很老,但我给出了更详细的回答。
要将 SpringMVC 和 OAuth 桥接在一起,您需要使用使用 Oauth 对 Web 应用程序进行身份验证的两个流程之一:密码(或资源所有者密码)流程或隐式流程。
使用密码流,您将拥有自己的登录页面(在您的 SpringMVC 应用程序中)并将凭据发送到授权服务器(OAuth 服务器)以验证它们。授权服务器可以使用 Spring Security OAuth 构建,也可以是 Google 的。您可以使用此示例来帮助您做到这一点:https ://github.com/skate056/spring-security-oauth2-google您需要配置将使用 RestTemplate 与授权服务器通信的特定过滤器。
如果您想使用隐式流程(更好的解决方案,因为它更安全:您的应用程序和授权服务器之间没有凭证),它更简单,您可以按照以下基本步骤操作:
弹簧安全上下文:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login
login-page="http://authserver/uaa/oauth/authorize?response_type=token&client_id=acme&scope=internal&redirect_uri=http://myserver/myappli/login.do"
authentication-failure-url="/login.do?login_error=1"
/>
<logout logout-url="/logout.do" logout-success-url="/login.do" />
<custom-filter ref="oauth2ClientContextFilter" after="EXCEPTION_TRANSLATION_FILTER"/>
<custom-filter ref="oAuth2AuthenticationProcessingFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</http>
<global-method-security pre-post-annotations="enabled"/>
<beans:bean id="oauth2ClientContextFilter" class="org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter" />
<beans:bean id="oAuth2AuthenticationProcessingFilter" class="fr.loicmathieu.auth.oauth.ImplicitFlowOAuthProcessingFilter">
<beans:constructor-arg name="defaultFilterProcessesUrl" value="/register_token"/>
<beans:property name="authenticationManager" ref="theAuthenticationManager" />
</beans:bean>
身份验证管理器与您的特定应用程序相关,它可以使用 get token info 端点从授权服务器加载用户信息,从 LDAP 加载用户信息,如果使用 JWT,甚至从令牌本身加载。
我的 ImplicitFlowOAuthProcessingFilter 实现非常基本,它从令牌创建一个身份验证对象,然后您的 AuthenticationProvider 将使用此身份验证对象来检索令牌并使用它做任何你想做的事情:
public class ImplicitFlowOAuthProcessingFilter extends AbstractAuthenticationProcessingFilter{
public ImplicitFlowOAuthProcessingFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
String token = request.getParameter("access_token");
return this.getAuthenticationManager().authenticate(new OAuth2TokenAuthentication(token));
}
最后一招是登录页面,Spring Security OAuth的Authentication Server的默认实现将访问令牌附加到ULR的#部分,这部分在服务器中是不可用的,所以我使用了一个会移动令牌的登录页面从 # 部分到 access_token 请求参数并重定向到 register_token URL:
- 授权服务器重定向到http://myserver/myapplication/login.do#access_token=
- 登录页面通过 JavaScript 读取 URL 的哈希并重定向到http://myserver/myapplication/register_token?access_token=
- 最后,我的 ImplicitFlowOAuthProcessingFilter 将读取此参数,获取令牌,构建将由身份验证管理器使用的身份验证对象
希望这会对某人有所帮助。
洛伊克