Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate Shiro with SpringBoot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how SpringBoot integrates Shiro. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Analysis of SpringBoot integrating Shiro ideas Analysis of Authentication process

We integrate our SpringBoot applications into shiro, and the main purpose is to get shiro to help us deal with authentication and authorization. In other words, we need to let shiro take over the session of our SpringBoot application. Let every request of the user be authenticated and authorized by shiro. Therefore, we need to intercept the user request and forward it to shiro for processing, which is provided by shiro, ShiroFilter.

Steps:

Users initiate requests through clients (browser, mobile App, Mini Program)

ShiroFilter intercepts the request and determines whether the requested resource is protected:

2.1 Yes, perform step 3

2.2 if not, just let it go.

Determine whether the user has been authenticated:

3.1 Yes, perform step 4

3.2 No, redirect the user request to the authentication page and let the user authenticate first

Compare the user permission information with the permission information needed to access the resource:

4.1 if the user has access rights, it will be released.

4.2 user does not have permission, return the corresponding prompt of 403

Database analysis and design

We keep data about our authentication and permissions through MySQL. The user-role-permission model is used to manage the user rights information dynamically.

We abstract the menu, button and back-end interface of the system into the resource data of the system. The following is the design of the database table:

Download the sql script at the end of the article.

Integrate step environment to build maven

Create a web application for SpringBoot and introduce the following dependencies

Org.apache.shiro shiro-spring-boot-web-starter 1.6.0 adds CRUD support for users, roles, and resources

The code is omitted here and does not affect understanding, and the complete code can be downloaded from the way provided at the end of the article.

Configure Shiro Custom Realm/** Custom Realm, use mysql data source * @ author Lai handle bingfengdev@aliyun.com * @ version 1.0 * @ date 9:09 * / public class MySQLRealm extends AuthorizingRealm {@ Autowired private IUserService userService; @ Autowired private IRoleService roleService; @ Autowired private IResourceService resourceService / * license * @ param principals * @ return * / @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {String username = (String) principals.getPrimaryPrincipal (); List roleList = roleService.findByUsername (username); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo (); for (Role role: roleList) {authorizationInfo.addRole (role.getRoleName ()) } List roleIdList = new ArrayList (); for (Role role: roleList) {roleIdList.add (role.getRoleId ());} List resourceList = resourceService.findByRoleIds (roleIdList); for (Resource resource: resourceList) {authorizationInfo.addStringPermission (resource.getResourcePermissionTag ());} return authorizationInfo } / * Certification * @ param token * @ return * @ throws AuthenticationException * / @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {if (token==null) {return null;} String principal = (String) token.getPrincipal (); User user = userService.findByUsername (principal) SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo (user.getUsername (), user.getPassword (), ByteSource.Util.bytes (user.getSalt ()), getName ()); return simpleAuthenticationInfo;}}

The Realm object in shiro acts as the data source of authentication and authorization information. For more information about custom Realm, please refer to my article "getting started with Shiro-using Custom Realm to complete Certification | Middle period of gas training".

ShiroConfig/**shiro configuration class * @ author version bingfengdev@aliyun.com * @ date 9:11 on 2020-10-6 * / @ Configurationpublic class ShiroConfig {/ * create ShiroFilter interceptor * @ return ShiroFilterFactoryBean * / @ Bean (name = "shiroFilterFactoryBean") public ShiroFilterFactoryBean getShiroFilterFactoryBean (DefaultWebSecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean (); shiroFilterFactoryBean.setSecurityManager (securityManager) / / configure not to block paths and intercept paths, HashMap map = new HashMap (5); map.put ("/ authc/**", "anon"); map.put ("/ login.html", "anon"); map.put ("/ js/**", "anon"); map.put ("/ css/**", "anon") Map.put ("/ * *", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap (map); / / override the default login url shiroFilterFactoryBean.setLoginUrl ("/ authc/unauthc"); return shiroFilterFactoryBean;} @ Bean public Realm getRealm () {/ / set the credential matcher to hash credential matcher HashedCredentialsMatcher myCredentialsMatcher = new HashedCredentialsMatcher () / / set algorithm myCredentialsMatcher.setHashAlgorithmName ("md5"); / / number of hashes myCredentialsMatcher.setHashIterations (512); MySQLRealm realm = new MySQLRealm (); realm.setCredentialsMatcher (myCredentialsMatcher); return realm } / * create a security manager under the shiro web application * @ return DefaultWebSecurityManager * / @ Bean public DefaultWebSecurityManager getSecurityManager (Realm realm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); securityManager.setRealm (realm); SecurityUtils.setSecurityManager (securityManager); return securityManager;}}

In the preparation of shiro configuration class this step, we need to pay attention to, because we use md5+salt+hash to encrypt our password, so to replace the default credential matcher CredentialsMatcher object, for this part of the content, please refer to my article "shiro introduction to learn-use MD5 and salt for encryption | later period of gas training".

Implement authentication module VO layer / * * authentication request parameters * @ author bingfengdev@aliyun.com * @ version 1.0 * @ date 15:12 on 2020-10-7 * / @ Datapublic class LoginVO implements Serializable {private String username; private String password } web layer / * * Authentication Module * @ author bingfengdev@aliyun.com * @ version 1.0 * @ date 10:07 on 2020-10-6 * / @ RestController@RequestMapping ("/ authc") public class AuthcController {@ Autowired private AuthcService authcService; @ PostMapping ("/ login") public boolean login (@ RequestBody LoginVO loginVO) {return authcService.login (loginVO) } @ GetMapping ("/ unauthc") public String unauthc () {return "Please log in first";}} service layer / * * @ author Lai handle bingfengdev@aliyun.com * @ version 1.0 * @ date, 2020-10-7 15:15 * / @ Servicepublic class AuthcServiceImpl implements AuthcService {@ Override public boolean login (LoginVO loginVO) throws AuthenticationException {if (loginVO==null) {return false } if (loginVO.getUsername () = = null | | ".equals (loginVO.getUsername () {return false;} if (loginVO.getPassword () = = null | |" .equals (loginVO.getPassword () {return false;} Subject subject = SecurityUtils.getSubject (); UsernamePasswordToken token = new UsernamePasswordToken (loginVO.getUsername (), loginVO.getPassword ()); subject.login (token) Return true;}} implement product module / * * product module * @ author bingfengdev@aliyun.com * @ version 1.0 * @ date 10:14 on 2020-10-6 * / @ RestController@RequestMapping ("/ product") public class ProductController {@ RequiresPermissions ("product:get") @ GetMapping ("/ get/list") public String getProductList () {return "productList" @ RequiresPermissions ("product:delete") @ GetMapping ("/ delete") public String deleteProduct () {return "Delete Product data";}}

Shiro has two main annotations for annotations to implement access control: RequiresPermissions and RequiresRoles. Can be used on classes and methods. The specific use can be determined according to the granularity of your own system permissions.

For these two comments, there are two parameters:

Value: corresponding to the permission string value of permission and the role name of role, respectively

Logical: logical operator. This is an enumerated type with two values AND and OR. When using AND, it means that all incoming value values need to be met, and OR means that only one value needs to be satisfied. Default is AND

For more information about shiro permissions (access control), you can read my other article, "getting started with shiro-Authorization (Authorization) | initial stage of Foundation Building".

Simply test the passing of the certification

The situation in which the certification failed.

Get product information

Request resources that do not have access

The default message prompt can be changed.

Direct access to protected resources without authentication

These are all the contents of the article "how SpringBoot integrates Shiro". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report