BasicAuthenticationFilter过滤器对应的类路径为
org.springframework.security.web.authentication.www.BasicAuthenticationFilter
Basic验证方式相比较而言用的不是太多。spring security也支持basic的方式,配置如下
- <security:http auto-config="true">
-
- <security:http-basic/>
- <security:logout logout-success-url="/login.jsp" invalidate-session="true"/>
- <security:intercept-url pattern="/login.jsp*" filters="none"/>
- <security:intercept-url pattern="/admin.jsp*" access="ROLE_ADMIN"/>
- <security:intercept-url pattern="/index.jsp*" access="ROLE_USER,ROLE_ADMIN"/>
- <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
- </security:http>
如果选择basic方式,需要把form-login标签的定义给注释掉。
接下来看BasicAuthenticationFilter的执行过程
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
- throws IOException, ServletException {
- final boolean debug = logger.isDebugEnabled();
- final HttpServletRequest request = (HttpServletRequest) req;
- final HttpServletResponse response = (HttpServletResponse) res;
-
-
-
- String header = request.getHeader("Authorization");
- if ((header != null) && header.startsWith("Basic ")) {
- byte[] base64Token = header.substring(6).getBytes("UTF-8");
-
- String token = new String(Base64.decode(base64Token), getCredentialsCharset(request));
- String username = "";
- String password = "";
- int delim = token.indexOf(":");
-
- if (delim != -1) {
- username = token.substring(0, delim);
- password = token.substring(delim + 1);
- }
-
- if (debug) {
- logger.debug("Basic Authentication Authorization header found for user '" + username + "'");
- }
-
- if (authenticationIsRequired(username)) {
- UsernamePasswordAuthenticationToken authRequest =
- new UsernamePasswordAuthenticationToken(username, password);
- authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
-
- Authentication authResult;
-
- try {
- authResult = authenticationManager.authenticate(authRequest);
- } catch (AuthenticationException failed) {
-
- if (debug) {
- logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
- }
-
- SecurityContextHolder.getContext().setAuthentication(null);
-
- rememberMeServices.loginFail(request, response);
-
- onUnsuccessfulAuthentication(request, response, failed);
-
- if (ignoreFailure) {
- chain.doFilter(request, response);
- } else {
- authenticationEntryPoint.commence(request, response, failed);
- }
-
- return;
- }
-
-
- if (debug) {
- logger.debug("Authentication success: " + authResult.toString());
- }
-
- SecurityContextHolder.getContext().setAuthentication(authResult);
-
- rememberMeServices.loginSuccess(request, response, authResult);
-
- onSuccessfulAuthentication(request, response, authResult);
- }
- }
-
- chain.doFilter(request, response);
- }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。