简介
SpringSecurity是专门针对基于Spring项目的安全框架,充分利用了依赖注入和AOP来实现安全管控。
SpringSecurity框架有两个概念认证和授权,认证可以访问系统的用户,而授权则是用户可以访问的资源。
构建项目
- 访问地址:http://start.spring.io
- 添加Web、MySQL、JPA、Druid、Security、JSP依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gala</groupId>
<artifactId>security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>security</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--SpringSecurity -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--SpringDataJPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
新增配置文件application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
username: root
password: 123456
#配置监控统计拦截的filters
filters: stat,wall,log4j
#最大活跃数
maxActive: 20
#初始化数量
initialSize: 1
#最大连接等待超时时间
maxWait: 60000
#打开PSCache,并指定每个连接PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
#通过connectionProperties属性打开mergeSql功能
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
minldle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableldleTimeMillis: 300000
validationQuery: select 1 from dual
testWhiledle: true
testOnBorrow: false
testOnReturn: false
jpa:
properties:
hibernate:
show_sql: true
format_sql: true
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
建表及初始化数据
-- ----------------------------
-- Table structure for ss_user 用户
-- ----------------------------
DROP TABLE IF EXISTS `ss_user`;
CREATE TABLE `ss_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(10) DEFAULT NULL COMMENT '用户名称',
`password` varchar(10) DEFAULT NULL COMMENT '用户密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `ss_user`(`id`,`username`,`password`) values (1,'admin','123456'),(2,'user','123456');
-- ----------------------------
-- Table structure for ss_user 角色
-- ----------------------------
DROP TABLE IF EXISTS `ss_role`;
CREATE TABLE `ss_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`role_name` varchar(10) DEFAULT NULL COMMENT '角色名称',
`role_description` varchar(20) DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `ss_role`(`id`,`role_name`,`role_description`) values (1,'ROLE_USER','普通用户'),(2,'ROLE_ADMIN','管理员');
-- ----------------------------
-- Table structure for ss_user_role 用户角色关系
-- ----------------------------
DROP TABLE IF EXISTS `ss_user_role`;
CREATE TABLE `ss_user_role` (
`user_id` int(11) DEFAULT NULL COMMENT '用户ID',
`role_id` int(11) DEFAULT NULL COMMENT '角色ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `ss_user_role`(`user_id`,`role_id`) values (1,1),(1,2),(2,1);
创建实体类
- User.java
package com.gala.security.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* UserDetails是SpringSecurity验证框架内部提供的用户验证接口
*/
@Entity
@Table(name = "ss_user")
public class User implements Serializable, UserDetails {
private static final long serialVersionUID = -5445460877560833224L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@Transient
Collection<GrantedAuthority> authorities;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ss_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
private List<Role> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setAuthorities(Collection<GrantedAuthority> authorities) {
this.authorities = authorities;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
/**
* 将我们定义的角色列表添加到授权的列表内
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
List<Role> roles = getRoles();
for (Role role : roles) {
System.out.println("获取用户角色-->" + role.getRoleName());
auths.add(new SimpleGrantedAuthority(role.getRoleName()));
}
return auths;
}
}
- Role.java
package com.gala.security.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "ss_role")
public class Role implements Serializable {
private static final long serialVersionUID = -2550502360099906919L;
private Long id;
private String roleName;
private String roleDescription;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDescription() {
return roleDescription;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
}
}
创建接口
package com.gala.security.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import com.gala.security.entity.User;
public interface UserDao extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
SpringSecurity用户认证
密码加密
package com.gala.security;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(rawPassword.toString());
}
}
认证配置
package com.gala.security.service;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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.Service;
import com.gala.security.entity.User;
import com.gala.security.jpa.UserDao;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserDao userDao;
/**
* 自定义用户登录
*/
@SuppressWarnings("unchecked")
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if (user == null) {
System.out.println("获取用户信息" + username + "失败");
throw new UsernameNotFoundException("用户名:" + username + "不存在");
}
Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) user.getAuthorities();
user.setAuthorities(authorities);
System.out.println("获取用户" + username + "信息成功!");
return user;
}
}
配置SpringBoot内的MVC控制器跳转
package com.gala.security.conf;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置SpringBoot内的MVC控制器跳转
*/
@Configuration
public class MVCConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
新增控制器
package com.gala.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
新增JSP
- 登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<form action="/login" method="post">
用户名:<input type="text" name="username" /><br />
密码:<input type="text" name="password" /><br />
<input type="submit" value="登录" />
</form>
</body>
</html>
2.登录成功页面
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
<title>首页</title>
</head>
<body>
登录成功!
<sec:authorize access="hasRole('ROLE_ADMIN')">
您拥有管理员权限。
</sec:authorize>
<br />
<sec:authorize access="hasRole('ROLE_USER')">
您拥有用户权限。
</sec:authorize>
</body>
</html>
测试
启动项目,访问:http://127.0.0.1:8080/index
输入用户名密码admin/123456
网友评论