0
点赞
收藏
分享

微信扫一扫

Spring Boot整合 Shiro安全框架

跟着Damon写代码 2022-04-08 阅读 83
java后端

**

Spring Boot 整合Shiro 安全框架

**

1.pom文件添加依赖

1.pom文件添加依赖

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>

2.新建一个包 config 创建两个配置类

package com.hengyang.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;

@Configuration
public class ShiroConfig {


@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);

//设置shiro的内置过滤器
/**
* anno:无需认证所有人都可以访问
* authc: 必须认证了才能访问
* user: 必须拥有记住我才能访问
* perms: 拥有某个资源的权限才能访问
* role: 拥有某个角色权限才能访问
*/


// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
//拦截
Map<String, String> filterMap = new LinkedHashMap<>();

//授权
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");



filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//未授权页面
bean.setUnauthorizedUrl("/noauth");
return bean;
}



@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}

//创建 realm 对象 ,需要自定义类
@Bean
public UserRealm userRealm(){
return new UserRealm();
}


//整合shiro Dialect: 用来整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}

}



package com.hengyang.config;

import com.hengyang.pojo.User;
import com.hengyang.service.UserService;
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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

@Autowired
UserService userService;

//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
//添加权限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal();//拿到user对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());

return info;
}

//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){//没有该用户
return null;
}

//当前登录用户放进session
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密码认证
return new SimpleAuthenticationInfo(user,user.getUser_password(),"");
}
}

3.UserController 用户登录

package com.hengyang.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class MyController {

@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,shiro");
return "index";
}


@RequestMapping("/user/add")
public String add(){
return "/user/add";
}

@RequestMapping("/user/update")
public String Update(){
return "/user/update";
}

@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}


/**
* 用户信息 账号和密码封装成token
* UsernamePasswordToken token = new UsernamePasswordToken(username, paddword);
* 用户的信息封装成一个令牌 然后直接 subject.login(token);
* 用try catch接住
* UnknownAccountException = 账号不存在
* IncorrectCredentialsException = 密码错误
* @param username
* @param paddword
* @param model
* @return
*/

@RequestMapping("/login")
public String login(String username,String paddword,Model model){
//获取当前的用户
Subject subject = SecurityUtils.getSubject();
//使用用户的登录信息创建令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, paddword);
try {
subject.login(token);//执行登录方法,如果没有异常就说明OK
return "index";
}catch (UnknownAccountException e){//用户名不存在
model.addAttribute("msg","用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}

}

@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}

/**
* 本地登出页面
* @param redirectAttributes
* @return
*/

@RequestMapping(value="/logout",method= RequestMethod.GET)
public String logout(RedirectAttributes redirectAttributes ){
//使用权限管理工具进行用户的退出,跳出登录,给出提示信息
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
subject.logout();
}
return "/login";
}



}

4.Shiro 整合 thymeleaf 前端不显示 没有权限的功能按钮

1.引入 pom 依赖

<!--		shiro-thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>

2.前端代码 首页 加上个 xmlns:shiro=“http://www.thymeleaf.org/thymeleaf-extras-shiro”

3.在UserRealm配置类的认证方法里往session里存放当前登录用户 ,供前端 判断是不是有该用户

        //当前登录用户放进session
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);

4.前端进行判断

<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登录</a>
</div>

<p th:text="${msg}"></p>

<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">添加</a>
</div>

<div shiro:hasPermission="user:update">
| <a th:href="@{/user/update}">修改</a>
</div>
举报

相关推荐

0 条评论