1 explain

1.1 Realm The role of

Realm Related to data interaction during authentication and authorization , amount to DAO layer .

1.2 AuthorizingRealm

》 Hierarchical diagram

》 effect
Inherit AuthorizingRealm Post class rewriting doGetAuthorizationInfo and doGetAuthenticationInfo You can implement authorization and authentication logic .

2 Code implementation

2.1 Create a maven Project and introduction shiro、junit rely on

2.2 Create a class inheritance AuthorizingRealm

2.3 rewrite doGetAuthorizationInfo and doGetAuthenticationInfo

2.4 Complete code

package com.xunyji.demo04.realm;
import com.xunyji.demo0.StringUtilsXyj;
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.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; /**
* @author AltEnter
* @create 2019-01-23 20:32
* @desc Customize Realm,md
public class CustomRealm extends AuthorizingRealm { private Logger log = LoggerFactory.getLogger(this.getClass()); private Map<String, String> userMap = new HashMap<String, String>(); {
// userMap.put("fury", "111111");
// userMap.put("fury", "96e79218965eb72c92a549dd5a330112");
userMap.put("fury", "66b747dd6c7c7c8ca4227a67fff8ea6e");
} /**
* Authorization logic
* @param principals
* @return
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 01 Get username
String username = (String) principals.getPrimaryPrincipal();
// 02 Get permission collection
Set<String> permissionSet = getPermissionSetByUsername(username);
// 03 Get role collection
Set<String> roleSet = getRoleSetByUsername(username);
// 04 encapsulation SimpleAuthorizationInfo object
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
return simpleAuthorizationInfo;
} /**
* Get permission set based on user name
* @param username
* @return
private Set<String> getPermissionSetByUsername(String username) {
HashSet<String> permissionSet = new HashSet<>();
return permissionSet;
} /**
* Get role collection based on user name
* @param username
* @return
private Set<String> getRoleSetByUsername(String username) {
HashSet<String> roleSet = new HashSet<>();
return roleSet;
} /**
* The authentication logic
* @param token
* @return
* @throws AuthenticationException
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 01 Get front-end user name and password
String username = (String) token.getPrincipal();
String passoword = new String((char[]) token.getCredentials());
if (StringUtilsXyj.isEmpty(passoword) || StringUtilsXyj.isEmpty(username)) {
String msg = "doGetAuthenticationInfo - User name and password cannot be empty ";
throw new RuntimeException(msg);
log.info(String.format("doGetAuthenticationInfo - The user information transmitted from the front end is - The user is called :%s , User password is :%s", username, passoword));
System.out.println(String.format("doGetAuthenticationInfo - The user information transmitted from the front end is - The user is called :%s , User password is :%s", username, passoword)); // 02 Get user password according to user name
String pwd = getPasswordByUsername(username);
// 03 Front end password encryption and salt addition
passoword = string2Md5Hash(passoword, "AltEnter");
System.out.println(" The password after salt encryption is :" + pwd); // 04 Password comparison
if (passoword.equals(pwd)) {
// encapsulation SimpleAuthenticationInfo object
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, passoword, getName());
// Salt treatment
return simpleAuthenticationInfo;
} else {
String msg = "doGetAuthenticationInfo - Wrong username or password ";
throw new RuntimeException(msg);
} /**
* Password encryption and salt addition
* @param password Password to be encrypted
* @param salt salt
* @return Encrypted and salted passwords
private String string2Md5Hash(String password, String salt) {
return new Md5Hash(password, salt).toString();
} /**
* Get password based on user name
* @param username
* @return
private String getPasswordByUsername(String username) {
String pwd = userMap.get(username);
return pwd;
} public static void main(String[] args) {
// Md5Hash md5Hash = new Md5Hash("111111");
// System.out.println("111111 The result after encryption is :" + md5Hash.toString());
// 96e79218965eb72c92a549dd5a330112 Md5Hash md5Hash = new Md5Hash("111111", "AltEnter");
System.out.println("111111 after MD5 Encryption and AltEnter The result after adding salt is :" + md5Hash.toString());
// 66b747dd6c7c7c8ca4227a67fff8ea6e

3 Test class

package com.xunyji.demo04.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test; import static org.junit.Assert.*; public class CustomRealmTest {
public void test01() {
CustomRealm customRealm = new CustomRealm();
// shiro encryption start
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
// Choose encryption method
// Number of encryption
// Customize Realm Set encryption rules
// shiro encryption end // Change authentication policy start
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
FirstSuccessfulStrategy firstSuccessfulStrategy = new FirstSuccessfulStrategy();
ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
// Change authentication policy end defaultSecurityManager.setRealm(customRealm); SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("fury", "111111"); subject.login(token);
System.out.println(String.format(" The certification information is :%s", subject.isAuthenticated())); System.out.println(String.format(" Have admin Roles? ? - %s", subject.hasRole("admin")));
System.out.println(String.format(" Have user:create Jurisdiction? ? - %s", subject.isPermitted("user:create"))); subject.logout();
System.out.println(String.format(" The certification information is :%s", subject.isAuthenticated())); }

4 Be careful

4.1 You can give SecurityManager Set authentication policy

4.2 You can give Realm Set up MD5 encryption

4.3 SecurityManager Authentication policy must be set before setting Realm

Shrio04 Customize Realm More articles about

  1. Permission framework - shiro Customize realm

    The default used in the last article is realm To achieve a simple login , It's just a demo, The real project must be connected to the database First, create a custom realm file , as follows : stay shiro Inject custom realm The fully qualified class name of : ...

  2. Shrio Certification details + Customize Realm

    Authentication( Identity Authentication ) yes Shiro The first step in access control , Used to tell the system that you are you . At the time of submission of certification , We need to submit two messages to the system : Principals: Is a unique property that represents the user , It can be a user ...

  3. Shiro Second articles 【 Introduce Shiro、 The certification process 、 Customize realm、 Customize realm Support md5】

    What is? Shiro shiro yes apache An open source framework , It's a framework for rights management , Realization User authentication . User authorization . spring There is spring security ( Original name Acegi), It's a permission framework , It and sp ...

  4. shiro( Two ) Customize realm, Simulate database query validation

    Customize a realm class , Realization realm Interface package com; import org.apache.shiro.authc.*; import org.apache.shiro.realm.Re ...

  5. shiro Customize Realm

    1.1  Customize Realm The program above uses shiro Self contained IniRealm,IniRealm from ini Read the user's information in the configuration file , In most cases, you need to read user information from the database of the system , So you need to customize it realm. ...

  6. Shiro introduction - By customizing Realm Even the database for authorization

    shiro-realm.ini [main] # Customize Realm myRealm=test.shiro.MyRealm # take myRealm Set to securityManager, amount to Spring Notes in ...

  7. Shiro introduction - By customizing Realm Even the number of database authentication (md5+salt form )

    shiro-realm-md5.ini [main] # Defines a credential matcher credentialsMatcher=org.apache.shiro.authc.credential.HashedCrede ...

  8. Shiro introduction - By customizing Realm Even the number of database authentication

    add to shiro-realm.ini file [main] # Customize Realm myRealm=test.shiro.MyRealm # take myRealm Set to securityManager, amount to Sprin ...

  9. shiro course 2( Customize Realm)

    adopt shiro course 1 We found that only data source information is defined in ini The file is not compatible with our actual development environment , So we want to be able to customize Realm. Customize Realm The implementation of the Create custom Realmjava class Create a jav ...

Random recommendation

  1. Linux Journey to the core Linked list implementation

    #include "stdio.h" #include "stdlib.h" struct list_head{ struct list_head *prev; ...

  2. C# winform in TabControl Dynamic display TabPage

    stay winform Application ,tabcontrol Is a good control , Multiple tabs can be provided on demand (TabPages), But there's a problem when a project needs multiple tabs , But different functions require different tabs to be displayed , The rest is not due to ...

  3. 【 turn 】 Use DevExpress Of WebChartControl Control to draw a chart ( Histogram 、 Broken line diagram 、 The pie chart )

    My first blog , No experience , The main thing is to compare yourself with Dev Some of our studies are posted for discussion , I hope you can help me to correct the shortcomings . WebChartControl yes DevExpress Control group under a Web The chart control , It uses very ...

  4. Implement singleton mode C++ edition

    Let's start with the simplest C++ The singleton pattern class CSingleton { private: CSingleton(){} static CSingleton *pInstance; public: sta ...

  5. [Windows Phone] Latitude and longitude of the map control

    original text :[Windows Phone] Latitude and longitude of the map control Preface This paper mainly demonstrates how to use the latitude and longitude of the map and how to display landmarks and pedestrian streets , And through the scroll control map zoom function . ? implementation step1 Create a project . ? step ...

  6. adopt VS2010 An error occurred when creating a strong named file in the command prompt window

    The problem description is shown in the figure Solution 00000005 intend Access Denied( Access is denied ). as a result of :Program Files(x86) The directory is read-only to ordinary users and administrators who have not been elevated . So just give Use ...

  7. angular2 route

    Routing is a module , Command line generation :ng generate module routerTest; Set up your own : Routing module description : Routes: Routing configuration , Routing profile type . such as :const routing:Rout ...

  8. C# And winform Achieve file drag and drop function

    When you drag a file to a control in a form , Display the path of the control on the control , As long as you get the path, you can naturally read the contents of the file Set the properties of a control AllowDrop Set to true, Then add DragDrop.DragEnter ...

  9. angular2 How to use the project sass

    angular/cli Support use sass New project : If it's a new one angular Engineering application sass: ng new My_New_Project --style=sass In this way, all the styles will be used sa ...

  10. PAT1091:Acute Stroke

    1091. Acute Stroke (30) The time limit 400 ms Memory limit 65536 kB Code length limit 16000 B The procedure of judging questions Standard author CHEN, Yue One impo ...