springboot中实现权限认证的两个框架
web开发安全框架
提供认证和授权功能!
一.SpringSecurity
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.6.9</version>
</dependency>
2.实现授权和认证功能
package com.springboot.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author panglili
* @create 2022-07-10-17:18
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//http Security认证,首页所有人都可以访问,功能页只有相应权限的人才能访问
//授权
http.authorizeHttpRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认跳登录页面
http.formLogin();
}
@Override
//认证
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("tata").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
}
}
3.超简单的注销功能
前端界面中,注销按钮处,使用thymeleaf点击到后端的security控制类中的logout
<!--注销-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
security中的logout是spring security自己提供的,只需要用它的参数http.logout()即可。
http.logout()
4.权限控制
此功能展示相应的界面给不同用户,上面实现的功能会展示所有界面,只是不同用户点击不是自己的权限内的页面会无法展示。
导入依赖包,使得可以在thymeleaf中调用security的变量。
<!--security和thymeleaf整合包-->
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
在html头文件记得导入,才会有提示!!!
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
实现不同用户的权限功能,只需要在不同前端内容中使用security的语句加以判断即可。
<div class="column" sec:authorize="hasRole('vip3')">
<div class="ui raised segment">
<div class="ui">
<div class="content" >
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
当用户角色为vip3时才展示div下面的内容。
5.记住我功能实现
后端security的参数http调用方法rememberme
http.rememberMe().rememberMeParameter("remember");
前端设置一个选择框,命名为remember
<div class="field">
<input type="checkbox" name="remember"/>记住我
</div>
二.shrio
1.导入jar
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
2.写配置功能
subject用户,securityManager管理所有用户,realm连接数据。
三大对象
package com.springboot.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author panglili
* @create 2022-07-10-21:15
*/
@Configuration
public class ShrioConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefault") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean Bean = new ShiroFilterFactoryBean();
Bean.setSecurityManager(defaultWebSecurityManager);
//添加shrio内置过滤器
Map<String,String> filterMap=new LinkedHashMap<>();
//只允许带有user:add的用户去访问add页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
Bean.setUnauthorizedUrl("/unauth");
//设置页面认证后才能访问
filterMap.put("/user/*","authc");
Bean.setFilterChainDefinitionMap(filterMap);
//设置登录页面
Bean.setLoginUrl("/toLogin");
return Bean;
}
@Bean(name="getDefault")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
//整合shrio和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
3.realm类实现授权和认证
package com.springboot.config;
import com.springboot.pojo.userDao;
import com.springboot.service.userDaoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
/**
* @author panglili
* @create 2022-07-10-21:16
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
userDaoService userDaoService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权功能=====>");
//获取当前登录的对象
Subject subject = SecurityUtils.getSubject();
//通过当前对象取到认证里的userdao
userDao currentUser = (userDao) subject.getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//设置当前用户权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证功能======>");
UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;
//获取数据库中的名字
userDao userDao = userDaoService.queryByName(usertoken.getUsername());
if(userDao==null){
return null; //返回null为一个异常,在controller中被捕获,会显示用户名错误。
}
return new SimpleAuthenticationInfo(userDao,usertoken.getPassword(),"");
}
}
4.controller密码认证判断
//登录界面
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
//shrio的登录权限认证
@RequestMapping("/login")
public String login(String username,String password,Model md){
System.out.println("进入了login");
System.out.println(username+password);
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//执行登录方法
try{
subject.login(token);
return "index";
}catch (UnknownAccountException e){
md.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
md.addAttribute("msg","密码错误");
return "login";
}
}
//没有权限的情况
@RequestMapping("/unauth")
@ResponseBody
public String unauth(){
return "没有权限访问!";
}
//退出登陆
@RequestMapping("/logout")
public String logOut(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}