Shiro, please move onShiro’s official website

1. Create a SpringBoot project

Use the Spring initializer to create it

2. Introduce dependencies

<! -- Shiro dependency -->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-starter</artifactId>
  <version>1.5.3</version>
</dependency>
Copy the code

3. Configure shiro

Write it up front. Three important concepts

Subject: represents the current user, which can be a person or a third-party service. In a single application, it can be considered a synonym for User.

SecurityManager: manage all the Subject, for Web applications generally use DefaultWebSecurityManager. Realms: For authentication of permissions, we do it ourselves. Is an executor, responsible for the real authentication and authentication.

  1. Creating a Configuration Class

package com.almond.springbootshiro.common.config;

import com.almond.springbootshiro.common.realms.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/** * shiro configuration class */
@Configuration
public class ShiroConfig {
    // 1. Create shiroFilter to block all requests
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // Set the security manager
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        Map<String, String> map = new LinkedHashMap<>();
        // Set system public resources that do not require authentication or authorization
        map.put("/user/login"."anon");
        map.put("/user/register"."anon");

        map.put("/register.jsp"."anon");
        // Set the resources that need to be authenticated and authorized
        map.put("/ * *"."authc"); // AuthC requests require authorization and authentication

        // Set the default resource path
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    2. Create a security manager
    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // Security manager sets the realm
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    // create a custom realm
    @Bean
    public Realm realm(HashedCredentialsMatcher hashedCredentialsMatcher) {
        MyRealm myRealm = new MyRealm();
        // Modify the credential verifier
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        returnmyRealm; }}Copy the code
  1. Create a custom Realm

package com.almond.springbootshiro.common.realms;

import com.almond.springbootshiro.mapper.TUserMapper;
import com.almond.springbootshiro.po.TUsers;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Resource
    private TUserMapper tUserMapper;

    / / authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
        // Get master identity information
        String principal = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // Add identity permission
        authorizationInfo.addRole("user");
        // Add resource permissions
        List<String> strings = Arrays.asList("sys:user:add"."sys:user:update");
        authorizationInfo.addStringPermissions(strings);
        return authorizationInfo;
    }

    / / verification
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        TUsers users = tUserMapper.getOne(principal);
        if (null == principal || "".equals(principal)) {
        	// It is recommended to throw custom exceptions
            throw new RuntimeException("Token information missing");
        }
        if (principal.equals(users.getUsername())) {
            if (null == users.getPassword() || "".equals(users.getPassword())) {
            	// It is recommended to throw custom exceptions
                throw new RuntimeException("User information missing");
            }
            return new SimpleAuthenticationInfo(principal, users.getPassword(), ByteSource.Util.bytes(users.getSlat()), getName());
        }
        return null; }}Copy the code
  1. Salt tools

package com.almond.springbootshiro.common.utils;

import java.util.Random;

public class SaltUtil {
    public static String getSalt(Integer n) {
        StringBuffer salt = new StringBuffer();
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789{}@! # $% ^ & * () < >? |".toCharArray();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            salt.append(aChar);
        }
        return salt.toString();
    }

    public static void main(String[] args) {
        String salt = getSalt(5); System.out.println(salt); }}Copy the code

4. Front-end page, using JSP

  1. The home page

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<! doctypehtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>The home page</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>
<ul>
    <shiro:hasAnyRoles name="user,admin">
        <li><a href="${pageContext.request.contextPath}/resource/one">Resource 1 (visible to user&&admin)</a></li>
        <ul>
            <shiro:hasPermission name="sys:user:add">
                <li>add</li>
            </shiro:hasPermission>
            <shiro:hasPermission name="sys:user:update">
                <li>Modify the</li>
            </shiro:hasPermission>
            <shiro:hasPermission name="sys:user:*">
                <li>The query</li>
            </shiro:hasPermission>
        </ul>
    </shiro:hasAnyRoles>
    <shiro:hasRole name="admin">
        <li><a href="${pageContext.request.contextPath}/resource/two">Resource 2 (visible to admin)</a></li>
        <li><a href="${pageContext.request.contextPath}/resource/three">Resource 2 (visible to admin)</a></li>
    </shiro:hasRole>
</ul>
</body>
</html>
Copy the code
  1. The login form

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<! doctypehtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>The login</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">User name:<input name="username" type="text"/><br/>Password:<input name="password" type="password"/><br/>
    <input value="Login" type="submit"/>
</form>
</body>
</html>
Copy the code
  1. Registration form

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<! doctypehtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>registered</h1>
<form action="${pageContext.request.contextPath}/user/register" method="post">User name:<input type="text" name="username" /><br />Password:<input type="password" name="password" /><br />
    <input type="submit" value="Registered">
</form>
</body>
</html>
Copy the code

Complete code movegitee