问题
I know this has been asked already, but I am not able to get it to work. Here is what I would like to get accomplished:
I am using Spring Security 3.2 to secure a REST-like service. No server side sessions. I am not using basic auth, because that would mean that I need to store the user's password in a cookie on client side. Otherwise the user would need to login with each page refresh/ change. Storing a token is I guess the lesser evil.
- A web client (browser, mobile app) calls a REST-like URL to login "/login" with username and password
- The server authenticates the user and sends a token back to the client
- The client stores the token and adds it to the http request header with each api call
- The server checks the validity of the token and sends a response accordingly
I did not even look at the token generation part yet. I know it is backwards, but I wanted to get the token validation part implemented first.
I am trying to get this accomplished by using a custom filer (implementation of AbstractAuthenticationProcessingFilter), however I seem to have the wrong idea about it.
Defining it like this:
public TokenAuthenticationFilter() {
super("/");
}
will only trigger the filter for this exact URL. I am sticking to some sample implementation, where it calls AbstractAuthenticationProcessingFilter#requiresAuthentication which does not accept wildcards. I can of course alter that behavior, but this somehow makes me think that I am on the wrong path.
I also started implementing a custom AuthenticationProvider. Maybe that is the right thing? Can someone give me a push into the right direction?
回答1:
I think pre-auth filter is a better fit for your scenario. Override AbstractPreAuthenticatedProcessingFilter's getPrincipal and getCredentials methods. In case the token is not present in the header, return null from getPrincipal.
Flow:
- User logs in for the first time, no header passed, so no authentication object set in securityContext, normal authentication process follows i.e. ExceptionTranslation filter redirtects the user to /login page based on form-logon filter or your custom authenticationEntryPoint
- After successful authentication, user requests secured url, pre-auth filter gets token from header authentication object set in securityContext, if user have access he is allowed to access secured url
来源:https://stackoverflow.com/questions/18131669/spring-security-3-2-token-authentication