Debug debugging: Run: http: // localhost: 8080/acegitest1/index. jsp because it is configured in web. xml:
<filter-name >AcegiFilterChainProxy </filter-name > <filter-class > org.acegisecurity.util.FilterToBeanProxy </filter-class > <init-param > <param-name >targetBean </param-name > <param-value >filterChainProxy </param-value > </init-param >
1. Enter: doFilter in the FilterToBeanProxy proxy class. Because init is executed only once and once at startup, you can directly access the doFilter method when accessing the url.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!initialized ) { doInit(); } delegate.doFilter(request, response, chain); }2. Go to: doFilter in the target class filterChainProxy
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); ConfigAttributeDefinition cad = this.filterInvocationDefinitionSource .getAttributes(fi); if (cad == null) { if ( logger.isDebugEnabled()) { logger.debug(fi.getRequestUrl() + " has no matching filters"); } chain.doFilter(request, response); return; } Filter[] filters = obtainAllDefinedFilters(cad); if (filters.length == 0) { if ( logger.isDebugEnabled()) { logger.debug(fi.getRequestUrl() + " has an empty filter list"); } chain.doFilter(request, response); return; } VirtualFilterChain virtualFilterChain = new VirtualFilterChain(fi, filters); virtualFilterChain.doFilter(fi.getRequest(), fi.getResponse()); }This method mainly gets the number of filters configured by the user in the aceg configuration file, and the filter order is displayed as an array. In this way, filter is connected. 3. Go to: filter the first filter, that is, the basicProcessingFilter we configured. The doFilter is as follows:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException( "Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException( "Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String header = httpRequest.getHeader( "Authorization"); if (logger.isDebugEnabled()) { logger.debug( "Authorization header: " + header); } if ((header != null) && header.startsWith( "Basic ")) { String base64Token = header.substring(6); String token = new String(Base64.decodeBase64(base64Token.getBytes())); String username = ""; String password = ""; int delim = token.indexOf( ":"); if (delim != -1) { username = token.substring(0, delim); password = token.substring(delim + 1); } if (authenticationIsRequired(username)) { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); authRequest.setDetails(authenticationDetailsSource .buildDetails((HttpServletRequest) request)); Authentication authResult; try { authResult = authenticationManager.authenticate(authRequest); } catch (AuthenticationException failed) { // Authentication failed if ( logger.isDebugEnabled()) { logger.debug( "Authentication request for user: " + username + " failed: " + failed.toString()); } SecurityContextHolder.getContext().setAuthentication( null); if ( rememberMeServices != null) { rememberMeServices.loginFail(httpRequest, httpResponse); } if ( ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } // Authentication success if ( logger.isDebugEnabled()) { logger.debug( "Authentication success: " + authResult.toString()); } SecurityContextHolder.getContext().setAuthentication(authResult); if ( rememberMeServices != null) { rememberMeServices.loginSuccess(httpRequest, httpResponse, authResult); } } } chain.doFilter(request, response); }The key lies in
If(Header! =
Null) & Header. startsWith ("Basic"), where basic authentication stores the user's input username and password in the header for basic authentication. Because this header is null [analysis header later], execute the next filter. 4. Enter exceptionfilter5. enter filterInvocationInterceptor
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); invoke(fi); }Follow in to invoke, and then enter InterceptorStatusToken token =
Super. BeforeInvocation (fi); the final key lies in ConfigAttributeDefinition attr =
This. ObtainObjectDefinitionSource (). getAttributes (object); obtainObjectDefinitionSource is familiar to everyone, that is, the acegi configuration file, which has the role to configure. Because index. jsp is not configured, it is returned as a callback function similar to null6. step by step. This page is executed once. Even if exceptionfilter captures an exception, but because index. jsp does not configure authorization, the exception policy authenticationEntryPoint in the filter is not executed. After access to index. jsp is completed, we can debug security. jsp for accessing the protected page because acegi is configured. The above process has been tuned to everyone, and the next step is the difference. Of course, this is also the filtering and connection process. The user name and password are not input during access to protected resources, and an exception is reported to basic. The basic authentication dialog box is displayed, indicating that the user name and password are entered. Enter the correct and valid user and test as follows: header: you configure to protect urlObjectDefinitionSource to obtain permissions:
public ConfigAttributeDefinition lookupAttributes(String url) { // Strip anything after a question mark symbol, as per SEC-161. See also SEC-321 int firstQuestionMarkIndex = url.indexOf( "?"); if (firstQuestionMarkIndex != -1) { url = url.substring(0, firstQuestionMarkIndex); } if (isConvertUrlToLowercaseBeforeComparison()) { url = url.toLowerCase(); if ( logger.isDebugEnabled()) { logger.debug( "Converted URL to lowercase, from: '" + url + "'; to: '" + url + "'"); } } Iterator iter = requestMap.iterator(); while (iter.hasNext()) { EntryHolder entryHolder = (EntryHolder) iter.next(); boolean matched = pathMatcher.match(entryHolder.getAntPath(), url); if ( logger.isDebugEnabled()) { logger.debug( "Candidate is: '" + url + "'; pattern is " + entryHolder.getAntPath() + "; matched=" + matched); } if (matched) { return entryHolder.getConfigAttributeDefinition(); } } return null; }Voting mechanism: key code:
authenticated = SecurityContextHolder.getContext().getAuthentication(); this. accessDecisionManager .decide(authenticated, object, attr); public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config) { int result = ACCESS_ABSTAIN; Iterator iter = config.getConfigAttributes(); while (iter.hasNext()) { ConfigAttribute attribute = (ConfigAttribute) iter.next(); if ( this.supports(attribute)) { result = ACCESS_DENIED; // Attempt to find a matching granted authority for ( int i = 0; i < authentication.getAuthorities().length ; i++) { if (attribute.getAttribute().equals(authentication.getAuthorities()[i].getAuthority())) { return ACCESS_GRANTED; } } } } return result; } while (iter.hasNext()) { AccessDecisionVoter voter = (AccessDecisionVoter) iter.next(); int result = voter.vote(authentication, object, config); switch (result) { case AccessDecisionVoter. ACCESS_GRANTED: return; case AccessDecisionVoter. ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied" , "Access is denied")); }The above is not a very complete code, but it is very critical code. You can download the source code, debug it yourself, and attach the acegi source code. Generally, basic authentication is rarely used for the complete system, because each system has its own logon page. If you have not logged on to the system, you should jump to the logon page. If you have insufficient permissions, you should jump to the accessdefined page. In the next blog, we will build form-based authentication. Project source code: