SpringSecurity

一、Spring Security介绍

       1.Spring Security 是 Spring 项目组中用来提供安全认证服务的框架,安全包括两个主要操作:

           1)“认证”,是为用户建立一个他所声明的主体。主题一般式指用户,设备或可以在你系 统中执行动作的其他系统。

           2)“授权”,指的是一个用户能否在你的应用中执行某个操作,在到达授权判断之前,身份的主题已经由 身份验证过程建立了。

        2.Maven依赖

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.0.1.RELEASE</version>
        </dependency>

二、Spring Security使用数据库认证 

          1.使用UserDetails、UserDetailsService来完成操作

             *  UserDetails

                UserDetails是一个接口,我们可以认为UserDetails作用是于封装当前进行认证的用户信息,但由于其是一个 接口,所以我们可以对其进行实现,也可以使用Spring Security提供的一个UserDetails的实现类User来完成 操作 

             *  UserDetailsService

三、登陆案例

        1.导入依赖

        2.配置SpringSecurity.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <!--开启JSR-250权限控制的注解-->
    <!--使用支持表达式的注解控制权限
        @PreAuthorize
    -->
    <security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"/>

   <!--配置jsp页面权限控制需要的配置-->
    <bean id="webSecurityExpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
    <!-- 配置不拦截的资源 -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/failer.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>

    <!--
        配置具体的规则
        auto-config="true"    不用自己编写登录的页面,框架提供默认登录页面
        use-expressions="false"    是否使用SPEL表达式
    -->
    <security:http auto-config="true" use-expressions="false">
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <!-- 定义跳转的具体的页面 -->
        <security:form-login
                login-page="/login.jsp"
                login-processing-url="/login.do"
                default-target-url="/index.jsp"
                authentication-failure-url="/failer.jsp"
                authentication-success-forward-url="/pages/main.jsp"
        />

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!-- 用户退出 -->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />

    </security:http>

    <!-- 切换成数据库中的用户名和密码 -->
    <security:authentication-manager>
<!--找到相应的service--> <security:authentication-provider user-service-ref="userService"> <!-- 配置加密的方式 --> <security:password-encoder ref="passwordEncoder"/> </security:authentication-provider> </security:authentication-manager> <!-- 配置加密类 --> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> </beans>

        3. 在web.xml中配置SpringSecurity

 <!-- 配置加载类路径的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml,classpath*:spring-security.xml</param-value>
  </context-param>

<!--springSecurity的配置-->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

          4.IUserService中继承UserDetailsService

public interface IUserService extends UserDetailsService{

}

          5.在IUserService的实现类UserService中实现相应的方法

public class UserServiceImpl implements IUserService {
      //用户登陆
    @Override
    public UserDetails loadUserByUsername(String username) {
        UserInfo userInfo = null;
        try {
            userInfo = userDao.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //创建springSecurity提供的User对象,把自己数据库中的用户(userInfo)对象封装到UserDetails的user中
//用户名、密码、用户状态(可用为1,不可用为0)、用户角色的集合。 User user = new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus()==0?false:true,true,true,true,getAuthority(userInfo.getRoles())); return user; } //返回一个list集合,集合中装入角色描述 public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){ List<SimpleGrantedAuthority> list=new ArrayList<>(); for(Role role:roles){ list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName())); } return list; } }

四、服务器端方法级权限控制

        1.Spring Security在方法的权限控制上 支持三种类型的注解:JSR-250注解、@Secured注解和支持表达式的注解;

        2.JSR-250注解的使用:

             1)需要在SpringSecurity.xml中开启注解

<!--开启JSR-250权限控制的注解-->
    <security:global-method-security jsr250-annotations="enabled"></security:global-method-security>
 

              2)在需要加权限的方法上使用注解

                     *  @RolesAllowed表示访问对应方法时必须具有具有的角色       

//只有拥有ADMIN角色的用户才可以使用该方法
@RolesAllowed("ADMIN")
public ModelAndView findAll() throws Exception {
.....
}

              3)  在pom.xml中导入依赖             

<dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>

       3.@Secured注解(SpringSecurity本身提供的)

           1)需要在SpringSecurity.xml中开启注解          

<!--使用@Secured注解控制权限-->
    <security:global-method-security secured-annotations="enabled"></security:global-method-security>

           2)在需要加权限的方法上使用注解

//只有拥有ADMIN角色的用户才可以使用该方法
@Secured("ROLE_ADMIN")
public ModelAndView findAll() throws Exception {
.....
}

    注意:在使用JSR250注解时,可以省略POLRE_的前缀,而使用@Secured时不能省略前缀

      4.支持表达式注解

              1)需要在SpringSecurity.xml中开启注解          

<!--使用支持表达式的注解控制权限
        @PreAuthorize
    -->
    <security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"/>

               2)在需要加权限的方法上使用注解

//只用拥有ADMIN角色的用户才可以使用此方法的操作
@PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findAll() throws Exception {
         ........
}

//只用用户名为tom的用户才可进行此操作
@PreAuthorize("authentication.principal.username == 'tom'")
    public String save() throws Exception {
         ........
}

                

原文地址:https://www.cnblogs.com/cqyp/p/12654921.html