本项目内容出自书籍《SpringBoot企业级开发教程》中第七章的项目内容,有兴趣的同学可以网上搜索一下,这里仅仅作为项目记录,将不会进行代码解释
sql数据库
# 选择使用数据库
USE springbootdata;
# 创建表t_customer并插入相关数据
DROp TABLE IF EXISTS `t_customer`;
CREATE TABLE `t_customer` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(200) DEFAULT NULL,
`password` varchar(200) DEFAULT NULL,
`valid` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t_customer` VALUES ('1', 'shitou', '$2a$10$5ooQI8dir8jv0/gCa1Six.GpzAdIPf6pMqdminZ/3ijYzivCyPlfK', '1');
INSERT INTO `t_customer` VALUES ('2', '李四', '$2a$10$5ooQI8dir8jv0/gCa1Six.GpzAdIPf6pMqdminZ/3ijYzivCyPlfK', '1');
# 创建表t_authority并插入相关数据
DROP TABLE IF EXISTS `t_authority`;
CREATE TABLE `t_authority` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`authority` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `t_authority` VALUES ('1', 'ROLE_common');
INSERT INTO `t_authority` VALUES ('2', 'ROLE_vip');
# 创建表t_customer_authority并插入相关数据
DROP TABLE IF EXISTS `t_customer_authority`;
CREATE TABLE `t_customer_authority` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`customer_id` int(20) DEFAULT NULL,
`authority_id` int(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `t_customer_authority` VALUES ('1', '1', '1');
INSERT INTO `t_customer_authority` VALUES ('2', '2', '2');
# 记住我功能中创建持久化Token存储的数据表
create table persistent_logins (username varchar(64) not null,
series varchar(64) primary key,
token varchar(64) not null,
last_used timestamp not null);
pom.xml
org.thymeleaf.extras thymeleaf-extras-springsecurity5 org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-maven-plugin
application.properties
# MySQL数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默认true spring.thymeleaf.cache=false
实体类:
Customer
package com.demo.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity(name = "t_customer")
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String password;
(省略getter、setter、toString方法)
Authority
package com.demo.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity(name = "t_authority ")
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String authority ;
(省略getter、setter、toString方法)
AuthorityRespository
package com.demo.repository; import com.demo.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface AuthorityRepository extends JpaRepository{ @Query(value = "select a.* from t_customer c,t_authority a,t_customer_authority ca where ca.customer_id=c.id and ca.authority_id=a.id and c.username =?1",nativeQuery = true) public List findAuthoritiesByUsername(String username); }
CustomerRepository
package com.demo.repository; import com.demo.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; public interface CustomerRepository extends JpaRepository{ Customer findByUsername(String username); }
CustomerService
package com.demo.service;
import com.demo.domain.Customer;
import com.demo.domain.Authority;
import com.demo.repository.CustomerRepository;
import com.demo.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CustomerService {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private RedisTemplate redisTemplate;
// 业务控制:使用唯一用户名查询用户信息
public Customer getCustomer(String username){
Customer customer=null;
Object o = redisTemplate.opsForValue().get("customer_"+username);
if(o!=null){
customer=(Customer)o;
}else {
customer = customerRepository.findByUsername(username);
if(customer!=null){
redisTemplate.opsForValue().set("customer_"+username,customer);
}
}
return customer;
}
// 业务控制:使用唯一用户名查询用户权限
public List getCustomerAuthority(String username){
List authorities=null;
Object o = redisTemplate.opsForValue().get("authorities_"+username);
if(o!=null){
authorities=(List)o;
}else {
authorities=authorityRepository.findAuthoritiesByUsername(username);
if(authorities.size()>0){
redisTemplate.opsForValue().set("authorities_"+username,authorities);
}
}
return authorities;
}
}
UserDetailsServiceImpl
package com.demo.service;
import com.demo.domain.Authority;
import com.demo.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private CustomerService customerService;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
// 通过业务方法获取用户及权限信息
Customer customer = customerService.getCustomer(s);
List authorities = customerService.getCustomerAuthority(s);
// 对用户权限进行封装
List list = authorities.stream()
.map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
.collect(Collectors.toList());
// 返回封装的UserDetails用户详情类
if(customer!=null){
UserDetails userDetails= new User(customer.getUsername(),customer.getPassword(),list) ;
return userDetails;
} else {
// 如果查询的用户不存在(用户名不存在),必须抛出此异常
throw new UsernameNotFoundException("当前用户不存在!");
}
// User user = new User(customer.getUsername(), customer.getPassword(), list);
// return user;
}
}
SecurityConfig
package com.demo.config;
import com.demo.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import javax.sql.DataSource;
@EnableWebSecurity //开启MVC Security安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
//3.
private UserDetailsServiceImpl userDetailsService;
@Autowired
private DataSource dataSource;
//书中7-3到7-4内容
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//密码需要设置编码器
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//1.使用内存用户信息,作为测试使用
// auth.inMemoryAuthentication().passwordEncoder(encoder)
// .withUser("shitou").password(encoder.encode("123456")).roles("common")
// .and()
// .withUser("admin").password(encoder.encode("admin")).roles("vip");
// //2.使用JDBC进行身份验证
// String userSQL = "select username,password,valid from t_customer where username = ?";
// String authoritySQL = "select c.username,a.authority " +
// "from t_customer c,t_authority a,t_customer_authority ca " +
// "where ca.customer_id = c.id and ca.authority_id = a.id and c.username = ?";
// auth.jdbcAuthentication().passwordEncoder(encoder)
// .dataSource(dataSource)
// .usersByUsernameQuery(userSQL)
// .authoritiesByUsernameQuery(authoritySQL);
//3.使用UserDetailsService进行身份认证
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests().antMatchers("/").permitAll()
//需要对static文件夹下静态资源进行统一放行
.antMatchers("/login/**").permitAll()
.antMatchers("/detail/common/**").hasRole("common")
.antMatchers("/detail/vip/**").hasRole("vip")
.anyRequest().authenticated()
.and()
.formLogin();
//自定义用户登陆控制
http.formLogin().loginPage("/userLogin").permitAll()
.usernameParameter("name")
.passwordParameter("pwd")
.defaultSuccessUrl("/")
.failureUrl("/userLogin?error");
//自定义用户退出控制
http.logout()
.logoutUrl("/mylogout")
.logoutSuccessUrl("/");
//定制Remember-me记住我功能
http.rememberMe()
.rememberMeParameter("rememberme")
.tokenValiditySeconds(200)
//对Cookie信息进行持久化管理
.tokenRepository(tokenRepository());
//可以关闭Spring Security默认开启的CSRF防护功能
// http.csrf().disable();
}
@Bean
public JdbcTokenRepositoryImpl tokenRepository(){
JdbcTokenRepositoryImpl jr = new JdbcTokenRepositoryImpl();
jr.setDataSource(dataSource);
return jr;
}
}
CSRFController
package com.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class CSRFController {
//向用户修改页跳转
@GetMapping("/toUpdate")
public String toUpdate(){
return "/csrf/csrfTest";
}
//用户修改提交处理
@ResponseBody
@PostMapping(value = "/updateUser")
public String updateUser(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
System.out.println(username);
System.out.println(password);
String csrf_token = request.getParameter("_csrf");
System.out.println(csrf_token);
return "OK";
}
}
FileController
package com.demo.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
@Controller
public class FileController {
//影片详情页
@GetMapping("/detail/{type}/{path}")
public String toDetail(@PathVariable("type") String type,
@PathVariable("path") String path){
return "detail/"+type+"/"+path;
}
@GetMapping("/userLogin")
public String toLoginPage(){
return "login/login";
}
@GetMapping("/getuserBySession")
@ResponseBody
public void getUser(HttpSession session){
//从当前HttpSession获取绑定到此会话的所有对象名称
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()){
//获取httpSession中会话名称
String element = names.nextElement();
//获取HttpSession中的应用上下文
SecurityContextImpl attribute = (SecurityContextImpl) session.getAttribute(element);
System.out.println("element:"+element);
System.out.println("attribute:"+attribute);
//获取用户相关信息
Authentication authentication = attribute.getAuthentication();
UserDetails principal = (UserDetails) authentication .getPrincipal();
System.out.println(principal);
System.out.println("username:"+principal.getUsername());
}
}
@GetMapping("/getUserByContext")
@ResponseBody
public void getUser2(){
SecurityContext context = SecurityContextHolder.getContext();
//获取用户相关信息
Authentication authentication = context.getAuthentication();
UserDetails principal = (UserDetails) authentication.getPrincipal();
System.out.println(principal.getUsername());
}
}
index.html
>VIP专享影视直播厅 欢迎进入电影网站首页
游客您好,如果想查看电影请登录
您好,您的用户权限为,您有权观看以下电影
普通电影
自定义登陆login.html
用户登录界面
内容页
影片详情 返回我不是药神
简介:根据真实社会事件改编,一位不速之客的意外到访,打破了神油店老板程勇(徐峥 饰)的平凡人生, 他从一个交不起房租的男性保健品商贩,一跃成为印度仿制药“格列宁”的独家代理商。收获巨额利润的他,生活剧烈变化, 被病患们冠以“药神”的称号。但是,一场关于救赎的拉锯战也在波涛暗涌中慢慢展开……
影片详情 返回夏洛特烦恼
简介:《夏洛特烦恼》是开心麻花2012年首度推出的话剧,由闫非和彭大魔联合编剧、执导。 2013、2014、2015年仍在上演。该作讲述了一个普通人在穿越重回到高中校园并实现了种种梦想的不可思议的经历……
影片详情 返回速度与激情
简介:《速度与激情》是罗伯·科恩等执导,于2001年至2017年范·迪塞尔、保罗·沃克(已故)、 乔丹娜·布鲁斯特、米歇尔·罗德里格兹等主演的赛车题材的动作犯罪类电影,截至2018年,一共拍了八部。之后两部续集正式定档, 《速度与激情9》和《速度与激情10》分别于2020年4月10日和2021年4月2日上映……
影片详情 返回猩球崛起
简介:《猩球崛起》是科幻片《人猿星球》的前传,由鲁伯特·瓦耶特执导,詹姆斯·弗兰科,汤姆·费尔顿, 芙蕾达·平托,布莱恩·考克斯等主演。剧情主要讲述人猿进化为高级智慧生物、进而攻占地球之前的种种际遇,主题是带有警世性质的——人类疯狂的野心所产生的恶果。 影片获得了第39届安妮奖最佳真人电影角色动画奖等奖项,同时获得了奥斯卡最佳特效奖提名,但很遗憾,并没有获奖……
csrf.html
用户修改
至此整个项目完成



