【发布时间】:2023-04-05 02:25:01
【问题描述】:
我需要使用 oauth2 服务创建授权。我需要从中获取令牌,而不是在访问资源(REST 服务)时使用此令牌。我怎样才能做到这一点?起点是什么?看看例子就更好了。
【问题讨论】:
标签: spring security model-view-controller spring-security-oauth2
我需要使用 oauth2 服务创建授权。我需要从中获取令牌,而不是在访问资源(REST 服务)时使用此令牌。我怎样才能做到这一点?起点是什么?看看例子就更好了。
【问题讨论】:
标签: spring security model-view-controller spring-security-oauth2
当您在 Google 中键入 SpringMVC OAuth 时,第一个 SOF 问题就是这个问题,并且现有的答案不是很详细(一切都是通过注释完成的......没有幕后的细节),尽管我给出的问题很老更详细的答案。
要将 SpringMVC 和 OAuth 桥接在一起,您需要使用通过 Oauth 对 Web 应用程序进行身份验证的两个流程之一:密码(或资源所有者密码)流程或隐式流程。
使用密码流,您将拥有自己的登录页面(在您的 SpringMVC 应用程序中)并将凭据发送到授权服务器(OAuth 服务器)以验证它们。授权服务器可以使用 Spring Security OAuth 构建,也可以是 Google 的。您可以使用此示例来帮助您完成此操作:https://github.com/skate056/spring-security-oauth2-google 您需要配置将使用 RestTemplate 与授权服务器通信的特定过滤器。
如果您想使用隐式流程(更好的解决方案,因为它更安全:您的应用程序和授权服务器之间没有凭证),它更简单,您可以按照以下基本步骤操作:
Spring 安全上下文:
<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:
希望这会对某人有所帮助。
洛伊克
【讨论】: