咱目前主要关注如何通过Shiro实现认证、授权和对话管理。
Apache Shiro的核心通过Filter来实现。
先将请求拦截,然后判断是否要认证(要的话,就让用户输入用户名和密码)、是否需要权限(有权限才能访问)。官方文档:实际上,我们想把它称为 “User”,因为这样 “更合理”,但我们决定不这么做:太多应用程序的现有 API 已经有了自己的 User 类/框架,我们不想与它们发生冲突。【但实际上叫Subject,依然会有冲突:)】
// 当前用户,在整个Shiro框架运作的过程中,通过拿到subject就能拿到用户信息
Subject subject = SecurityUtils.getSubject();
subject.login(new UsernamePasswordToken(username, password));
// AuthorizingRealm是授权Realm
public abstract class AuthorizingRealm extends AuthenticatingRealm implements Authorizer, Initializable, PermissionResolverAware, RolePermissionResolverAware {
......
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection var1);
......
}
// AuthenticatingRealm是认证Realm
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
......
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;
}
要让Shiro框架运转起来,先要定义出需要的组件,然后按要求组装起来,这就需要ShiroConfig.java。详见:
5、重点:如何使用Shiro安全框架实现认证和授权?
开干吧!
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-springartifactId>
<version>1.7.1version>
dependency>
这里假设db表里面已经有一些用户信息了,当用户登录时,会将传入的username和password和db表里的信息进行比对。
CREATE DATABASE learn_shiro_mysql;
use learn_shiro_mysql;
CREATE TABLE User (
id INT PRIMARY KEY,
username VARCHAR(32),
password VARCHAR(64),
permission VARCHAR(32),
role VARCHAR(32)
);
INSERT INTO User (id, username, password)
VALUES (1, '张飞', '123');
INSERT INTO User (id, username, password, permission)
VALUES (2, '关羽', '456', 'manage');
INSERT INTO User (id, username, password, permission, role)
VALUES (3, '刘备', '789', 'manage', 'administrato`在这里插入代码片`r');
- 这张表的设计是不合理的。原因在于,一个用户可能拥有多个permission,即username和permission不是一对一的关系,不适合放一张表里。
- 但本文重点在于“认识并使用Shiro技术”,所以暂且不在db表的设计上花费功夫。
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.2version>
dependency>
引入了DAO层框架:mybatis-plus
# 数据库配置
spring:
datasource:
# Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/learn_shiro_mysql
username: root
password: xxx
# mybatis-plus配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
learn_shiro_mysql是上面建好的database。
与User表一一对应
@Data
@TableName("User")
public class User {
private Integer id;
private String username;
private String password;
private String permission;
private String role;
}
通过mybatis-plus进行增删改查
/**
* 不添加@Repository注解,当通过@Autowired注入时:
*
* @Autowired
* private UserMapper userMapper;
*
* IDEA会给userMapper打上红色下划线,提示:Could not autowire. No beans of 'UserMapper' type found.
* 这是因为UserMapper是接口,不能被实例化。但实际上,运行时会生成一个代理对象,代理对象会继承UserMapper接口,所以可以被@Autowired注入。
* 为了消除红色下划线,所以添加@Repository注解。
* @Autowired
* private UserMapper userMapper;
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectAllUser() {
userMapper.selectList(null).forEach(System.out::println);
}
}
User(id=1, username=张飞, password=123, permission=null, role=null)
User(id=2, username=关羽, password=456, permission=manage, role=null)
User(id=3, username=刘备, password=789, permission=manage, role=administrator)
public interface IUserService {
User selectByUsername(String username);
}
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public @Nullable User selectByUsername(String username) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username", username);
return userMapper.selectOne(queryWrapper);
}
}
@SpringBootTest
public class UserServiceImplTest {
@Autowired
private IUserService userService;
@Test
public void testSelectByUsername() {
String username = "刘备";
System.out.println(userService.selectByUsername(username));
}
}
User(id=3, username=刘备, password=789, permission=manage, role=administrator)
@Controller
public class UserController {
@GetMapping("/{url}")
public String redirect(@PathVariable String url) {
// 例如,如果url的值为"main",就返回"main"视图
return url;
}
}
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [favicon.ico], template might not exist or might not be accessible by any of the configured Template Resolvers
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
head>
<body>
<h1>I am main.html !h1>
body>
html>
如上所述,补上
参考资料
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
head>
<body>
<h1>I am manage.html !h1>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
head>
<body>
<h1>I am administrator.html !h1>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
head>
<body>
<h1>I am index.html !h1>
<a href="/main">maina> | <a href="/manage">managea> | <a href="/administrator">administratora>
body>
html>
每个html中都要补上
,着实很离谱。
// 其实还可以这么做:
@GetMapping("favicon.ico")
@ResponseBody
void favicon() {
// 方法体为空即可
}
当然了,正常情况下, 是会提供resources/favicon.ico。所以,不如去网上找一个favicon.ico。
目前,用户没有登录,便可以访问上述所有html,这显然是不安全的。因此,我们要使用Shiro技术来认证和授权。
// AuthorizingRealm是授权Realm
public abstract class AuthorizingRealm extends AuthenticatingRealm implements Authorizer, Initializable, PermissionResolverAware, RolePermissionResolverAware {
......
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection var1);
......
}
// AuthenticatingRealm是认证Realm
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
......
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;
}
public class UserRealm extends AuthorizingRealm {
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 暂时 return null;
return null;
}
/**
* 认证,即校验用户的用户名和密码
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 暂时 return null;
return null;
}
}
@Configuration
public class ShiroConfig {
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return shiroFilterFactoryBean;
}
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
// 设置过滤器
Map<String, String> filterChainDefinitionMap = new HashMap<>();
filterChainDefinitionMap.put("/main", "authc");
filterChainDefinitionMap.put("/manage", "perms[manage]");
filterChainDefinitionMap.put("/administrator", "role[administrator]");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
理论补充:
(1)认证过滤器:
1)anon
: 无需认证
2)authc
: 必须认证
3)authcBasic
: 需要通过HTTP Basic认证
4)user
: 只要曾经被Shiro记录即可,比如:记住我
(2)授权过滤器
1)perms
: 必须拥有某个权限才能访问
2)roles
: 必须拥有某个角色才能访问
3)port
: 请求的端口必须是指定值才可以
4)rest
: 请求必须基于RESTful (POST、PUT、GET、DELETE)
5)ssl
: 必须是安全的URL请求(协议HTTPS)
不登录,就没法看有限制的页面了!
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
......
// 设置登录页面
shiroFilterFactoryBean.setLoginUrl("/login");
......
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" value="login">
form>
body>
html>
@PostMapping("/login")
public String login(String username, String password, Model model) {
// 将用户登录的认证过程交给Shiro
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username, password));
return "index";
} catch (UnknownAccountException | IncorrectCredentialsException e) {
// 重新返回登录页面
model.addAttribute("error", "用户名不存在 或者 密码错误");
return "login";
} catch (Exception e) {
// 重新返回登录页面
model.addAttribute("error", "登录出错");
return "login";
}
}
使用Model对象将错误信息传递给前端显示。Model是Spring MVC中一个非常重要的对象,它封装了视图显示所需要的数据,在视图中可以很方便的取出Model中的数据。
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (authenticationToken instanceof UsernamePasswordToken) {
UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
User user = userService.selectByUsername(upToken.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
}
return null;
}
当执行
subject.login(new UsernamePasswordToken(username, password));
时,会执行到doGetAuthenticationInfo方法中。
根据用户传入的username去查User表,
(1)没查到,返回null
(2)查到了,但用户传入的密码和User表中的密码不匹配,抛异常
(3)查到了,密码也匹配上了,登录成功
接下来,说明还未授权,接下来就要准备授权了。
(1)ShiroConfig.java
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
......
// 设置未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
return shiroFilterFactoryBean;
}
(2)UserController
@GetMapping("/unauthorized")
@ResponseBody
public String unauthorized() {
return "您没有权限访问该页面!";
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Subject currentUser = SecurityUtils.getSubject();
Object tmpUser = currentUser.getPrincipal();
if (tmpUser instanceof User) {
User user = (User) tmpUser;
// 角色
Set<String> roles = new HashSet<>();
roles.add(user.getRole());
// 权限
Set<String> perms = new HashSet<>();
perms.add(user.getPermission());
SimpleAuthorizationInfo saInfo = new SimpleAuthorizationInfo();
saInfo.setRoles(roles);
saInfo.setStringPermissions(perms);
return saInfo;
} else {
return null;
}
}
(1)登录时,我需要知道当前页面是谁在访问,此需求可以简化为:登录后,显示“欢迎xxx回家~”
(2)然后,要提供登出的按钮。
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>I am index.html !h1>
<div th:if="${session.user != null}">
<p>Welcome, <span th:text="${session.user.username}">span>!p>
div>
<a href="/main">maina> | <a href="/manage">managea> | <a href="/administrator">administratora>
<div>
<a href="/logout">logouta>
div>
body>
html>
IDEA会在
user
下标注黄色波浪线,看着真难受啊~
@PostMapping("/login")
public String login(String username, String password, Model model) {
// 将用户登录的认证过程交给Shiro
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username, password));
subject.getSession().setAttribute("user", subject.getPrincipal());
return "index";
} catch (UnknownAccountException | IncorrectCredentialsException e) {
...
} catch (Exception e) {
...
}
}
@GetMapping("/logout")
public String logout() {
// 退出登录
SecurityUtils.getSubject().logout();
return "login";
}
(1)当执行
subject.login(new UsernamePasswordToken(username, password));
时,会执行UserRealm类的doGetAuthenticationInfo方法,如果登录成功,那么return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
此时,user赋予了principal。
(2)因此subject.getPrincipal()取出的便是user。
刘备拥有main.html、manage.html、administrator.html的权限,所以可以看到3个main、manage、administrator的链接,那么对于没有权限的人,咱希望他不要看到对应的链接。
<dependency>
<groupId>com.github.theborakompanionigroupId>
<artifactId>thymeleaf-extras-shiroartifactId>
<version>2.1.0version>
dependency>
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>I am index.html !h1>
<div th:if="${session.user != null}">
<p>Welcome, <span th:text="${session.user.username}">span>! <a href="/logout">logouta>p>
div>
<a href="/main">maina>
<div shiro:hasPermission="manage">
<a href="/manage">managea>
div>
<div shiro:hasRole="administrator">
<a href="/administrator">administratora>
div>
body>
html>
讲得真不错~ 感谢老师~