1、功能实现
1.查询数据库,获取用户信息,赋予用户角色交给Security管理
2.自定义登录页面、无权访问跳转页面
2、security02 子工程
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yzm</groupId>
<artifactId>security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>security02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>security02</name>
<packaging>jar</packaging>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>com.yzm</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.192.128:3306/testdb?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: root
password: 1234
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
type-aliases-package: com.yzm.security02.entity
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3、自定义获取账号信息
通过查询数据库,来获取用户账号信息,需要我们实现 UserDetailsService 并重写 loadUserByUsername()方法
package com.yzm.security02.config;
import com.yzm.security02.entity.Role;
import com.yzm.security02.entity.User;
import com.yzm.security02.service.RoleService;
import com.yzm.security02.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* 自定义UserDetailsService,重写loadUserByUsername方法,查询数据库获取用户信息和权限信息
* Spring Security进行用户认证时,需要根据用户的账号、密码、权限等信息进行认证,
* 因此,需要根据查询到的用户信息封装成一个认证用户对象并交给Spring Security进行认证。
* 查询用户信息并封装成认证用户对象的过程是在UserDetailsService接口的实现类(需要用户自己实现)中完成的
*/
@Service
public class SecUserDetailsServiceImpl implements UserDetailsService {
private final UserService userService;
private final RoleService roleService;
public SecUserDetailsServiceImpl(UserService userService, RoleService roleService) {
this.userService = userService;
this.roleService = roleService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.lambdaQuery().eq(User::getUsername, username).one();
if (user == null) {
throw new UsernameNotFoundException(String.format("用户'%s'不存在", username));
}
List<Integer> roleIds = Arrays.stream(user.getRIds().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
List<Role> roleList = roleService.listByIds(roleIds);
List<SimpleGrantedAuthority> authorities = roleList.stream()
.map(Role::getRName)
.distinct()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
// 这里我们的权限只是基于角色的
return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
}
}
loadUserByUsername 返回的 UserDetails 对象封装了用户信息,但它是一个接口,使用Security默认提供的org.springframework.security.core.userdetails.User返回即可
4、SecurityConfig 配置类
package com.yzm.security02.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Slf4j
@Configuration
@EnableWebSecurity // 开启Security服务
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 注入自定义的 UserDetailsService
private final UserDetailsService userDetailsService;
public SecurityConfig(@Qualifier("secUserDetailsServiceImpl") UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* 密码编码器
* passwordEncoder.encode是用来加密的,passwordEncoder.matches是用来解密的
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 配置用户
* 指定默认从哪里获取认证用户的信息,即指定一个UserDetailsService接口的实现类
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 从数据库读取用户、并使用密码编码器解密
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
//配置资源权限规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 关闭CSRF跨域
.csrf().disable()
// 登录
.formLogin()
.loginPage("/auth/login") //指定登录页的路径,默认/login
.loginProcessingUrl("/login") //指定自定义form表单请求的路径(必须跟login.html中的form action=“url”一致)
.defaultSuccessUrl("/home", true) // 登录成功后的跳转url地址
.failureUrl("/auth/login?error") // 登录失败后的跳转url地址
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/401") // 拒接访问跳转页面
.and()
// 退出登录
.logout().permitAll()
.and()
// 访问路径URL的授权策略,如注册、登录免登录认证等
.authorizeRequests()
.antMatchers("/", "/home", "/register", "/auth/login").permitAll() //指定url放行
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER") // 需要角色(二选一)
.antMatchers("/admin/**").hasRole("ADMIN") // 需要角色
.anyRequest().authenticated() //其他任何请求都需要身份认证
.and()
;
}
}
5、访问接口
package com.yzm.security02.controller;
import com.yzm.security02.entity.User;
import com.yzm.security02.service.UserService;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HomeController {
private final UserService userService;
private final PasswordEncoder passwordEncoder;
public HomeController(UserService userService, PasswordEncoder passwordEncoder) {
this.userService = userService;
this.passwordEncoder = passwordEncoder;
}
@GetMapping(value = {"/", "/home"})
public String home(ModelMap map, @AuthenticationPrincipal UserDetails userDetails) {
String username = userDetails == null ? null : userDetails.getUsername();
map.addAttribute("username", username);
return "home";
}
@GetMapping("/auth/login")
public String login() { return "login"; }
@GetMapping("401")
public Object notRole() { return "401"; }
@PostMapping("register")
public Object register(@RequestParam String username, @RequestParam String password, ModelMap map) {
User user = new User();
user.setUsername(username);
// 密码加密
user.setPassword(passwordEncoder.encode(password));
userService.save(user);
map.addAttribute("user", user);
return "home";
}
}
package com.yzm.security02.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/admin")
public class AdminController {
@GetMapping
public Object admin(@AuthenticationPrincipal UserDetails userDetails) {
return userDetails;
}
@GetMapping("/select")
public Object select() { return "Select"; }
@GetMapping("/create")
public Object create() { return "Create"; }
@GetMapping("/update")
public Object update() { return "Update"; }
@GetMapping("/delete")
public Object delete() { return "Delete"; }
}
package com.yzm.security02.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping
public Object user(@AuthenticationPrincipal UserDetails userDetails) {
return userDetails;
}
@GetMapping("/select")
public Object select() { return "Select"; }
@GetMapping("/create")
public Object create() { return "Create"; }
@GetMapping("/update")
public Object update() { return "Update"; }
@GetMapping("/delete")
public Object delete() { return "Delete"; }
}
6、html页面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>当前登录状态:<span th:text="${username ?: '未登录 '}"></span></h1>
<h2>1.注册 <span th:if="${user != null}"> [[${user.username}]] 成功</span></h2>
<form action="/register" method="post">
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Username">
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Password">
</p>
<button type="submit">Register</button>
</form>
<h2>2.注销</h2>
<form action="/logout" method="post">
<button type="submit">Sign out</button>
</form>
<h3>3.User列表</h3>
<p><a href="/user">User角色</a></p>
<p><a href="/user/select">User角色,拥有 select 权限</a></p>
<p><a href="/user/create">User角色,拥有 create 权限</a></p>
<p><a href="/user/update">User角色,拥有 update 权限</a></p>
<p><a href="/user/delete">User角色,拥有 delete 权限</a></p>
<h3>4.Admin列表</h3>
<p><a href="/admin">Admin角色</a></p>
<p><a href="/admin/select">Admin角色,拥有 select 权限</a></p>
<p><a href="/admin/create">Admin角色,拥有 create 权限</a></p>
<p><a href="/admin/update">Admin角色,拥有 update 权限</a></p>
<p><a href="/admin/delete">Admin角色,拥有 delete 权限</a></p>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录页</title>
</head>
<body>
<h1 th:if="${param.logout}">You have been logged out.</h1>
<h1 th:if="${param.error}">You username or password is wrong</h1>
<h2>用户名密码登录</h2>
<form action="/login" method="post">
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Username">
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Password">
</p>
<p>
<label>
<input type="checkbox" name="rememberMe">
</label> Remember me on this computer.
</p>
<button type="submit">Sign in</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>401</title>
</head>
<body>
<h1>抱歉,你无权访问</h1>
</body>
</html>
7、注册用户
启动项目,注册admin、yzm
用户表
角色表
权限表
admin有双重身份
8、测试
访问主页,点击用户详情,跳转到我们自定义的登录页,默认是/login
loginPage("/auth/login") //指定登录页的路径,默认/login
登录失败示范,登录失败跳转
failureUrl("/auth/login?error") // 登录失败后的跳转url地址
登录成功跳转
defaultSuccessUrl("/home", true) // 登录成功后的跳转url地址
我们给yzm赋予的角色是USER
设置url的也是USER
但是访问不了 /user/** 的接口
这是因为Security自动给我们加了前缀ROEL_
修改数据库,如下
重启后就可以正常访问了 /user/** 接口
访问 /admin/** 还是无权,跳转到401
exceptionHandling().accessDeniedPage("/401") // 拒接访问跳转页面
9 hasRole 和 hasAuthority 的 区别
hasRole(hasAnyRole):添加前缀,hasRole(“ADMIN”) --> 匹配数据库“ROLE_ADMIN”
hasAuthority(hasAnyAuthority):不会添加前缀,hasAuthority(“ADMIN”) --> 匹配数据库"ADMIN"
//.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
//.antMatchers("/admin/**").hasRole("ADMIN")
// 把hasRole换成hasAuthority
.antMatchers("/user/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")
.antMatchers("/admin/**").hasAuthority("ROLE_ADMIN")