我已经配置了所有弹簧安全性和oauth令牌等等
但我是否必须在每次休息api呼叫中从DB验证用户?
这是我的例子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;
}
答案 0 :(得分:1)
您可以通过实施以下过滤器来拦截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>