前言:
学习B站UP主狂神说视频笔记整理视频链接
SpringSecurity
安全简介
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。
Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求
从官网的介绍中可以知道这是一个权限框架。想我们之前做项目是没有使用框架是怎么控制权限的?对于权限 一般会细分为功能权限,访问权限,和菜单权限。代码会写的非常的繁琐,冗余。
怎么解决之前写权限代码繁琐,冗余的问题,一些主流框架就应运而生而Spring Scecurity就是其中的一种。
Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。
对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。
测试环境搭建
测试环境使用笔记二Web开发的员工管理系统员工管理系统链接
什么是SpringSecurity
sring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
-
WebSecurityConfigurerAdapter:自定义Security策略
-
AuthenticationManagerBuilder:自定义认证策略
-
@EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
“认证”(Authentication)
身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
“授权” (Authorization)
授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
这个概念是通用的,而不是只在Spring Security 中存在。
快速上手
认证和授权
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
编写 Spring Security 配置类
参考官网:https://spring.io/projects/spring-security
/**
* security 安全
* @author Tu_Yooo
* @Date 2021/5/1 15:22
*/
@EnableWebSecurity //开启security 编写security配置类需要继承WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//拦截器
//授权
//请求授权的规则 HttpSecurity Http安全策略
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问 功能页只有对应有权限的人才能访问
//antMatchers() 拦截路径 .hasRole("vip1")对应权限 permitAll()所有人都能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/login").permitAll()
.antMatchers("/employee/**").hasRole("vip1");
}
}
运行发现员工信息页进不去了,因为我们没有对应的权限
检测到用户没有对应的权限时,我们可以自动跳转到登录页,而不是给用户返回报错信息
# 只需要配置如下代码
# 没有权限会跳转登录页
http.formLogin();
测试一下:发现,没有权限的时候,会跳转到登录的页面!
现在我们来定义认证规则
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.jdbcAuthentication() 数据库取信息认证
//内存认证
auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("vip1")
.and()
.withUser("root").password("123").roles("vip1","vip2");
}
登录时发现报以下错误
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:250) ~[spring-security-core-5.3.6.RELEASE.jar:5.3.6.RELEASE]
at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:198) ~[spring-security-core-5.3.6.RELEASE.jar:5.3.6.RELEASE]
这是告诉我们应该对密码进行加密
修改代码:
//认证
//密码编码 PasswordEncoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.jdbcAuthentication() 数据库取信息认证
//内存认证 .passwordEncoder(new BCryptPasswordEncoder())密码加密方式
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//.password(new BCryptPasswordEncoder().encode("123")) 密码加密
.withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2");
}
扩展JDBC认证:
在Securityconfig
中配置密码加密方式
//数据库加密方式
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
需要重写 UserDetailsService
/**
* security从数据库中获取用户信息
*
* 需要重写 UserDetailsService
* @author Tu_Yooo
* @Date 2021/5/26 10:31
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private SysUserService sysUserService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//数据库中获取用户信息
SysUser sysUser = sysUserService.getByUsername(username);
if (sysUser == null)
throw new UsernameNotFoundException("用户名或密码不正确");
//参数: 用户id 用户名 用户密码 权限信息
return new AccountUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));
}
/**
* 获取用户权限信息 <角色 菜单>
* @param userId 用户id
* @return 权限信息
*/
public List<GrantedAuthority> getUserAuthority(Long userId){
return null;
}
}
返回的UserDetails
默认实现是User 为了方便我们后续扩展新字段
于是重写 UserDetails
/**
*
* 封装用户信息
*
* UserDetails 默认实现类 User
* 我们需要去重写它 方便日后字段扩展
* @author Tu_Yooo
* @Date 2021/5/26 10:45
*/
public class AccountUser implements UserDetails {
///扩展字段 用户id
private Long userId;
private static final long serialVersionUID = 530L;
private static final Log logger = LogFactory.getLog(User.class);
private String password;//密码
private final String username; //用户名
private final Collection<? extends GrantedAuthority> authorities; //权限信息
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
public AccountUser(Long userId,String username, String password, Collection<? extends GrantedAuthority> authorities) {
this(userId,username, password, true, true, true, true, authorities);
}
public AccountUser(Long userId,String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
if (username != null && !"".equals(username) && password != null) {
this.userId=userId;
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = authorities;
} else {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return this.accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return this.accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return this.credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
}
在Securityconfig
中配置认证方式
//数据库获取用户信息
@Autowired
private UserDetailsServiceImpl userDetailsService;
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//数据库认证方式
auth.userDetailsService(userDetailsService);
}
注销
注销功能实现非常简单,只需要在授权中进行设置
@Override
protected void configure(HttpSecurity http) throws Exception {
//
...
//注销功能 注销完跳转首页
http.logout().logoutSuccessUrl("/");
}
编写页面退出按钮
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
权限控制
我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!
我们需要结合thymeleaf中的一些功能
导入thymeleaf整合Security依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
修改前端页面
导入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
修改导航栏,增加认证判断
<!--顶部栏-->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="nowrap">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#"><ADMIN sec:authentication="name"></ADMIN></a><!--sec:authentication显示登录用户名-->
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3" sec:authorize="!isAuthenticated()"><!--判断是否登录-->
<!--未登录显示 登录按钮-->
<li class="nav-item text-nowrap">
<a class="nav-link" th:href="@{/login}">登录</a>
</li>
</ul>
<ul class="navbar-nav px-3" sec:authorize="isAuthenticated()">
<!--登录状态显示 显示退出按钮-->
<li class="nav-item text-nowrap">
<a class="nav-link" th:href="@{/logout}">退出登录</a>
</li>
</ul>
</nav>
测试使用
扩展:侧边栏权限控制
有对应权限的用户只能看到相应权限的选项,没权限点开的选项不予显示出来
修改前端页面
<!--侧边栏-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
<div class="sidebar-sticky">
<!--sec:authorize="hasRole('vip1')" 拥有vip1的权限的人 才能看到此选项-->
<!--根据用户权限动态实现-->
<ul class="nav flex-column" sec:authorize="hasRole('vip1')">
<li class="nav-item">
<a th:class="${activs=='dashboard.html'?'nav-link active':'nav-link'}" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
Dashboard <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#" >
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
Orders
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
Products
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip1')">
<a th:class="${activs=='list.html'?'nav-link active':'nav-link'}" th:href="@{/employee/alluser}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工信息
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Reports
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
Integrations
</a>
</li>
</ul>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Saved reports</span>
<a class="d-flex align-items-center text-muted" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
</a>
</h6>
<ul class="nav flex-column mb-2" >
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Current month
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Last quarter
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Social engagement
</a>
</li>
<li class="nav-item" sec:authorize="hasRole('vip2')">
<a class="nav-link" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Year-end sale
</a>
</li>
</ul>
</div>
</nav>
测试使用
当前admin用户
root用户
记住我
只需要在授权内加入如下代码
//开启记住我功能 cookie 默认保存2周
http.rememberMe();
定制登录页
总是使用使用Security提供的登录页面是非常难受的,有时候我们想使用自己写的登录页
在授权中进行如下配置
//没有权限会跳转登录页 .loginPage("/index.html") 走自己写的登录页
http.formLogin().loginPage("/index.html")
如果页面表单提交路径是这样的:
还需要定义如下:
//没有权限会跳转登录页 .loginPage("/index.html") 走自己写的登录页
//.loginProcessingUrl("/user/login"); 表单的提交路径
http.formLogin().loginPage("/index.html").loginProcessingUrl("/user/login");
如果表单的name属性不是username,password
还需要添加如下代码:
//没有权限会跳转登录页 .loginPage("/index.html") 走自己写的登录页
//.loginProcessingUrl("/user/login"); 表单的提交路径
//.usernameParameter("user").passwordParameter("pwd") 对应表单name属性
http.formLogin().loginPage("/index.html").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/user/login");
前端记住我的名字,也是可以自己定义的,之后在配置类里面配置和前端一样的
使用自定义登录页面注销时出现404
如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能
http.csrf().disable();
完整Security配置代码
/**
* security 安全
* @author Tu_Yooo
* @Date 2021/5/1 15:22
*/
@EnableWebSecurity //开启security 编写security配置类需要继承WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//拦截器
//授权
//请求授权的规则 HttpSecurity Http安全策略
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人都可以访问 功能页只有对应有权限的人才能访问
//antMatchers() 拦截路径 .hasRole("vip1")对应权限 permitAll()所有人都能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/login").permitAll()
.antMatchers("/employee/**").hasRole("vip1");
//没有权限会跳转登录页 .loginPage("/index.html") 走自己写的登录页
http.formLogin().loginPage("/index.html").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/user/login");
//关闭csrf功能
http.csrf().disable();
//注销功能 注销完跳转首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能 cookie 默认保存2周
http.rememberMe().rememberMeParameter("remember");
}
//认证
//密码编码 PasswordEncoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.jdbcAuthentication() 数据库取信息认证
//内存认证 .passwordEncoder(new BCryptPasswordEncoder())密码加密方式
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//.password(new BCryptPasswordEncoder().encode("123")) 密码加密
.withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip2");
}
}
Shiro
什么是Shiro
Apache Shiro是一个Java的安全(权限)框架。
Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
三大核心组件
Shiro有三大核心组件,即Subject、SecurityManager和Realm
-
Subject: 为认证主体。应用代码直接交互的对象是Subject,Subject代表了当前的用户。包含Principals和Credentials两个信息。
-
- Pricipals:代表身份。可以是用户名、邮件、手机号码等等,用来标识一个登陆主题的身份。
-
- Credentials:代表凭证。常见的有密码、数字证书等等。
也就是说两者代表了认证的内容,最常见就是用户名密码了。用Shiro进行身份认证,其中就包括主体认证。
- Credentials:代表凭证。常见的有密码、数字证书等等。
-
SecurityManager:为安全管理员。是Shiro架构的核心。与Subject的所有交互都会委托给SecurityManager, Subject相当于是一个门面,而SecurityManager才是真正的执行者。它负责与Shiro 的其他组件进行交互。
-
Realm:是一个域。充当了Shiro与应用安全数据间的“桥梁”。Shiro从Realm中获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm中获取相应的用户进行比较,来确定用户的身份是否合法;也需要从Realm得到用户相应的角色、权限,进行验证用户的操作是否能过进行,可以把Realm看成DataSource,即安全数据源。
Subject | 用户 |
---|---|
SecurityManager | 管理所有用户 |
Realm | 连接数据 |
十分钟了解Shiro
在官网的例子中了解Shiro
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 获取当前用户
Subject currentUser = SecurityUtils.getSubject();
// 通过当前用户拿到session
Session session = currentUser.getSession();
//在session中存值
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 判断当前的用户是否被认证
if (!currentUser.isAuthenticated()) {
//token 令牌 随意设置
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//设置记住我
token.setRememberMe(true);
try {
currentUser.login(token); //执行了登录操作
} catch (UnknownAccountException uae) { //用户名不存在
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) { //密码错误
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) { //用户被锁定
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) { //认证异常
//unexpected condition? error?
}
}
//获取当前用户的认证
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//获得当前用户的角色
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//是否拥有粗粒度(简单)权限
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//是否拥有更高权限
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
快速上手
导入依赖
shiro整合Spring包
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
编写shiro配置类
我们需要做如下这几件事:
@Configuration
public class ShiroConfig {
//shiroFilterBean 第三步
//DefaultWebSecurityManager 第二步
//创建Realm对象 需要自定义类 第一步
}
自定义Realm
//自定义Realm 需要继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了授权=>");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
return null;
}
}
继续编写shiro配置类
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
//设置安全管理器
filter.setSecurityManager(manager);
return filter;
}
//DefaultWebSecurityManager 第二步
@Bean(name="manager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
//关联UserRealm
manager.setRealm(userRealm);
return manager;
}
//创建Realm对象 需要自定义类 第一步
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
准备测试环境
controller:
@Controller
public class HelloController {
@RequestMapping({"/","index.html"})
public String toIndex(){
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@RequestMapping("/login")
public String tologin(){
return "login";
}
}
再准备四个简单页面
首页:
<body>
<h1>首页</h1>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a>
</body>
</html>
新增页:
<body>
<h2>增加用户</h2>
</body>
修改页:
<body>
<h2>修改用户</h2>
</body>
登录页:
<body>
<h1>登录</h1>
<p th:text="${msg}" style="color:red;"></p>
<form th:action="@{/tologin}" method="post">
<p>用户名:<input type="username" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
实现登录拦截
编写Shiro配置类
//ShiroFilterFactoryBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
//设置安全管理器
filter.setSecurityManager(manager);
//增加shiro内置过滤器
/**
* anon: 无需认证就可以访问
* authc: 必须认证才能访问
* user: 必须拥有记住我功能才能访问
* perms: 拥有对某个资源的权限才能访问
* role:拥有某个角色权限才能访问
*/
Map<String, String> map = new LinkedHashMap<>();
map.put("/user/add","authc");
map.put("/user/update","authc");
filter.setFilterChainDefinitionMap(map);
//设置登录页面
filter.setLoginUrl("/login");
return filter;
}
用户认证
shiro的认证是在自定义Realm中进行的
首先在controller中编辑登录功能
//用户登录功能
@PostMapping("/tologin")
public String tologin(String username, String password, Model model){
//获取用户
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据并且生成一个token令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
subject.login(token);//登录 如果没有异常就说明OK了
return "index";//返回首页
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
在自定义UserRealm中进行认证
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
//用户名密码 数据库中取
String name="admin";
String password="123";
UsernamePasswordToken userName=(UsernamePasswordToken)token;
if (!userName.getUsername().equals(name)){
return null;//抛出异常
}
//密码认证 shiro做
return new SimpleAuthenticationInfo("",password,"");
}
shiro整合mybais
导入依赖
<!--spring boot整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--Mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--SpringbootJDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
编写配置
spring:
thymeleaf:
cache: false #关闭模板引擎的缓存
# 配置数据源 serverTimezone=UTC 设置时区
datasource:
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.tony.pojo
mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}
编写接口
@Mapper
@Repository
public interface UserMapper {
//根据用户查询用户名
public User queryUserbyName(String name);
}
编写映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tony.mapper.UserMapper">
<select id="queryUserbyName" resultType="com.tony.pojo.User" parameterType="string">
select * from user where name=#{name}
</select>
</mapper>
修改自定义Realm代码
@Autowired
private UserMapper userMapper;
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
UsernamePasswordToken userName=(UsernamePasswordToken)token;
//连接真实数据库
User user = userMapper.queryUserbyName(userName.getUsername());
if(user==null){ //没查出用户
return null;
}
//密码认证 shiro做 密码加密
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
请求授权
编写Shiro过滤器
1.设置访问/user/add
路径时,需要[user:add
权限
2.没有此权限访问时,会跳转指定路径
//ShiroFilterFactoryBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
//设置安全管理器
filter.setSecurityManager(manager);
//增加shiro内置过滤器
/**
* anon: 无需认证就可以访问
* authc: 必须认证才能访问
* user: 必须拥有记住我功能才能访问
* perms: 拥有对某个资源的权限才能访问
* role:拥有某个角色权限才能访问
*/
Map<String, String> map = new LinkedHashMap<>();
// map.put("/user/add","authc");
map.put("/user/update","authc");
map.put("/user/add","perms[user:add]"); //访问此路径需要user:add权限
filter.setFilterChainDefinitionMap(map);
//设置登录页面
filter.setLoginUrl("/login");
filter.setUnauthorizedUrl("/noperms");//无权限时执行这个请求
return filter;
}
编写controller
@RequestMapping("/noperms")
@ResponseBody
public String perms(){
return "你没有权限进行访问";
}
编写UserRealm
在认证中,将用户数据传递进来,以便在授权时能够获取
授权:
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了授权=>");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");//对每个用户进行授权
//取出用户信息
Subject subject = SecurityUtils.getSubject();
User principal = (User)subject.getPrincipal();
//将用户信息的权限信息 设置进去
//动态设置权限 需要新增一些数据库表 如:权限表
//info.addStringPermission(principal.getParms());
return info;
}
shiro整合thymeleaf
导入依赖
shiro整合thymeleaf包
<!--shiro-thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
在Bean容器中注入
编写Shiro配置文件
//shiro整合thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
编写页面
需要导入命名空间
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<!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>Title</title>
</head>
<body>
<h1>首页</h1>
<!--shiro:hasPermission 如果用户拥有对应权限则显示出来-->
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>