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

What is Java springboot's method of integrating the Shiro framework?

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what is the method of Java springboot integrating Shiro framework". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the method of integrating the Shiro framework with Java springboot?"

Shiro introduction

Shiro is a security framework with three main classes: Subject, SecurityManager, and Realm

Subject: represents the current user

SecurityManager: the security manager, that is, all security-related operations interact with SecurityManager; and it manages all Subject;. You can see that it is the core of Shiro, and it is responsible for interacting with other components of Shiro, which is equivalent to the role of DispatcherServlet in SpringMVC.

Realm:Shiro obtains security data (such as users, roles, permissions) from Realm

Shiro frame structure diagram

Springboot integrates Shiro

To build a project, check spring web and import dependencies.

Org.springframework.boot spring-boot-starter-thymeleaf org.apache.shiro shiro-spring 1.7.1 org.projectlombok lombok true 1.18.2 mysql mysql-connector-java Com.alibaba druid 1.0.9 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1 log4j log4j 1.2.17 com.github.theborakompanioni Thymeleaf-extras-shiro 2.0.0

Write a page and its control layer

The settings for forwarding are all written in the front controller in MVCConfig

@ Configurationpublic class MyMvcConfig implements WebMvcConfigurer {@ Override public void addViewControllers (ViewControllerRegistry registry) {registry.addViewController ("/") .setViewName ("index"); registry.addViewController ("/ login.html") .setViewName ("login"); registry.addViewController ("/ user/add") .setViewName ("user/add"); registry.addViewController ("/ user/update") .setViewName ("user/update") Registry.addViewController ("/ loginout") .setViewName ("login");}}

Connect to the database

Write application.yml

Spring: datasource: username: * * password: * url: jdbc:mysql://localhost:3306/db_2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true filters: stat,wall Log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true Druid.stat.slowSqlMillis=500mybatis: type-aliases-package: com.example.demo.pojo

Write pojo, dao, service three layers, dao layer can directly make the annotation of Mybatis.

The method you need is findByName (String username), which is queried by the username value passed in by the form.

Writing UserRealm needs to inherit AuthorizingRealm

Public class UserRealm extends AuthorizingRealm {@ Autowired private IuserService iuserService;// authorization @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {System.out.println ("= = > authorization"); SimpleAuthorizationInfo Info = new SimpleAuthorizationInfo (); / / get login object Subject subject = SecurityUtils.getSubject (); user principal = (user) subject.getPrincipal (); / / get user Info.addStringPermission (principal.getPerms ()) Return Info;} / / Certification @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println ("= = > Certification"); UsernamePasswordToken authenticationToken1 = (UsernamePasswordToken) authenticationToken; user byName= iuserService.findByName (authenticationToken1.getUsername ()); if (byName==null) {return null / / throw an exception with an incorrect username} / / password authentication shiro completes passing the user object to the above method to authorize return new SimpleAuthenticationInfo (byName,byName.getPassword (), ");}}

Code analysis:

Certification section:

Encapsulate the data submitted by the form into an object, query an object from the database through username, and compare it.

Finally, the object of this query is passed to the authorization method.

Authorization section:

Get the user object and authorize the user object accordingly. (permissions are set in the passed user object)

Write ShiroConfig

@ Configurationpublic class ShiroConfig {@ Bean / / create object public UserRealm userRealm () {return new UserRealm ();} @ Bean / / takeover object @ Bean default method name public DefaultWebSecurityManager securityManager (@ Qualifier ("userRealm") Realm realm) {DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager (); defaultWebSecurityManager.setRealm (realm); return defaultWebSecurityManager } @ Bean / / give the front-end processing public ShiroFilterFactoryBean shiroFilterFactoryBean (@ Qualifier ("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean (); shiroFilterFactoryBean.setSecurityManager (defaultWebSecurityManager); HashMap hashMap = new HashMap (); / / the path must be authenticated before you can access hashMap.put ("/ user/*", "authc") / / authorize hashMap.put ("/ user/add", "perms [add]"); hashMap.put ("/ user/update", "perms [update]"); / / log out of hashMap.put ("/ logout", "logout"); shiroFilterFactoryBean.setFilterChainDefinitionMap (hashMap); / / set the path to the login page shiroFilterFactoryBean.setLoginUrl ("/ login.html") / / set the authorization page shiroFilterFactoryBean.setUnauthorizedUrl ("/ noLogin"); return shiroFilterFactoryBean;} / / complete the integration @ Bean public ShiroDialect getShiroDialect () {return new ShiroDialect ();}}

Code analysis

In this configuration class, the method of configuration is ioc injection.

Can be configured in ShiroFilterFactoryBean

Permissions corresponding to the resource path

Landing page

The path to a page that cannot be accessed with insufficient permissions

Write off

Supplement: intercepted attributes

Anon: access without authentication

Authc: must be authenticated to access

User: you must have the ability to remember me to use it.

Perms: access only if you have permission to a resource

Role: have permissions for a role

Write control layer code

@ Controllerpublic class logincontroller {/ / execute the process front-end form-"Control layer Code -" config @ PostMapping ("/ login") public String login (String username, String password, Model model) {/ / get a user Subject subject = SecurityUtils.getSubject (); / / encapsulate the user login data UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken (username, password) / / execute the login method and throw an exception try {subject.login (usernamePasswordToken); return "index";} catch (UnknownAccountException e) {model.addAttribute ("msg", "user name error"); return "login";} catch (IncorrectCredentialsException e) {model.addAttribute ("msg", "password error") Return "login";} @ GetMapping ("/ noLogin") @ ResponseBody public String nologin () {return "cannot be accessed without authorization";}}

Code analysis:

Login method: get the data passed from the form, encapsulate the UsernamePasswordToken object, and call the login method to log in.

Shiro integrates Thymeleaf

ShiroDialect needs to be integrated in ShiroConfig

/ / complete the integration @ Bean public ShiroDialect getShiroDialect () {return new ShiroDialect ();}

Constraint

Xmlns:shiro= "http://www.pollix.at/thymeleaf/shiro"

Usage

Shiro:notAuthenticated: no login display

Shiro:authenticated: login display

If the shiro:hasPermission= "A" user has the permission of A, it is displayed.

Sample code:

Title Home Login Logout ADD UPDATE Summary

Login process: login form-"loginController-" ShiroConfig- "UserRealm"

Effect:

Click to log in, and the console will display

When you go to the add/update page, you will also print "= > Authorization", which also proves the execution process of login.

At this point, I believe that you have a deeper understanding of "what is the method of Java springboot integrating the Shiro framework". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Development

Wechat

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

12
Report