赞
踩
文章目录
一、导入依赖
二、创建数据库
三、准备页面
四、配置application.properties
五、创建实体、Dao、Service和Controller
5.1 实体
5.2 Dao
5.3 Service
5.4 Controller
六、配置SpringSecurity
6.1 UserDetailsService
6.2 WebSecurityConfig
七、运行程序
一、导入依赖
导入 spring-boot-starter-security 依赖,在 SpringBoot 2.0 环境下默认使用的是 5.0 版本。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、创建数据库
一般权限控制有三层,即:用户<–>角色<–>权限,用户与角色是多对多,角色和权限也是多对多。这里我们先暂时不考虑权限,只考虑用户<–>角色。
创建用户表sys_user:
CREATE TABLE `sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建权限表sys_role:
CREATE TABLE `sys_role` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建用户-角色表sys_user_role:
CREATE TABLE `sys_user_role` (
`user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `fk_role_id` (`role_id`),
CONSTRAINT `fk_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
初始化一下数据:
INSERT INTO `sys_role` VALUES ('1', 'ROLE_ADMIN');
INSERT INTO `sys_role` VALUES ('2', 'ROLE_USER');
INSERT INTO `sys_user` VALUES ('1', 'admin', '123');
INSERT INTO `sys_user` VALUES ('2', 'jitwxs', '123');
INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('2', '2');
博主有话说:
这里的权限格式为ROLE_XXX,是Spring Security规定的,不要乱起名字哦。
三、准备页面
因为是示例程序,页面越简单越好,只用于登陆的login.html以及用于登陆成功后的home.html,将其放置在 resources/static 目录下:
(1)login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>
<h1>登陆</h1>
<form method="post" action="/login">
<div>
用户名:<input type="text" name="username">
</div>
<div>
密码:<input type="password" name="password">
</div>
<div>
<button type="submit">立即登陆</button>
</div>
</form>
</body>
</html>
博主有话说:
用户的登陆认证是由Spring Security进行处理的,请求路径默认为/login,用户名字段默认为username,密码字段默认为password
(2)home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登陆成功</h1>
<a href="/admin">检测ROLE_ADMIN角色</a>
<a href="/user">检测ROLE_USER角色</a>
<button οnclick="window.location.href='/logout'">退出登录</button>
</body>
</html>
四、配置application.properties
在配置文件中配置下数据库连接:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#开启Mybatis下划线命名转驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
五、创建实体、Dao、Service和Controller
5.1 实体
(1)SysUser
public class SysUser implements Serializable{
static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String password;
// 省略getter/setter
}
(2)SysRole
public class SysRole implements Serializable {
static final long serialVersionUID = 1L;
private Integer id;
private String name;
// 省略getter/setter
}
(3)SysUserRole
public class SysUserRole implements Serializable {
static final long serialVersionUID = 1L;
private Integer userId;
private Integer roleId;
// 省略getter/setter
}
5.2 Dao
(1)SysUserMapper
@Mapper
public interface SysUserMapper {
@Select("SELECT * FROM sys_user WHERE id = #{id}")
SysUser selectById(Integer id);
@Select("SELECT * FROM sys_user WHERE name = #{name}")
SysUser selectByName(String name);
}
(2)SysRoleMapper
@Mapper
public interface SysRoleMapper {
@Select("SELECT * FROM sys_role WHERE id = #{id}")
SysRole selectById(Integer id);
}
(3)SysUserRoleMapper
@Mapper
public interface SysUserRoleMapper {
@Select("SELECT * FROM sys_user_role WHERE user_id = #{userId}")
List<SysUserRole> listByUserId(Integer userId);
}
5.3 Service
(1)SysUserService
@Service
public class SysUserService {
@Autowired
private SysUserMapper userMapper;
public SysUser selectById(Integer id) {
return userMapper.selectById(id);
}
public SysUser selectByName(String name) {
return userMapper.selectByName(name);
}
}
(2)SysRoleService
@Service
public class SysRoleService {
@Autowired
private SysRoleMapper roleMapper;
public SysRole selectById(Integer id){
return roleMapper.selectById(id);
}
}
(3)SysUserRoleService
@Service
public class SysUserRoleService {
@Autowired
private SysUserRoleMapper userRoleMapper;
public List<SysUserRole> listByUserId(Integer userId) {
return userRoleMapper.listByUserId(userId);
}
}
5.4 Controller
@Controller
public class LoginController {
private Logger logger = LoggerFactory.getLogger(LoginController.class);
@RequestMapping("/")
public String showHome() {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
logger.info("当前登陆用户:" + name);
return "home.html";
}
@RequestMapping("/login")
public String showLogin() {
return "login.html";
}
@RequestMapping("/admin")
@ResponseBody
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String printAdmin() {
return "如果你看见这句话,说明你有ROLE_ADMIN角色";
}
@RequestMapping("/user")
@ResponseBody
@PreAuthorize("hasRole('ROLE_USER')")
public String printUser() {
return "如果你看见这句话,说明你有ROLE_USER角色";
}
}
博主有话说:
如代码所示,获取当前登录用户:SecurityContextHolder.getContext().getAuthentication()
@PreAuthorize 用于判断用户是否有指定权限,没有就不能访问
————————————————
六、配置SpringSecurity
6.1 UserDetailsService
首先我们需要自定义 UserDetailsService ,将用户信息和权限注入进来。
我们需要重写 loadUserByUsername 方法,参数是用户输入的用户名。返回值是UserDetails,这是一个接口,一般使用它的子类org.springframework.security.core.userdetails.User,它有三个参数,分别是用户名、密码和权限集。
实际情况下,大多将 DAO 中的 User 类继承 org.springframework.security.core.userdetails.User 返回。
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private SysUserService userService;
@Autowired
private SysRoleService roleService;
@Autowired
private SysUserRoleService userRoleService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Collection<GrantedAuthority> authorities = new ArrayList<>();
// 从数据库中取出用户信息
SysUser user = userService.selectByName(username);
// 判断用户是否存在
if(user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
// 添加权限
List<SysUserRole> userRoles = userRoleService.listByUserId(user.getId());
for (SysUserRole userRole : userRoles) {
SysRole role = roleService.selectById(userRole.getRoleId());
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
// 返回UserDetails实现类
return new User(user.getName(), user.getPassword(), authorities);
}
}
6.2 WebSecurityConfig
该类是 Spring Security 的配置类,该类的三个注解分别是标识该类是配置类、开启 Security 服务、开启全局 Securtiy 注解。
首先将我们自定义的 userDetailsService 注入进来,在 configure() 方法中使用 auth.userDetailsService() 方法替换掉默认的 userDetailsService。
这里我们还指定了密码的加密方式(5.0 版本强制要求设置),因为我们数据库是明文存储的,所以明文返回即可,如下所示:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
});
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 如果有允许匿名的url,填在下面
// .antMatchers().permitAll()
.anyRequest().authenticated()
.and()
// 设置登陆页
.formLogin().loginPage("/login")
// 设置登陆成功页
.defaultSuccessUrl("/").permitAll()
// 自定义登陆用户名和密码参数,默认为username和password
// .usernameParameter("username")
// .passwordParameter("password")
.and()
.logout().permitAll();
// 关闭CSRF跨域
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
// 设置拦截忽略文件夹,可以对静态资源放行
web.ignoring().antMatchers("/css/**", "/js/**");
}
}
七、运行程序
ROLE_ADMIN 账户:用户名 admin,密码 123
ROLE_USER 账户:用户名 jitwxs,密码 123
注:如果你想要将密码加密,可以修改 configure() 方法如下:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
每二天:
一. 在内存中创建登录用户
以下代码做了基本配置, 通过AuthenticationManagerBuilder在内存中创建一个用户izuul,密码也是 izuul,角色是 USER.
这个过程主要要添加PasswordEncoder(编码器), 否则报错
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q3c78F0t-1609982260954)(https://ws4.sinaimg.cn/large/006tNc79ly1g1rrw02vrjj31mc07iwh0.jpg)]
package com.izuul.springsecurity.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void config(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("izuul")
.password(passwordEncoder().encode("izuul"))
.roles("USER");
}
}
启动项目访问: <http://localhost:8080/ 并输入账号(izuul) 密码(izuul), 登录
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eIe8vmDM-1609982260956)(https://ws1.sinaimg.cn/mw600/006tNc79ly1g1rs67db25j30tg0fu3z2.jpg)]
项目登录成功就会进入主页
二. 配置 HttpSecurity 资源控制
在上文中 SecurityConfig 配置类中复写 configure 方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/users/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").failureUrl("/login-error")
.and()
.logout().logoutUrl("/logout");
}
这段代码中进行了如下配置:
根路径 “/” 允许全部访问请求
路径 “/users/**” 只允许角色是 USER 的访问, hasRole() 方法也可以用多参数方法 hasAnyRole()
登录路径设置为 /login
登录失败跳转到 /login-error
注销路径 /login
HttpSecurity 配置好了下面开始写 controller 路径
新建 controller 包并且新建 SecurityController 类
SecurityController 中很简单就使用默认请求方式吧
package com.izuul.springsecurity.controller;
@Controller
public class SecurityController {
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", true);
model.addAttribute("msg", "登录失败");
return "login";
}
@RequestMapping("/logout")
public String logout() {
return "logout";
}
@RequestMapping("/users")
public String users() {
return "user";
}
}
4个页面:
1、index.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
izuul 主页
<br>
<a th:href="@{/login}">登录</a>
<br>
<a th:href="@{/users}">users</a>
</body>
</html>
2、login.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form th:action="@{/login}" method="post">
<span th:if="${error}" th:text="${msg}" style="color: red"></span>
<br>
<label>
用户名:
<input name="username" type="text">
</label>
<br>
<label>
密码:
<input name="password" type="password">
</label>
<br>
<button>提交</button>
</form>
</div>
</body>
</html>
3、user.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>user</title>
</head>
<body>
user页面
</body>
</html>
4、logout.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>user</title>
</head>
<body>
user页面
<br>
<a th:href="@{/logout}">注销</a>
</body>
</html>
访问进行测试:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rs9CG6vs-1609982260958)(https://ws3.sinaimg.cn/mw600/006tNc79ly1g1rvezz5i2j30j00ee3za.jpg)]
输入一个错误的密码
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kA8XfyAD-1609982260963)(https://ws3.sinaimg.cn/mw600/006tNc79ly1g1rvgio5tdj30l60fm3zl.jpg)]
登录成功
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RjmmAE9v-1609982260965)(https://ws4.sinaimg.cn/mw600/006tNc79ly1g1rvi8jdhbj30jo0didgl.jpg)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5MSUzcCm-1609982260967)(https://ws4.sinaimg.cn/mw600/006tNc79ly1g1rvilljn8j30lu09wmxw.jpg)]
下一篇教程会将用户登录信息存入数据库
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。