This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
Shiro profileShiro is what? Apache Shiro is a Java security (permissions) framework Shiro can easily develop good enough applications that can be used not only in Javase environment but also in Javaee environment Shiro can complete, authentication, authorization, encryption, session management, Web integration, Cache, etc.
- ●Authentication: identity Authentication, login, verify whether the user has the corresponding identity;
- ●Authorization: verifies whether an authenticated user has a certain permission. That is, determine whether the user can perform any operations
- For example, verify whether a user has a role, or fine-grained verify whether a user has a permission on a resource!
- ●Session Manager: Session management, that is, after the user logs in, it is the first Session. All its information is in the Session before the user logs out.
- The session can be a normal JavaSE environment or a Web environment;
- ●Cryptography: to protect the security of data, such as encrypted passwords stored in a database, rather than in clear text;
- ●Web Support: Web Support, can be very easy to integrate into the Web environment;
- ●Caching: For example, after a user logs in, the user information, roles, and permissions do not need to be checked every time. This improves efficiency
- Concurrency Concurrency for multi-threaded applications is supported. For example, when a thread is opened within another thread, Concurrency is automatically transferred
- On the past
- ●Testing: provide Testing support;
- ●Run As: allow – a user to pretend to be another user (if they allow) to access;
- ● This is a very common feature that allows you to log in once and then not log in the next time
- ●Subject: any ‘user’ who can interact with the application;
- ●Security Manager: equivalent to DispatcherServlet in SpringMVC; Is Shiro’s heart, through which all concrete interactions pass
- The Security Manager controls, manages all the Subjects and is responsible for authentication, authorization, session, and cache management.
- ●Authenticator: responsible for Subject authentication, is an extension point, can be customized implementation; Authentication policies can be used
- Strategy), that is, under what circumstances is the user authenticated;
- ●Authorizer: an Authorizer, that is, an access controller, used to determine whether a subject has permission to perform the corresponding operation; It controls the user’s access to the application
- Those functions of;
- ● Realms: There can be one or more realms, which can be considered secure entity data sources. That is, secure entities can be obtained using DBC real
- Now, it can also be memory implementation and so on, provided by the user; So you’ll need to implement your own realm in your applications
- ●SessionManager: a component that manages the Session lifecycle, Shiro can be used not only in Web environments, but also in general
- JavaSE environment
- ●Authorizer: an Authorizer, that is, an access controller, used to determine whether a subject has permission to perform the corresponding operation; It controls the user’s access to the application
- Those functions of; .
- ● Realms: There can be one or more realms that can be considered secure entity data sources. That is, secure entities can be obtained using DBC real
- Now, it can also be memory implementation and so on, provided by the user; So all applications need to implement their own realm
- ●SessionManager: a component that manages the Session lifecycle, Shiro can be used not only in Web environments, but also in general
- JavaSE environment
- CH with English J”, Jane Feast:
- ●CacheManager: cache controller to manage caches such as users, roles, and permissions. Because these data basically change very little, put in slow
- Storage can improve the performance of access;
- ●Cryptography: Cryptography module, Shiro improves — some common encryption components for password encryption, decryption, etc
The first Shiro POM.xml for a quick start
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>shiro</artifactId>
<version>1.0 the SNAPSHOT</version>
<dependencies>
<! -- https://mvnrepository. com/artifact/org. apache. shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.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>
<! - log start -- >
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
Copy the code
log4j.properties
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
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
Copy the code
shiro.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 thisFile # 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:eagle5Copy the code
Just copy the first demo class from the official website
/* * 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. */
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
//import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
//import org.apache.shiro.lang.util.Factory;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since0.9 RC2 * /
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The official code is out of date, hahaha
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// Get the current executing user:
Subject currentUser = SecurityUtils.getSubject();
// Use Session to do something (no Need for Web or EJB container!!)
Session session = currentUser.getSession();
// Set session session
session.setAttribute("someKey"."aValue");
// Get the corresponding value
String value = (String) session.getAttribute("someKey");
/ / determine
if (value.equals("aValue")) {
// Print it
System.out.println("value = " + value);
log.info("Retrieved the correct value! [" + value + "]");
}
/ / · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · above is the work of the Subject
// Let's log in to the current user so that we can check roles and permissions:
if(! currentUser.isAuthenticated()) { UsernamePasswordToken token =new UsernamePasswordToken("lonestarr"."vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
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 (perhaps custom exceptions for your application?
catch (AuthenticationException ae) {
//unexpected condition? error?}}// Specify who they are:
// Prints its identity subject (in this case, the user name) :
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); }}Copy the code
The results of
"C: \ Program Files \ Java \ jdk1.8.0 _231 \ bin \ Java exe" "-javaagent:D:\idea\IntelliJ IDEA 2019.3.5\lib\idea_rt.jar=62162:D:\idea\IntelliJ IDEA 2019.3.5\bin" -Dfile.encoding=UTF-8 -classpath "C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ charsets jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ deploy the jar. C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ access - bridge - 64. The jar. C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ cldrdata jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ DNSNS jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ jaccess jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ JFXRT jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ localedata jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ nashorn jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ sunec jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ sunjce_provider jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ sunmscapi jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ sunpkcs11 jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ ext \ zipfs jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ javaws jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ jce jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ JFR jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ JFXSWT jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ jsse jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ management - agent jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ plugin jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ resources jar; C: \ Program Files \ Java \ jdk1.8.0 _231 \ jre \ lib \ rt jar; E:\shiro\target\classes; E: \ maven_jar package \ org \ apache \ shiro, shiro - core, 1.4.1, shiro - core - the 1.4.1. Jar; E: \ maven_jar package \ org \ apache \ shiro, shiro - lang, 1.4.1, shiro - lang - 1.4.1. Jar; E: \ maven_jar package \ org \ apache \ shiro, shiro - cache, 1.4.1, shiro - cache - the 1.4.1. Jar; E: \ \ org \ apache \ shiro maven_jar package \ shiro - crypto - hash \ 1.4.1 \ shiro - crypto - hash - 1.4.1. Jar; E: \ \ org \ apache \ shiro maven_jar package \ shiro - crypto - core \ 1.4.1 \ shiro - crypto - core - the 1.4.1. Jar; E: \ \ org \ apache \ shiro maven_jar package \ shiro - crypto - cipher \ 1.4.1 \ shiro - crypto - cipher - 1.4.1. Jar; E: \ \ org \ apache \ shiro maven_jar package \ shiro - config - core \ 1.4.1 \ shiro - config - core - the 1.4.1. Jar; E: \ \ org \ apache \ shiro maven_jar package \ shiro - config - ogdl \ 1.4.1 \ shiro - config - ogdl - 1.4.1. Jar; E: \ \ maven_jar package Commons beanutils \ Commons - beanutils \ 1.9.3 \ Commons beanutils - 1.9.3. Jar; E: \ \ maven_jar package Commons - collections, Commons - collections, 3.2.2, Commons - collections - 3.2.2. Jar; E: \ maven_jar package \ org \ apache \ shiro, shiro - event, 1.4.1, shiro - event - the 1.4.1. Jar; E: \ \ org \ slf4j maven_jar package \ JCL - over - slf4j \ 1.7.21 \ JCL - over - slf4j - 1.7.21. Jar; E: \ \ org \ slf4j maven_jar package \ \ 1.7.21 \ slf4j slf4j - API - API - 1.7.21. Jar; E: \ \ org \ slf4j maven_jar package \ slf4j - log4j12\1.7.21 \ slf4j - log4j12-1.7.21. Jar; E: \ \ maven_jar package log4j, log4j, 1.2.17, log4j - 1.2.17. Jar" Quickstart
2020-12-23 2009:50.625 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler...
value = aValue
2020-12-23 2009:51.315 INFO [Quickstart] - Retrieved the correct value! [aValue]
2020-12-23 2009:51.315 INFO [Quickstart] - User [lonestarr] logged in successfully.
2020-12-23 2009:51.315 INFO [Quickstart] - May the Schwartz be with you!
2020-12-23 2009:51.315 INFO [Quickstart] - You may use a lightsaber ring. Use it wisely.
2020-12-23 2009:51.315 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!
Process finished with exit code 0
Copy the code
Analyze the source code The role assignment is explained in that INL Springboot and Shiro environment setup1. Import dependencies
<! -- Introduce thymeleaf dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<! -- Shro-spring dependencies -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
Copy the code
Write config class Shior Config class
package com.jj.demo.config;
import org.apache.shiro.mgt.SecurityManager;
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;
@Configuration
public class ShiroConfig {
// Shiro's three
/ / Subject users
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return shiroFilterFactoryBean;
}
// The SecurityManager manages all users
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
/ / associated Realm
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
// Realm connects data
@Bean
public UserRealm userRealm(a){
return newUserRealm(); }}Copy the code
Shiro’s three main // Subject users // SecurityManager manages all users
// Realm connects dataCopy the code
Write your own Realm class
package com.jj.demo.config;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
/ / authorization
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("PrincipalCollection = Authorization" + principalCollection);
return null;
}
/ / certification
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("AuthenticationToken = authentication" + authenticationToken);
return null; }}Copy the code
Simple few pages and control layers Control layer
package com.jj.demo.control;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Shirocontrol {
@RequestMapping({"/","/index"})
public String demo(Model model){
model.addAttribute("msg"."Hello, my first Springboot-SGIRo program!!");
return "index";
}
// Jump to add
@RequestMapping("/user/add")
public String add(a){
return "/user/add";
}
// Jump to update
@RequestMapping("/user/update")
public String update(a){
return "/user/update"; }}Copy the code
Achieve login interception function!! Simply write a login control layer, and the login page can be the effect Go to the URL control layer we specify and write a login method
/ / login
@RequestMapping("login")
public String login1(String name,String pwd,Model model){
// Get the current user
Subject subject = SecurityUtils.getSubject();
// Encapsulate the current logon data to get the token
UsernamePasswordToken token = new UsernamePasswordToken(name,pwd);
try {
subject.login(token); // Execute the login method without exception
return "index";
//
// The user name is normal
} catch (UnknownAccountException uae) {
model.addAttribute("msg"."Wrong username!!");
return "login";
}
catch (IncorrectCredentialsException ice) {
model.addAttribute("msg"."Password error");
return "login"; }}Copy the code
Will automatically be associated with the authentication of the UserRealm we wrote. The effect
2020-12-24 1609:05.446 INFO 4028 --- [ main] com.jj.demo.DemoApplication : Started DemoApplication in 1.929 seconds (JVM running for 3.107)
2020-12-24 1609:16.455 INFO 4028 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-24 1609:16.456 INFO 4028 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-12-24 1609:16.458 INFO 4028 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2Ms authenticationToken = certification org. Apache. Shiro. Authc. The UsernamePasswordToken - jiaojiao, rememberMe =false
Copy the code
Connect to the database testSimple names for the entity class, PWD Simple according to the name to do a query specific code is very simple. Inject the Service layer into UserRealm!!
Write pom.xml in your own UserRealm authentication class
<! - Lombok introduction -- -- >
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<! -- Shro-spring dependencies -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<! -- log4-->
<! - log start -- >
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<! -- druid connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- mysql 的-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<! -- Mybatis bag -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
Copy the code
Yml configuration
# data source configuration
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/op? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
druid:
# initial connection number
initialSize: 5
Minimum number of connection pools
minIdle: 10
# Maximum number of connection pools
maxActive: 20
Set the connection wait timeout
maxWait: 60000
Configure how often to detect idle connections that need to be closed, in milliseconds
timeBetweenEvictionRunsMillis: 60000
Set the minimum time for a connection to live in the pool in milliseconds
minEvictableIdleTimeMillis: 300000
Set the maximum number of milliseconds for a connection to live in the pool
maxEvictableIdleTimeMillis: 900000
Configure to check whether the connection is valid
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# mybatis configuration
mybatis:
configuration:
# SQL log display, using standard display here
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Package to integrate aliases
SQL > select * from user_name where name = '_' and name = '_'
# map-underscore-to-camel-case: true
Configure the mapper file path
type-aliases-package: com.jj.demo.pojo
mapper-locations: classpath:mapper/*.xml
Copy the code
/ / certification
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("AuthenticationToken = authentication" + authenticationToken);
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
vip vip = vipdaoserviceimpl.showbyname(userToken.getUsername());
if (vip.getName()==null) {return null;
// Throw an exception
}
// Password authentication is done by Shiro
return new SimpleAuthenticationInfo("",vip.getPwd(),"");
}
Copy the code
Authorization features!!Add a field to a database Add the following code to ShiroConfig UserRealm class
/ / authorization
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("PrincipalCollection = Authorization" + principalCollection);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// Add method
info.addStringPermission("vip:add");
info.addStringPermission("vip:update");
// Get the current login object
Subject subject = SecurityUtils.getSubject();
// Get the VIP object
vip vip = (com.jj.demo.pojo.vip) subject.getPrincipal();
// Set the permissions of the current user
System.out.println("vip.getPerms() = " + vip.getPerms());
info.addStringPermission(vip.getPerms());
return info;
}
Copy the code