安全框架shiro

8 篇文章 0 订阅
6 篇文章 0 订阅

一 、 什么是shiro

  • Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

  • 开发商:Apache 性质:Java安全框架
    **

二、三个核心组件

  • Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
  • SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
  • Realms: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
  • Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果系统默认的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。
    在这里插入图片描述
    三个核心组件的关系
    在这里插入图片描述

入门

  • pom文件依赖
 <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.7.1</version>
        </dependency>

        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
  • 先看看源码的Quickstart 类
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro's API.
 * 一个简单的快速入门应用程序,显示了如何使用Shiro的API。
 *
 * @author W
 * @since 0.9 RC2
 */
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 ();

        /**
         *对于这个简单的示例快速入门,使SecurityManager可以作为JVM单例进行访问。
         大多数应用程序不会这样做,
         而是依赖于其容器配置或webapps的web.xml。这超出了此简单快速入门的范围,因此我们将只做最少的工作,以便您可以继续感受一下。
         */
        SecurityUtils.setSecurityManager (securityManager);

        // 1 获取当前用户对象Subject
        Subject currentUser = SecurityUtils.getSubject ();
        // 2 通过当前用户拿到Session
        Session session = currentUser.getSession ();

        session.setAttribute ("someKey", "aValue");
        String value = (String) session.getAttribute ("someKey");
        if (value.equals ("aValue")) {
            log.info ("Subject取到了session=> " + value + "!");
        }

        //3 判断当前用户是否被认证 (让我们登录当前用户,以便我们可以检查角色和权限)
        if (!currentUser.isAuthenticated ()) {
            //token 令牌
            UsernamePasswordToken token = new UsernamePasswordToken ("lonestarr", "vespa");
            token.setRememberMe (true);
            try {
                //执行了登录操作
                currentUser.login (token);

            } catch (UnknownAccountException uae) {
                //未知帐户异常 UnknownAccountException
                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?身份验证异常
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info ("User [" + currentUser.getPrincipal () + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole ("schwartz")) {
            log.info ("May the Schwartz be with you!");
        } else {
            log.info ("Hello, mere mortal.");
        }
//粗粒度
        //test a typed permission (not instance-level)
        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.");
        }
//细粒度
        //a (very powerful) Instance Level permission:
        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!");
        }
//注销
        //all done - log out!
        currentUser.logout ();

        System.exit (0);
    }
}

  • lo4j的配置类
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

shrio.ini的原始配置

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================

# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

shiro的基本使用

soringboot整合shiro
技术支持:shiro、soringboot、thymeleaf、mysql、druid、mybatis、log4j及其互相整合的包

  • pom文件
<dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</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>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.4.0</version>
        </dependency>
<!--        整合thymeleaf-extras-shiro-->
        <!-- 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>

        <!--
        Subject用户
        SecurityManager管理所有用户
        Realm连接 数据
        -->
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

搭建项目
在这里插入图片描述
第一步 静态页面 templates
在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<p style="color:red;" th:text="${msg}"></p>
<form th:action="@{/login}" method="post">
    用户名:<input type="text" name="username"><br>&nbsp;码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

  • index.html
<!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>
    <style>
        a {
            color: #443399
        }
    </style>
</head>
<body>
<H1>欢您你!</H1>
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:hasPermission="user:add">
    <p style="color:red;" th:text="${msg}"></p>
    <a th:href="@{/up}">up</a>&nbsp;<a th:href="@{/add}">add</a>
</div>
</body>
</html>

  • user文件夹
    在这里插入图片描述
  • add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>增加页面</title>
</head>
<body>

<h1>增加页面</h1>
<p style="color:red;" th:text="${msg}"></p>
</body>
</html>

  • update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>update</title>
</head>
<body>
<h1>修改页面</h1>
<p style="color:red;" th:text="${msg}"></p>
</body>
</html>

pojo实体类
在这里插入图片描述
第二步 pojo实体类

package com.kuang.w.pojo;

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

import java.io.Serializable;

/**
 * @ClassName : User  //类名
 * @Description : 用户的封装  //描述
 * @Author : W //作者
 * @Date: 2021/5/16  11:10
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 123L;
    private int id;
    private String name;
    private String password;
    private int tid;
    private String perms;

}


第三步 构建mapper层(dao层)
在这里插入图片描述

package com.kuang.w.mapper;

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

/**
 * @ClassName : UserMapper  //类名
 * @Description : 用户名的 dao层  //描述
 * @Author : W //作者
 * @Date: 2021/5/16  11:13
 * @Repository 表示这是一个dao层
 * @Mapper 表示把这个类是mybatis注入到spring的容器
 */
@Repository
@Mapper
public interface UserMapper {
    /**
     * class queryUserByName(String name)
     *
     * @param name
     * @return user
     * @Data
     */
    User queryUserByName(String name);
}


第四步 mapper层(dao)接口
在这里插入图片描述
第六步 实现mapper接口 UserMapper.xml

<?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.kuang.w.mapper.UserMapper">
    <!--开启缓存-->   <!-- 在这里使用了二级缓存 实体类必须要实现序列化接口 implements Serializable  -->
    <cache/>

    <select id="queryUserByName" parameterType="String" resultType="User">
        select *
        from mybatis.user
        where name = #{name}
    </select>
</mapper>

第七步 service层
在这里插入图片描述

  • UserService接口
package com.kuang.w.service;

import com.kuang.w.pojo.User;

/**
 * @ClassName : UserService  //类名
 * @Description : 用户的服务层  //描述
 * @Author : W //作者
 * @Date: 2021/5/16  11:32
 */
public interface UserService {
    /**
     * class queryUserByName(String name)
     *
     * @param name
     * @return user
     * @Data
     */
    User queryUserByName(String name);
}


  • 实现UserService的接口UserServiceImpl 类
package com.kuang.w.service;

import com.kuang.w.mapper.UserMapper;
import com.kuang.w.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName : UserServiceImpl  //类名
 * @Description : 用户的服务的实现层  //描述
 * @Author : W //作者
 * @Date: 2021/5/16  11:34
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

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


第八步 controller层(mvc 控制层)
在这里插入图片描述

  • Controller类
package com.kuang.w.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.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName : MyController  //类名
 * @Description : 页面跳转  //描述
 * @Author : W //作者
 * @Date: 2021/5/15  10:12
 */
@Controller
public class MyController {
    @RequestMapping({"/", "/index", "/a"})
    public String toIndex(Model model) {
        model.addAttribute ("msg", "hello shiro");
        return "index";
    }

    @RequestMapping({"/add", "/ad"})
    public String toadd(Model model) {
        model.addAttribute ("msg", "add");
        return "user/add";
    }

    @RequestMapping("/up")
    public String toUp(Model model) {
        model.addAttribute ("msg", "update");
        return "user/update";
    }

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

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //1 获取当前用户
        /**
         *   Subject用户
         *         SecurityManager管理所有用户
         *         Realm连接 数据*/
        Subject subject = SecurityUtils.getSubject ();
        //封装用户信息
        UsernamePasswordToken token = new UsernamePasswordToken (username, password);
        try {
            //执行的登录的方法
            subject.login (token);

            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute ("msg", "用户名错误(UnknownAccountException)!");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute ("msg", "密码错误(IncorrectCredentialsException)!");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String toNoauth() {
        return "您没有权限,不可以查看!";
    }
}

第九步 配置类config
在这里插入图片描述

  • ShiroConfig

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

/**
 * @ClassName : ShiroConfig  //类名
 * @Description : config配置  //描述
 * @Author : W //作者
 * @Date: 2021/5/15  10:46
 */
@Configuration
public class ShiroConfig {
    /**
     * ShiroFilterFactoryBean第3步
     * DafaultWebSecurityManager第2步
     * 创建 realm对象,需要自定义类:第1步
     */
    /**
     * ShiroFilterFactoryBean第3步
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("DWebSecurityManager") DefaultWebSecurityManager DWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean ();
        shiroFilterFactoryBean.setSecurityManager (DWebSecurityManager);

        /**
         * 添Jmishiro的内置过滤器 第3步
         *
         * anon:无需认 证就可以访问
         * authc:必须认证了 才能让问
         * user:必须拥有 记住我功能才能用
         * perms:拥有的对像 资源的权限才能访问;
         * role:拥有某 个角色权限才能访问
         * */
        Map<String, String> configMap = new LinkedHashMap<> ();

        configMap.put ("/add", "perms[user:add]");
        //授权 正常情况下 没有权限会跳到没有权限会的页面  设置权限:perms[user:update]
        configMap.put ("/up", "perms[user:update]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap (configMap);
        //设置请求,如果没有权限设置跳转到登录页面
        shiroFilterFactoryBean.setLoginUrl ("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl ("/noauth");
        return shiroFilterFactoryBean;
    }

    /**
     * * DafaultWebSecurityManager第2步
     */
    @Bean(name = "DWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealms") UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager ();
        //关联userRealm 特别重要
        defaultWebSecurityManager.setRealm (userRealm);


        return defaultWebSecurityManager;
    }

    /**
     * 创建realm对象,需要自定义 类:第1步
     *
     * @Bean(name = "userRealms")给方法附上名字
     */
    @Bean(name = "userRealms")
    public UserRealm userRealm() {
        return new UserRealm ();
    }

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

  • UserRealm类 (shrio的授权、认证)
package com.kuang.w.config;

import com.kuang.w.pojo.User;
import com.kuang.w.service.UserServiceImpl;
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.mgt.SecurityManager;
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;

import javax.security.sasl.AuthorizeCallback;

/**
 * @ClassName : UserRealm  //类名
 * @Description : 自定义类  //描述
 * @Author : W //作者
 * @Date: 2021/5/15  10:50
 */

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserServiceImpl userService;

    /**
     * 2 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println ("执行了==>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();

        //  subjectUser  拿到当前用户这个对象
        Subject subjectUser = SecurityUtils.getSubject ();
        //拿到user对象
        User principalUser = (User) subjectUser.getPrincipal ();

        //当前用户的权限
        info.addStringPermission (principalUser.getPerms ());
        // **没有配置是返回为空 认证了要返回SimpleAuthorizationInfo | return null;
        return info;
    }

    /**
     * 1 先认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println ("执行了==>认证doGetAuthenticationInfo");

        /**
         *   Subject用户
         *         SecurityManager管理所有用户
         *         Realm连接 数据*/
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 链接数据库
        // 调用userService的方法 进行查询有无用户
        User user = userService.queryUserByName (userToken.getUsername ());



     /*   if (!userToken.getUsername ().equals (user.getName ())) {
            return null;
            //抛出异常
        }*/
        if (user == null) {
            //如果没有这个人
            return null;
            //抛出异常
        }
// 存session的值  用来判断是否显示index 登录连接
        Subject subject = SecurityUtils.getSubject ();
        Session session = subject.getSession ();
        session.setAttribute ("loginUser", user);
//密码认证
        return new SimpleAuthenticationInfo (user, user.getPassword (), "");
    }
}


在这里插入图片描述

  • application.properties配置
mybatis.type-aliases-package=com.kuang.w.pojo
mybatis.mapper-locations=classpath:mapper/*.xm
  • application.yml
spring:
  datasource:
    username: root
    password: 123
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    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

完结。。。。。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cookie3_1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值