资讯专栏INFORMATION COLUMN

spring系列---Security 安全框架使用和文件上传FastDFS

K_B_Z / 2320人阅读

摘要:框架入门简介是一个能够为基于的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

1.Spring Security框架入门 1.1 Spring Security简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
1.2 Spring Security入门小Demo 1.2.1最简单Demo
(1)创建工程spring_security_demo ,pom.xml内容

    4.0.0
    cn.itcast.demo
    spring-security-demo
    war
    0.0.1-SNAPSHOT
    
        4.2.4.RELEASE
    
    
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-test
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework.security
            spring-security-web
            4.1.0.RELEASE
        
        
            org.springframework.security
            spring-security-config
            4.1.0.RELEASE
        
        
            javax.servlet
            servlet-api
            2.5
            provided
        
    
    
              
          
          
                org.apache.maven.plugins
                maven-compiler-plugin
                3.2
                
                    1.7
                    1.7
                    UTF-8
                
                
          
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                
                    
                    9090
                    
                    /
                
            
         
    
(2)创建web.xml 

        
       
        contextConfigLocation
        classpath:spring-security.xml
     
     
        
            org.springframework.web.context.ContextLoaderListener
        
         
       
        springSecurityFilterChain           org.springframework.web.filter.DelegatingFilterProxy  
       
       
        springSecurityFilterChain  
        /*  
         
(3)创建index.html   内容略(IDEA的index.jsp也可用)

(4)创建spring 配置文件spring-security.xml



    
    
        
            
    

    
    
        
            
                
                    
            
    
**配置说明**:
    intercept-url 表示拦截页面   
    //  表示的是该目录下的资源,只包括本级目录不包括下级目录
    // 表示的是该目录以及该目录下所有级别子目录的资源
    form-login  为开启表单登陆

use-expressions 为是否使用使用 Spring 表达式语言( SpEL ),默认为true ,如果开启,则拦截的配置写成以下形式

此时启动localhost:9090就能看到登陆页面

2项目中的配置及使用

pom.xml

    
        
        
            com.yh
            yh_common
            1.0-SNAPSHOT
        
        
        
            org.springframework
            spring-context
        
        
            org.springframework
            spring-beans
        
        
            org.springframework
            spring-webmvc
        
        
            org.springframework
            spring-jdbc
        
        
            org.springframework
            spring-aspects
        
        
            org.springframework
            spring-jms
        
        
            org.springframework
            spring-context-support
        
        
            org.springframework
            spring-test
        
        
        
            org.springframework.security
            spring-security-web
        
        
            org.springframework.security
            spring-security-config
        
        
        
            com.alibaba
            dubbo
        
        
            org.apache.zookeeper
            zookeeper
        
        
            com.github.sgroschupf
            zkclient
        
        
            junit
            junit
        
        
            com.alibaba
            fastjson
        
        
            org.javassist
            javassist
            3.23.1-GA
        
        
            commons-codec
            commons-codec
        
        
            javax.servlet
            servlet-api
            provided
        
        
            com.yh
            yh_sellergoods_interface
            1.0-SNAPSHOT
        

        
        
            org.csource.fastdfs
            fastdfs
        
        
            commons-fileupload
            commons-fileupload
        
    

    
        
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    
                    9102
                    
                    /
                
            
        
    

web.xml



    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
        
            forceEncoding
            true
        
    
    
        CharacterEncodingFilter
        /*
    


    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath:spring/spring*.xml
        
        2
    

    
        springmvc
        *.do
    

    
        contextConfigLocation
        
        classpath:spring/spring*.xml,classpath*:spring/applicationContext*.xml
    
    
        
            org.springframework.web.context.ContextLoaderListener
        
    


    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
    
    
        springSecurityFilterChain
        /*
    

pringmvc.xml



    

    
    
        
        
        
    

    
        
            
                
                
                    
                        WriteMapNullValue
                        WriteDateUseDateFormat
                    
                
            
        
    

    
    
    
    

Spring-secuity.xml




    
    
    
    
    
    
    
    


    
    
    
        
        
        
        
        
        
        
        
        
            
            
        
    

    
        
        
            
        
    


    
    
    
    


    
    

com.yh.service.UserDetailServiceImpl.java

package com.yh.page.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yh.pojo.TbSeller;
import com.yh.sellergoods.service.SellerService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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;

/
  实现userdetail接口 用于验证前台输入用户信息匹配
  

需要让接口扫描到这个类 / @Component public class UserDetailServiceImpl implements UserDetailsService { //远程调用dubbo提供的服务 但是此时还没有 @Reference public SellerService sellerService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { TbSeller seller = sellerService.findOne(username); System.out.println(seller); //没找到用户 或者用户没有通过审核 if (seller == null || !"1".equals(seller.getStatus())) { return null; } ArrayList list = new ArrayList<>(); list.add(new SimpleGrantedAuthority("ROLE_SELLER")); return new User(username, seller.getPassword(), list); } }

config/fdfs_client.conf

# connect timeout in seconds
# default value is 30s
connect_timeout=30

# network timeout in seconds
# default value is 30s
network_timeout=60

# the base path to store log files
base_path=/home/fastdfs

# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
tracker_server=172.16.224.128:22122

#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info

# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false

# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600

# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false

# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false

# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf


#HTTP settings
http.tracker_server_port=80

#use "#include" directive to include HTTP other settiongs
##include http.conf

com.yh.shop.controller.UploadController

package com.yh.shop.controller;
import entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.FastDFSClient;
//  文件上传controller
@RestController
 public class UploadController {
  @Value("${FILE_SERVER_URL}")
  public String FILE_SERVER_URL;
   
    @RequestMapping("upload")
    public Result upload(MultipartFile file) {
        //文件名称
        //String originalFilename = file.getOriginalFilename();
        //获取扩展名称
        //String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        try {
            //创建fastdfs客户端
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
            //返回图片路径
            String path = fastDFSClient.uploadFile(file.getBytes(), extName);
            System.out.println(path);
            return new Result(true, FILE_SERVER_URL + path);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "上传失败");
        }
        
    }
    
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77085.html

相关文章

  • 把「策略模式」应用到实际项目中

    摘要:阅读原文把策略模式应用到实际项目中无论你知不知道这个设计模式,但必定在项目中都似曾相识。文件存储的方式不同,同时文件的获取和删除也不同保存,获取,删除后的响应也是相同的,也不考虑了。此时引入是解决问题的最佳方式。 阅读原文:把「策略模式」应用到实际项目中 无论你知不知道这个设计模式,但必定在项目中都似曾相识。倘若仅仅聊理论必然枯燥乏味,只有理论和实战相结合方可达到人剑合一的境界。 首先...

    LeviDing 评论0 收藏0
  • Spring Security

    摘要:框架具有轻便,开源的优点,所以本译见构建用户管理微服务五使用令牌和来实现身份验证往期译见系列文章在账号分享中持续连载,敬请查看在往期译见系列的文章中,我们已经建立了业务逻辑数据访问层和前端控制器但是忽略了对身份进行验证。 重拾后端之Spring Boot(四):使用JWT和Spring Security保护REST API 重拾后端之Spring Boot(一):REST API的搭建...

    keelii 评论0 收藏0
  • SpringSecurity系列01】初识SpringSecurity

    摘要:什么是是一个能够为基于的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它来自于,那么它与整合开发有着天然的优势,目前与对应的开源框架还有。通常大家在做一个后台管理的系统的时候,应该采用判断用户是否登录。 ​ 什么是SpringSecurity ? ​ Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全...

    elva 评论0 收藏0
  • 农民进城之初尝FastDFS搭建图片分布式系统

    摘要:新建文件夹尝试启动为默认监听端口看到已经在监听端口,说明启动成功。修改修改为的路径,我这里为修改为你的监听的和端口号,我这里为保存退出。即为上传图片成功 于前不久,公司论坛的图片终于将服务器给挤爆了,已经达到了恐怖的34G,服务器总容量才40G。如果直接加硬盘的话,那么discuz中的逻辑几乎就要全改,所以不行。如果将所有图片扔到对象存储的话,那么这会是一大笔支出(虽然钱不是我出),所...

    LiveVideoStack 评论0 收藏0
  • 农民进城之初尝FastDFS搭建图片分布式系统

    摘要:新建文件夹尝试启动为默认监听端口看到已经在监听端口,说明启动成功。修改修改为的路径,我这里为修改为你的监听的和端口号,我这里为保存退出。即为上传图片成功 于前不久,公司论坛的图片终于将服务器给挤爆了,已经达到了恐怖的34G,服务器总容量才40G。如果直接加硬盘的话,那么discuz中的逻辑几乎就要全改,所以不行。如果将所有图片扔到对象存储的话,那么这会是一大笔支出(虽然钱不是我出),所...

    Cheriselalala 评论0 收藏0

发表评论

0条评论

K_B_Z

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<