上QQ阅读APP看书,第一时间看更新
The DomainUsernamePasswordAuthenticationFilter class
Spring Security provides a number of servlet filters that act as controllers for authenticating users. The filters are invoked as one of the delegates of the FilterChainProxy object that we discussed in Chapter 2, Getting Started with Spring Security. Previously, the formLogin() method instructed Spring Security to use o.s.s.web.authentication.UsernamePasswordAuthenticationFilter to act as a login controller. The filter's job is to perform the following tasks:
- Obtain a username and password from the HTTP request.
- Create a UsernamePasswordAuthenticationToken object with the information obtained from the HTTP request.
- Request that Spring Security validates UsernamePasswordAuthenticationToken.
- If the token is validated, it will set the authentication returned to it on SecurityContextHolder, just as we did when a new user signed up for an account. We will need to extend UsernamePasswordAuthenticationFilter to leverage our newly created DoainUsernamePasswordAuthenticationToken object.
- Create a DomainUsernamePasswordAuthenticationFilter object, as follows:
//src/main/java/com/packtpub/springsecurity/web/authentication/
DomainUsernamePasswordAuthenticationFilter.java
public final class
DomainUsernamePasswordAuthenticationFilter extends
UsernamePasswordAuthenticationFilter {
public Authentication attemptAuthentication
(HttpServletRequest request,HttpServletResponse response) throws
AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException
("Authentication method not supported: "
+ request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
String domain = request.getParameter("domain");
// authRequest.isAuthenticated() = false since no
//authorities are specified
DomainUsernamePasswordAuthenticationToken authRequest
= new DomainUsernamePasswordAuthenticationToken(username,
password, domain);
setDetails(request, authRequest);
return this.getAuthenticationManager()
.authenticate(authRequest);
}
}
The new DomainUsernamePasswordAuthenticationFilter object will perform the following tasks:
- Obtain a username, password, and domain from the HttpServletRequest method.
- Create our DomainUsernamePasswordAuthenticationToken object with information obtained from the HTTP request.
- Request that Spring Security validates DomainUsernamePasswordAuthenticationToken. The work is delegated to CalendarUserAuthenticationProvider.
- If the token is validated, its superclass will set the authentication returned by CalendarUserAuthenticationProvider on SecurityContextHolder, just as we did to authenticate a user after they created a new account.