shiro springsecurity

spring-security

  1. 引入依赖
<?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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.starcpdk</groupId>
    <artifactId>springboot-springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-springsecurity</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--security thymeleaf整合包-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  1. 编写配置类
package com.starcpdk.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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 在前端页面中 , 我们需要引入一个命名空间
    // xmlns:th="http://www.thymeleaf.org"
    // xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4
    // 通过sec标签进行操作
    /*
    <div sec:authorize="!isAuthenticated()">
        <a href="item" th:href="@{/toLogin}"></a>
    </div>
     */


    // 授权
    // 链式调用
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问 , 但是功能页只有有权限的人才能访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1") // 这里的意思是vip1的角色有权利访问/level1下面的所有资源
                .antMatchers("/level2/**").hasRole("vip2") // 这里的意思是vip2的角色有权利访问/level2下面的所有资源
                .antMatchers("/level3/**").hasRole("vip3"); // 这里的意思是vip3的角色有权利访问/level3下面的所有资源

        // 没有权限默认会到登录页面
            // 默认是到login请求
            // 定制登录页 /toLogin  登录认证的是loginProcessingUrl("/login");
        http.formLogin().loginPage("/toLogin") // 未登录的话跳转到toLogin请求
                .usernameParameter("user") // 前端传递的表字段中的用户名是user , 我们需要自定义前端传来的参数 , 默认在源码中 , 用户名是username
                .passwordParameter("pwd")
                .loginProcessingUrl("/login"); // 表单提交的请求action请求到login

        // 注销
        // 开启了注销功能 , 调到首页
        // 防止网站攻击
        http.csrf().disable(); // 关闭csrf功能 , 登出失败可能存在的原因就是没加这行代码
        http.logout().logoutSuccessUrl("/"); // 注销成功跳转到/请求即为首页

        // 开启记住我功能 , cookie , 默认保存两周
        // 自定义接受前端的参数
        http.rememberMe().rememberMeParameter("remember"); // 前端在记住我的选项框中name属性的值是remember , 所以我们此处需要自定义的让其接受remember这个参数
    }

    // 认证   springboot  2.1.x   可以直接使用
    // 密码编码:passwordEncoder
    // 在springsecurity5.0+  新增了很多加密的方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 这些数据正常应该从数据库读取
        // 现在是从内存中读取的用户的身份
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())// 设置密码加密的方式
                .withUser("yyf")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip2" , "vip3") // 这里相当于在内存中创建用户 , yyf , 密码是通过BCryptPasswordEncoder对123456进行加密得到的 , 权限有vip3 , vip2
                .and()
                .withUser("root")
                .password("123456")
                .roles("vip1" , "vip2" , "vip3")
                .and()
                .withUser("guest")
                .password("123456")
                .roles("vip1");
    }
}

shiro

  1. 引入依赖
<?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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.starcpdk</groupId>
    <artifactId>shior-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shior-springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>

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

        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

        <!--整合mybatis和springboot的包-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <!--
            Shiro 三大对象
            SecurityManager 管理所有用户
            Realm 连接数据
                     -->

        <!--导入Shiro整合springboot的包-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.0</version>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ShiroConfig类

  1. Shiro 需要两个配置文件类
package com.starcpdk.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 {
    // ShiroFiliterFactoryBean
    @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;
    }

    // DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

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

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

UserRealm类

package com.starcpdk.config;

import com.starcpdk.pojo.User;
import com.starcpdk.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;

// 自定义的realm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); // 拿到user对象

        // 添加了这个的授权user:add , 在ShiroConfig 类 中添加了perms[user:add]这个授权验证
        // 设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 用户名 , 密码 , 数据库取
        // 连接真实数据库
        User user = userService.queryUserByName(token.getUsername());

        if (user == null){
            return null; // 抛出异常  UnknownAccountException
        }

        // 登录成功创建session保存用户信息
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        // 可以加密 , MD5:   MD5盐值加密
        // 密码认证 : Shiro做
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}

controller

package com.starcpdk.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.omg.CORBA.portable.UnknownException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

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

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

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

    @RequestMapping("/login")
    public String login(String username , String password , Model model){
        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //
        try {
            subject.login(token); // 执行登录的方法 , 如果没有异常就说明执行成功了
            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 "未经授权 , 无法访问此页面";
    }

}

mapper

package com.starcpdk.mapper;

import com.starcpdk.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {
    User queryUserByName(String name);
}

User实体类

package com.starcpdk.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

service层

package com.starcpdk.service.impl;

import com.starcpdk.mapper.UserMapper;
import com.starcpdk.pojo.User;
import com.starcpdk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

druid数据源配置文件

spring:
  datasource:
    username: root
    password: root
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

springboot扫描包配置文件

mybatis.type-aliases-package=com.starcpdk.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值