spring security4.1.3配置以及踩过的坑

https://blog.csdn.net/honghailiang888/article/details/53520557

spring security完全可以作为一个专门的专题来说,有一个专题写的不错http://www.iteye.com/blogs/subjects/spring_security,我这里主要是针对4.1.3进行配置说明

一、所需的库文件

  1.  
    //spring-security
  2.  
    compile 'org.springframework.security:spring-security-web:4.1.3.RELEASE'
  3.  
    compile 'org.springframework.security:spring-security-config:4.1.3.RELEASE'
  4.  
    compile 'org.springframework.security:spring-security-taglibs:4.1.3.RELEASE'

二、web配置

从4以后security就只吃java配置了,具体可以看下《spring in action第四版》,我这里还是使用xml配置

过滤器配置,security是基于过滤器的,web.xml

  1.  
    <!-- Spring-security -->
  2.  
    <filter>
  3.  
    <filter-name>springSecurityFilterChain</filter-name>
  4.  
    <filter-class>
  5.  
    org.springframework.web.filter.DelegatingFilterProxy
  6.  
    </filter-class>
  7.  
    </filter>
  8.  
    <filter-mapping>
  9.  
    <filter-name>springSecurityFilterChain</filter-name>
  10.  
    <url-pattern>/*</url-pattern>
  11.  
    </filter-mapping>

需要注意的是,如果配置了sitemesh装饰器,如果在装饰器页面中用到了security,比如标签,那么security过滤器需要配置在sitemesh之前,否则装饰器页中的<sec:authorize>标签可能不起作用

  1.  
    <!-- Spring-security -->
  2.  
    <filter>
  3.  
    <filter-name>springSecurityFilterChain</filter-name>
  4.  
    <filter-class>
  5.  
    org.springframework.web.filter.DelegatingFilterProxy
  6.  
    </filter-class>
  7.  
    </filter>
  8.  
    <filter-mapping>
  9.  
    <filter-name>springSecurityFilterChain</filter-name>
  10.  
    <url-pattern>/*</url-pattern>
  11.  
    </filter-mapping>
  12.  
     
  13.  
    <!--sitemesh装饰器放在spring security过来器的后面,以免装饰器页中的security不起作用-->
  14.  
    <filter>
  15.  
    <filter-name>sitemesh</filter-name>
  16.  
    <filter-class>
  17.  
    org.sitemesh.config.ConfigurableSiteMeshFilter
  18.  
    </filter-class>
  19.  
    <init-param>
  20.  
    <param-name>ignore</param-name>
  21.  
    <param-value>true</param-value>
  22.  
    </init-param>
  23.  
    <init-param>
  24.  
    <param-name>encoding</param-name>
  25.  
    <param-value>UTF-8</param-value>
  26.  
    </init-param>
  27.  
    </filter>
  28.  
    <filter-mapping>
  29.  
    <filter-name>sitemesh</filter-name>
  30.  
    <url-pattern>/*</url-pattern>
  31.  
    </filter-mapping>

装饰器页面中的使用

  1.  
    <sec:authorize access="!hasRole('ROLE_USER')">
  2.  
    <li>你好,欢迎来到Mango!<a href="<c:url value='/login'/>" class="current">登录</a></li>
  3.  
    </sec:authorize>
  4.  
    <sec:authorize access="hasRole('ROLE_USER')">
  5.  
    <li><sec:authentication property="principal.username"/>欢迎光临Mango!<a href="<c:url value='/logout'/>" class="current">退出</a></li>
  6.  
    </sec:authorize>

三、security配置文件配置

applicationContext-security.xml

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
     
  3.  
    <beans:beans xmlns="http://www.springframework.org/schema/security"
  4.  
    xmlns:beans="http://www.springframework.org/schema/beans"
  5.  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6.  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.  
    http://www.springframework.org/schema/beans/spring-beans.xsd
  8.  
    http://www.springframework.org/schema/security
  9.  
    http://www.springframework.org/schema/security/spring-security.xsd">
  10.  
     
  11.  
    <http auto-config="true" use-expressions="true" >
  12.  
    <form-login
  13.  
    login-page="/login"
  14.  
    authentication-failure-url="/login?error"
  15.  
    login-processing-url="/login"
  16.  
    always-use-default-target="false"
  17.  
    authentication-success-handler-ref="myAuthenticationSuccessHandler" />
  18.  
    <!-- 认证成功用自定义类myAuthenticationSuccessHandler处理 -->
  19.  
     
  20.  
    <logout logout-url="/logout"
  21.  
    logout-success-url="/"
  22.  
    invalidate-session="true"
  23.  
    delete-cookies="JSESSIONID"/>
  24.  
     
  25.  
    <csrf disabled="true" />
  26.  
    <intercept-url pattern="/order/*" access="hasRole('ROLE_USER')"/>
  27.  
    </http>
  28.  
     
  29.  
    <!-- 使用自定义类myUserDetailsService从数据库获取用户信息 -->
  30.  
    <authentication-manager>
  31.  
    <authentication-provider user-service-ref="myUserDetailsService">
  32.  
    <!-- 加密 -->
  33.  
    <password-encoder hash="md5">
  34.  
    </password-encoder>
  35.  
    </authentication-provider>
  36.  
    </authentication-manager>
  37.  
     
  38.  
    </ beans:beans>

这里配置了自定义登录界面/login,还需要配置控制器条撞到login.jsp页面,如果字段使用默认值为username和password,当然也可以用 form-login标签中的属性username-parameter="username"password-parameter="password"进行设置,这里的值要和登录页面中的字段一致。login.jsp

  1.  
    <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
  2.  
    <%@ include file="../includes/taglibs.jsp"%>
  3.  
    <!DOCTYPE html>
  4.  
    <html>
  5.  
    <head>
  6.  
    <title>Mango-Login</title>
  7.  
    <meta name="menu" content="home" />
  8.  
    </head>
  9.  
     
  10.  
    <body>
  11.  
     
  12.  
    <h1>请登录!</h1>
  13.  
     
  14.  
    <div style="text-align:center">
  15.  
    <form action="<c:url value='/login' />" method="post">
  16.  
    <c:if test="${not empty error}">
  17.  
    <p style="color:red">${error}</p>
  18.  
    </c:if>
  19.  
    <table>
  20.  
    <tr>
  21.  
    <td>用户名:</td>
  22.  
    <td><input type="text" name="username"/></td>
  23.  
    </tr>
  24.  
    <tr>
  25.  
    <td>密码:</td>
  26.  
    <td><input type="password" name="password"/></td>
  27.  
    </tr>
  28.  
    <tr>
  29.  
    <td colspan="2" align="center">
  30.  
    <input type="submit" value="登录"/>
  31.  
    <input type="reset" value="重置"/>
  32.  
    </td>
  33.  
    </tr>
  34.  
    </table>
  35.  
    </form>
  36.  
    </div>
  37.  
     
  38.  
    </body>
  39.  
    </html>

其中,form action的值要和配置文件中login-process-url的值一致,提交后UsernamePasswordAuthenticationFilter才能对其进行授权认证。
另外认证是采用的自定义myUserDetailsService获取用户信息方式,由于该项目中集成的是Hibernate,所以自己定义了,security系统中是支持jdbc进行获取的

  1.  
    package com.mango.jtt.springSecurity;
  2.  
     
  3.  
    import org.springframework.beans.factory.annotation.Autowired;
  4.  
    import org.springframework.security.core.authority.AuthorityUtils;
  5.  
    import org.springframework.security.core.userdetails.User;
  6.  
    import org.springframework.security.core.userdetails.UserDetails;
  7.  
    import org.springframework.security.core.userdetails.UserDetailsService;
  8.  
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
  9.  
    import org.springframework.stereotype.Service;
  10.  
     
  11.  
    import com.mango.jtt.po.MangoUser;
  12.  
    import com.mango.jtt.service.IUserService;
  13.  
     
  14.  
    /**
  15.  
    * 从数据库中获取信息的自定义类
  16.  
    *
  17.  
    * @author HHL
  18.  
    *
  19.  
    */
  20.  
    @Service
  21.  
    public class MyUserDetailsService implements UserDetailsService {
  22.  
     
  23.  
    @Autowired
  24.  
    private IUserService userService;
  25.  
     
  26.  
    /**
  27.  
    * 获取用户信息,设置角色
  28.  
    */
  29.  
    @Override
  30.  
    public UserDetails loadUserByUsername(String username)
  31.  
    throws UsernameNotFoundException {
  32.  
    // 获取用户信息
  33.  
    MangoUser mangoUser = userService.getUserByName(username);
  34.  
    if (mangoUser != null) {
  35.  
    // 设置角色
  36.  
    return new User(mangoUser.getUserName(), mangoUser.getPassword(),
  37.  
    AuthorityUtils.createAuthorityList(mangoUser.getRole()));
  38.  
    }
  39.  
     
  40.  
    throw new UsernameNotFoundException("User '" + username
  41.  
    + "' not found.");
  42.  
    }
  43.  
     
  44.  
    }


认证成功之后也是自定义了处理类myAuthenticationSuccessHandler,该处理类继承了SavedRequestAwareAuthenticationSuccessHandler,实现了保存请求信息的操作,如果不配置,默认的也是交给SavedRequestAwareAuthenticationSuccessHandler处理,因为在解析security配置文件时,如果没有配置会将此设置为默认值。

  1.  
    package com.mango.jtt.springSecurity;
  2.  
     
  3.  
    import java.io.IOException;
  4.  
     
  5.  
    import javax.servlet.ServletException;
  6.  
    import javax.servlet.http.HttpServletRequest;
  7.  
    import javax.servlet.http.HttpServletResponse;
  8.  
     
  9.  
    import org.springframework.beans.factory.annotation.Autowired;
  10.  
    import org.springframework.security.core.Authentication;
  11.  
    import org.springframework.security.core.userdetails.UserDetails;
  12.  
    import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
  13.  
    import org.springframework.stereotype.Component;
  14.  
     
  15.  
    import com.mango.jtt.po.MangoUser;
  16.  
    import com.mango.jtt.service.IUserService;
  17.  
     
  18.  
    /**
  19.  
    * 登录后操作
  20.  
    *
  21.  
    * @author HHL
  22.  
    * @date
  23.  
    *
  24.  
    */
  25.  
    @Component
  26.  
    public class MyAuthenticationSuccessHandler extends
  27.  
    SavedRequestAwareAuthenticationSuccessHandler {
  28.  
     
  29.  
    @Autowired
  30.  
    private IUserService userService;
  31.  
     
  32.  
    @Override
  33.  
    public void onAuthenticationSuccess(HttpServletRequest request,
  34.  
    HttpServletResponse response, Authentication authentication)
  35.  
    throws IOException, ServletException {
  36.  
     
  37.  
    // 认证成功后,获取用户信息并添加到session中
  38.  
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
  39.  
    MangoUser user = userService.getUserByName(userDetails.getUsername());
  40.  
    request.getSession().setAttribute( "user", user);
  41.  
     
  42.  
    super.onAuthenticationSuccess(request, response, authentication);
  43.  
     
  44.  
    }
  45.  
     
  46.  
     
  47.  
    }


认证失败则回到登录页,只不过多了error,配置为authentication-failure-url="/login?error" 控制类会对其进行处理

  1.  
    /**
  2.  
    *
  3.  
    */
  4.  
    package com.mango.jtt.controller;
  5.  
     
  6.  
    import org.springframework.stereotype.Controller;
  7.  
    import org.springframework.ui.Model;
  8.  
    import org.springframework.web.bind.annotation.RequestMapping;
  9.  
    import org.springframework.web.bind.annotation.RequestParam;
  10.  
     
  11.  
    /**
  12.  
    * @author HHL
  13.  
    *
  14.  
    * @date 2016年12月8日
  15.  
    *
  16.  
    * 用户控制类
  17.  
    */
  18.  
    @Controller
  19.  
    public class UserController {
  20.  
     
  21.  
    /**
  22.  
    * 显示登录页面用,主要是显示错误信息
  23.  
    *
  24.  
    * @param model
  25.  
    * @param error
  26.  
    * @return
  27.  
    */
  28.  
    @RequestMapping("/login")
  29.  
    public String login(Model model,
  30.  
    @RequestParam(value = "error", required = false) String error) {
  31.  
    if (error != null) {
  32.  
    model.addAttribute( "error", "用户名或密码错误");
  33.  
    }
  34.  
    return "login";
  35.  
    }
  36.  
    }

另外,从spring security3.2开始,默认就会启用csrf保护,本次将csrf保护功能禁用<csrf disabled="true" />,防止页面中没有配置crsf而报错“Could not verify the provided CSRF token because your session was not found.”,如果启用csrf功能的话需要将login和logout以及上传功能等都需要进行相应的设置,因此这里先禁用csrf保护功能具体可参考spring-security4.1.3官方文档

四,后面会对认证过程,以及如何认证的进行详细说明。

完整代码:http://download.csdn.net/detail/honghailiang888/9705858

或 https://github.com/honghailiang/SpringMango

猜你喜欢

转载自www.cnblogs.com/cfas/p/9395918.html