三、Springboot 整合Shiro---01认证

本篇基于:二、Sprinboot 整合 beetl 模板引擎

shiro是什么?

Shiro是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、密码学和会话管理。使用Shiro易于理解的API,您可以快速且轻松地保护任何应用程序——从最小的移动应用程序到最大的web和企业应用程序。

Shiro提供了应用程序安全API来执行以下方面(我喜欢将其称为应用程序安全性的4个基石:

Authentication——证明用户身份,通常称为用户登录。
Authorization——访问控制
Cryptography——保护或隐藏数据
Session Management——会话管理。管理用户特定的会话
Shiro还支持一些辅助功能,如web应用程序安全性、单元测试和多线程支持,但这些功能的存在是为了加强上述四个主要关注点。

认证: 

身份验证是验证用户身份的过程。也就是说,当用户使用一个应用程序进行身份验证时,他们就会证明他们实际上就是他们所说的那个人。这有时也被称为“登录”。这通常是一个三步骤的过程。

  • 收集用户的识别信息,称为主体,以及支持身份证明,称为凭证。
  • 向系统提交主体和凭证。
  • 如果提交的凭证与系统期望的用户标识(主体)相匹配,则用户被认为是经过身份验证的

授权:

授权本质上是访问控制——控制您的用户在您的应用程序中可以访问的内容,例如资源、web页面等。大多数用户通过使用诸如角色和权限之类的概念来执行访问控制。也就是说,用户通常被允许做一些事情,而不是根据分配给他们的角色和/或权限。然后,您的应用程序可以根据这些角色和权限的检查控制哪些功能被公开。正如您所期望的,Subject API允许您很容易地执行角色和权限检查。

会话管理:

Apache Shiro在安全框架的世界中提供了一些独特的东西:在任何应用程序和任何架构层中都可以使用一致的会话API。也就是说,Shiro为任何应用程序提供了会话编程范式——从小型的守护程序独立应用程序到最大的集群web应用程序。这意味着,如果希望使用会话的应用程序开发人员不再需要使用Servlet或EJB容器,如果他们不需要的话

域:

 shiro和应用程序的权限数据之间的桥梁,为shiro提供安全数据。 SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。

Subject (org.apache.shiro.subject.Subject) 

    与应用交互的主体,例如用户,第三方应用等。

SecurityManager (org.apache.shiro.mgt.SecurityManager)

    SecurityManager是shiro的核心,负责整合所有的组件,使他们能够方便快捷完成某项功能。例如:身份验证,权限验证等。

Authenticator (org.apache.shiro.authc.Authenticator)

     认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了。

Authorizer (org.apache.shiro.authz.Authorizer)

      来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能。

SessionManager (org.apache.shiro.session.mgt.SessionManager) 

     会话管理。

SessionDAO (org.apache.shiro.session.mgt.eis.SessionDAO) 

  数据访问对象,对session进行CRUD。

CacheManager (org.apache.shiro.cache.CacheManager)

     缓存管理器。创建和管理缓存,为 authentication, authorization 和 session management 提供缓存数据,避免直接访问数据库,提高效率。

Cryptography (org.apache.shiro.crypto.*)

     密码模块,提供加密组件。

Realms (org.apache.shiro.realm.Realm)

      可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提 供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm。

开始整合

一、在上一个项目基础上添加依赖Shiro依赖:

pom:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-example</artifactId>
        <groupId>com.xslde</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>springboot-example03</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--beetl模板引擎依赖-->
        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl-framework-starter</artifactId>
            <version>${beetl.version}</version>
        </dependency>
        <!--shiro依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>${shiro.version}</version>
        </dependency>
    </dependencies>

    <!--Maven插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、创建User.class

package com.xslde.model;

import java.io.Serializable;

/**
 * @Author xslde
 * @Description
 * @Date 2018/7/20 16:23
 */
public class User implements Serializable {


    //用户名称
    private String username;

    //用户密码
    private String password;

    //密码加盐
    private String salt;

    //用户是否可用
    private Integer available;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Integer getAvailable() {
        return available;
    }

    public void setAvailable(Integer available) {
        this.available = available;
    }
}

三、创建ShiroRealm.class

package com.xslde.configurer;

import com.xslde.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Author xslde
 * @Description
 * @Date 2018/7/20 16:30
 */
public class ShiroRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();
        if (!"xslde".equals(username)&&!"test".equals(username)){
            throw new UnknownAccountException();
        }
        User user =null;
        if ("xslde".equals(username)){
            user = new User();
            user.setUsername("xslde");
            user.setPassword("0caf568dbf30f5c33a13c56b869259fc");
            user.setSalt("abcd");
            user.setAvailable(1);
        }
        if ("test".equals(username)){
            user = new User();
            user.setUsername("test");
            user.setPassword("0caf568dbf30f5c33a13c56b869259fc");
            user.setSalt("abcd");
            user.setAvailable(0);
        }
        if (user.getAvailable()!=1){
            throw  new LockedAccountException("账户已被锁定");
        }
        return  new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
    }

    //生成一个加盐密码
    public static void main(String[] args) {
        String hashAlgorithmName = "md5";//加密类型
        Integer iteration = 2;//迭代次数
        String password = "123456";
        String salt = "abcd";
        String s = new SimpleHash(hashAlgorithmName,password,salt,iteration).toHex();
        System.out.println(s);
        //加密后的密码
        //0caf568dbf30f5c33a13c56b869259fc

    }
}

 四、创建ShiroConf.class

package com.xslde.configurer;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author xslde
 * @Description
 * @Date 2018/7/20 16:25
 */
@Configuration
public class ShiroConf {


    //注入shiro过滤器
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilter(WebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");  // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setSuccessUrl("/index");// 登录成功后要跳转的链接
        Map<String, String> chains = new LinkedHashMap<>();
        chains.put("/login", "anon");//anon表示可以匿名访问
        chains.put("/**", "authc");//表示需要认证,才能访问
        shiroFilterFactoryBean.setFilterChainDefinitionMap(chains);
        return shiroFilterFactoryBean;
    }


    //安全管理器
    @Bean
    public WebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm.
        securityManager.setRealm(shiroRealm());
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }
    
    //会话管理器
    @Bean
    public SessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        sessionManager.setGlobalSessionTimeout(1 * 60 * 60 * 1000);
        sessionManager.setDeleteInvalidSessions(true);
        sessionManager.setSessionIdCookie(simpleCookie());
        return sessionManager;
    }

    //Realm,里面是自己实现的认证和授权业务逻辑
    @Bean
    public ShiroRealm shiroRealm() {
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setCacheManager(cacheManager());
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }

    //缓存管理
    @Bean
    public EhCacheManager cacheManager() {
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
        return cacheManager;
    }

    //密码管理
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5"); //散列算法使用md5
        credentialsMatcher.setHashIterations(2);        //散列次数,2表示md5加密两次
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    //cookie管理
    @Bean
    public SimpleCookie simpleCookie() {
        SimpleCookie cookie = new SimpleCookie("sessionId");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(1 * 60 * 60);
        return cookie;
    }
}

五、在resources 下创建ehcache.xml

<ehcache name="spring_boot_shiro_ehcache">
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="100000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>
</ehcache>

六、在templates下创建login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<form action="/login" method="post">
    <div>
        <span style="color: red;">${msg!}</span>
        <br>
        <div>
            <label>用户名称:</label>
            <input type="text" name="username" placeholder="请输入用户名称!">
        </div>
        <br>
        <div>
            <label>用户密码:</label>
            <input type="password" name="password" placeholder="请输入用户密码!">
        </div>
        <br>
        <input type="submit" value="登录" style="margin-left: 100px">
    </div>
</form>
</body>
</html>

所有步骤完成后启动项目,访问http:localhost:7000,输入用户名和密码登录

登录成功后:

到此Shiro的认证功能就完成了 

项目地址:springboot-example03

猜你喜欢

转载自blog.csdn.net/xslde_com/article/details/81133553