gpt4 book ai didi

java - Spring oauth拦截rest api调用并从一个拦截器转发

转载 作者:行者123 更新时间:2023-12-01 11:03:33 24 4
gpt4 key购买 nike

我已经配置了所有的 spring security 和 oauth token 获取等

但是我是否必须在每个 REST API 调用中从数据库验证用户?

这是我的示例 API:

@GET
@Path("/getUUID")
public Response getUUID(@Context HttpServletRequest request, final @Context SecurityContext securityContext) {
//here do i have to do this in each api or there is one filter that can i write and pass this user object from that to api
User loadUser = loadUserFromSecurityContext(securityContext);
}

protected User loadUserFromSecurityContext(SecurityContext securityContext) {

OAuth2Authentication requestingUser = (OAuth2Authentication) (securityContext).getUserPrincipal();
String principal = requestingUser.getUserAuthentication().getName();
User user = null;
user = new UserDAO().getUser(principal);

return user;
}

最佳答案

您可以通过实现以下过滤器来拦截 api 调用:

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

AuthenticationManager authManager;

public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
this.authManager = authManager;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest)request;

//access your token here and do what you wanna do with it
String authToken = httpServletRequest.getHeader("AUTHORIZATION");

// continue thru the filter chain
chain.doFilter(request, response);
}
}

在你的 spring-servlet.xml 中

<http pattern="/api/**" create-session="never" use-expressions="true"
entry-point-ref="oauthAuthenticationEntryPoint" xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<custom-filter ref="authenticationTokenProcessingFilter" before="FORM_LOGIN_FILTER"/>
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<bean id="authenticationTokenProcessingFilter" class="com.yourpackage.AuthenticationTokenProcessingFilter">
<constructor-arg ref="authenticationManager" />
</bean>

关于java - Spring oauth拦截rest api调用并从一个拦截器转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com