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
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, "上传失败");
}
}
}