3、入門代碼

快速入門代碼 github.com/apache/shir…java

先建立項目 【紅線框起來的,其餘文件你先當作沒看見】 這裏寫圖片描述 添加pom.xml 內容 github.com/apache/shir…git

<?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">

    <name>samples</name>
    <groupId>com.shiro</groupId>
    <artifactId>samples</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>


    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>

        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

</project>
複製代碼

把 log4j.properties 和 shiro.ini 粘貼到 resources中 github.com/apache/shir… log4j.properties文件github

#
# 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=TRACE

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
複製代碼

shiro.ini 文件spring

#
# 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
複製代碼

建立 Quickstart.java github.com/apache/shir…express

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.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
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;

/**
 * @author: admin
 * @create: 2018-06-28 16:35
 * 描述:
 */
public class Quickstart{

    static Logger logger = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        Session session = subject.getSession();

        session.setAttribute("name", "張三");


        String name = (String) session.getAttribute("name");
        if (null != name) {
            logger.info("得到 session中的 name:" + name);

        }

        if (!subject.isAuthenticated()) {
            logger.info("沒有登陸 ,準備登陸。。。。");

            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            Object credentials = token.getCredentials();

            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                logger.info("用戶名錯誤");

            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                logger.info("密碼錯誤");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }

        }

        logger.info("已經登陸,登陸用戶" + subject.getPrincipal() + ",");


        if (subject.hasRole("goodguy")) {
            logger.info("用戶" + subject.getPrincipal() + "擁有權限goodguy");

        } else {
            logger.info("用戶" + subject.getPrincipal() + "不曾擁有權限goodguy");
        }

        if (subject.isPermitted("winnebago:drive:eagle5")) {
            logger.info("用戶" + subject.getPrincipal() + "擁有權限winnebago:drive:eagle5");

        } else {
            logger.info("用戶" + subject.getPrincipal() + "不曾擁有次權限winnebago:drive:eagle5");
        }
        if (subject.isPermitted("lightsaber:*")) {
            logger.info("用戶" + subject.getPrincipal() + "擁有權限lightsaber:*");

        } else {
            logger.info("用戶" + subject.getPrincipal() + "不曾擁有次權限lightsaber:*");
        }
//

        subject.logout();

        logger.info("用戶退出成功" );
    }

}
複製代碼

代碼流程其實很簡單 就是拿到 SecurityManager 來與其餘進行交互 apache

  1. Subject:主體,表明了當前「用戶」。這個用戶不必定是一個具體的人,與當前應用交互的任何東西都是 Subject,如網絡爬蟲,機器人等。全部 Subject 都綁定到 SecurityManager,與 Subject 的全部交互都會委託給 SecurityManager。咱們能夠把 Subject 認爲是一個門面,SecurityManager 纔是實際的執行者。
  2. SecurityManager:安全管理器。即全部與安全有關的操做都會與 SecurityManager 交互,且它管理着全部 Subject。能夠看出它是 Shiro 的核心,它負責其餘組件進行交互。
  3. Realm:Shiro 從 Realm 獲取安全數據(如用戶、角色、權限),就是說 SecurityManager 要驗證用戶身份,那麼它須要從 Realm 獲取相應的用戶進行比較以肯定用戶身份是否合法,也須要從 Realm 獲得用戶相應的角色/權限進行驗證用戶是否能進行操做。 能夠配置多個但最少得有一個

subject.login 就是進行登陸 經過realm進行驗證 在講shiro源碼的時候會提到這一塊安全

UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
 
                subject.login(token);
複製代碼
相關文章
相關標籤/搜索