SpringSecurity安全框架的应用示范

POM文件

            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-webartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-configartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframework.securitygroupId>
            <artifactId>spring-security-taglibsartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>

主配置文件:spring-security.xml

SpringSecurity安全框架的应用示范_第1张图片


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/mvc
						http://www.springframework.org/schema/mvc/spring-mvc.xsd
						http://code.alibabatech.com/schema/dubbo
						http://code.alibabatech.com/schema/dubbo/dubbo.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context.xsd
                     http://www.springframework.org/schema/security
                     http://www.springframework.org/schema/security/spring-security.xsd">

    
    
    
    <security:http security="none" pattern="/login.html">security:http>
    <security:http security="none" pattern="/css/**">security:http>
    <security:http security="none" pattern="/img/**">security:http>
    <security:http security="none" pattern="/js/**">security:http>
    <security:http security="none" pattern="/plugins/**">security:http>
    

    
    <security:http auto-config="true" use-expressions="true">
        <security:headers>
            
            <security:frame-options policy="SAMEORIGIN">security:frame-options>
        security:headers>
        
        
        
        <security:intercept-url pattern="/pages/**"  access="isAuthenticated()" />

        
        
        <security:form-login
                login-page="/login.html"
                username-parameter="username"
                password-parameter="password"
                login-processing-url="/login.do"
                default-target-url="/pages/main.html"
                authentication-failure-url="/login.html">security:form-login>

        
        <security:csrf disabled="true">security:csrf>

        
        <security:logout logout-url="/logout.do"
                         logout-success-url="/login.html" invalidate-session="true"/>

    security:http>

    
    <security:authentication-manager>
        
        <security:authentication-provider user-service-ref="springSecurityUserService">
            
            
            <security:password-encoder ref="passwordEncoder">security:password-encoder>
        security:authentication-provider>
    security:authentication-manager>

    
    <bean id="passwordEncoder"
          class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

    
    <security:global-method-security pre-post-annotations="enabled" />
beans>

web.xml配置(引入spring-security.xml)

SpringSecurity安全框架的应用示范_第2张图片



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>

  
  <filter>
    
    <filter-name>springSecurityFilterChainfilter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
  filter>
  
  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
    <init-param>
      <param-name>forceEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChainfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xml,classpath:spring-security.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>*.dourl-pattern>
  servlet-mapping>
web-app>

配置SpringSecurity安全框架的服务类

该服务类用于查询一个数据库,数据库中存有权限账号,如果存在这个权限账号,SpringSecurity安全框架才会允许访问.
而每个数据库中的账号也有各自不同的权限
SpringSecurity安全框架的应用示范_第3张图片

用户授权访问层:SpringSecurityUserService.java

SpringSecurity安全框架的应用示范_第4张图片

package cn.health.service;

import cn.health.pojo.Permission;
import cn.health.pojo.Role;
import cn.health.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;

/**
 * SpringSecurity安全框架的服务层
 */
@Component //@controller 控制器(注入服务)
public class SpringSecurityUserService implements UserDetailsService {
     //实现'UserDetailsService'这个这个由安全框架提供的接口.

    @Reference
    private UserService userServiceObj;

    //根据用户名来查询数据库,进而获取到该用户的信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     
        User userObj = userServiceObj.findByUsername(username);
        if (userObj == null){
     //如果用户名不存在,则返回安全框架的UserDetails对象为空,告诉安全框架不存在此用户.
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();

        //如果不为空,则说明存在此用户,届时动态地为当前所查询到的用户来授权.
        Set<Role> roles = userObj.getRoles();
        for (Role role : roles) {
     
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            //遍历权限集合,为用户授权
            for (Permission permission : permissions) {
     
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User sucerityObj = new org.springframework.security.core.userdetails.User(username,userObj.getPassword() ,list );
        return sucerityObj;
    }
}

用户权限查询层(仅参考)

仅参考,具体还要看权限表结构的不同而不同.

接口:UserService.java

package cn.health.service;

import cn.health.pojo.User;

public interface UserService {
     

    // 根据用户名来查询数据库获取用户信息,此处的User返回值是Poje实体类的User,而非是SpringSecurity的User类.
    public User findByUsername(String username);

}

实现类:UserServiceImp.java

package cn.health.service;

import cn.health.dao.PermissionDao;
import cn.health.dao.RoleDao;
import cn.health.dao.UserDao;
import cn.health.pojo.Permission;
import cn.health.pojo.Role;
import cn.health.pojo.User;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImp implements UserService {
     
    @Autowired
    private UserDao userDaoObj;
    @Autowired
    private RoleDao roleDaoObj;
    @Autowired
    private PermissionDao permissionDaoObj;

     /* 根据用户名来查询数据库获取用户信息,此处的User返回值是Poje实体类的User,而非是SpringSecurity的User类.
      即:根据用户名获取用户所关联的角色信息,同时需要查看角色所关联的权限信息*/

    @Override
    public User findByUsername(String username) {
     
        //先查询用户基本信息
      User userResult =  userDaoObj.findByUsername(username);
        if (userResult==null){
     
            return null;
        }
        //再根据查询用户所对应的角色
       Set<Role> rolesResult = roleDaoObj.findByUserid(userResult.getId());

        //再根据角色查询所对应的权限
        for (Role role : rolesResult) {
     
            Integer id = role.getId();
          Set<Permission> permissionsResult =  permissionDaoObj.findByRoleID(id);
          role.setPermissions(permissionsResult);
        }
        userResult.setRoles(rolesResult);
        return userResult;
    }
}

被安全框架所管理应用的Controller层

SpringSecurity安全框架的应用示范_第5张图片

SpringSecurity安全框架的应用示范_第6张图片

代码仅示例.
在要被SpringSecurity框架所要管理的web方法上使用PreAuthorize注解来表明如果访问该web方法需要哪些权限.
格式:
PreAuthorize("hasAuthority('数据库表中所存在的权限名')")
例如:

PreAuthorize("hasAuthority('CHECKITEM_ADD')")
package cn.health.controller;

import cn.health.constant.MessageConstant;
import cn.health.entity.PageResult;
import cn.health.entity.QueryPageBean;
import cn.health.entity.Result;
import cn.health.pojo.CheckItem;
import cn.health.service.CheckItemService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/checkitem")
public class CheckItemController {
     

    @Reference
    private CheckItemService checkItemServiceObj;

    //新增检查项
    @PreAuthorize("hasAuthority('CHECKITEM_ADD')")//权限校验
    @RequestMapping("/add.do")
    public Result checkitemAdd(@RequestBody CheckItem checkItemObj) {
     
        System.out.println(checkItemObj);
        try {
     
            checkItemServiceObj.add(checkItemObj);
        } catch (Exception e) {
     
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);

    }

    /**
     * 获取检查项页面数据
     * @param queryPageBeanObj
     * @return
     */
    @PreAuthorize("hasAuthority('CHECKITEM_QUERY')")//权限校验
    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBeanObj){
     

        PageResult pageResultObj = checkItemServiceObj.findPage(queryPageBeanObj);

        return pageResultObj;
    }


    /**
     * 删除检查项
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('CHECKITEM_DELETE')")//权限校验
    @RequestMapping("/delete.do")
    public Result checkitemDelete(Integer id){
     
        System.out.println(id);
        try {
     
            checkItemServiceObj.deleteById(id);
            return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS );
        } catch (Exception e) {
     
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_CHECKITEM_FAIL );
        }


    }

    /**
     * 回显编辑窗口信息
     * @param id
     * @return
     */

    @RequestMapping("/show.do")
    public CheckItem showCheckItem(Integer id){
     
        CheckItem showResult = checkItemServiceObj.show(id);

        return showResult;


    }

    /**
     *更新编辑信息
     * @param checkItemObj
     * @return
     */
    @PreAuthorize("hasAuthority('CHECKITEM_EDIT')")//权限校验
    @RequestMapping("/paramupdate.do")
    public Result paramUpdate(@RequestBody CheckItem checkItemObj){
     
        System.out.println(checkItemObj);
        try {
     
            checkItemServiceObj.paramUpdate(checkItemObj);
            return new Result(true,MessageConstant.EDIT_CHECKITEM_SUCCESS );
        } catch (Exception e) {
     
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_CHECKITEM_FAIL );
        }


    }



}

详细文档下载:
链接: https://pan.baidu.com/s/1f9kU70oVToybadnnTHu4vg 提取码: mfc8

你可能感兴趣的:(Spring)