In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how Springboot integrates Shiro to achieve login and authority verification". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope that this article "how to achieve login and authority verification with Springboot integration Shiro" can help you solve the problem.
Springboot-cli develops scaffolding series
Springboot gracefully integrates Shiro for login verification and authority authentication (with source code download)
Brief introduction
Springboo configures Shiro for login verification, authority authentication, and demo demonstration.
Preface
We are committed to allowing developers to quickly build the basic environment and get applications running, providing examples for users to refer to, and for beginners to get started quickly.
The source code address of this blog project:
Project source code github address
Project source code domestic gitee address
1. Environment
Dependence
Org.apache.shiro shiro-core 1.9.0 org.apache.shiro shiro-spring 1.9.0 com.github.theborakompanioni thymeleaf-extras-shiro 2.1.0 org. Springframework.boot spring-boot-starter-thymeleaf
Yml configuration
Server:
Port: 9999
Servlet:
Session:
# Let Tomcat only get session information from COOKIE, so that when there is no Cookie, URL will not be automatically added; jsessionid= … Yes.
Tracking-modes: COOKIE
Spring:
Thymeleaf:
# disable the page cache to facilitate testing in the development environment
Cache: false
# static resource path
Prefix: classpath:/templates/
# Web resources end with default .html
Mode: HTML
two。 Brief introduction
Three functional modules of Shiro
Subject
Authentication subject, usually referring to the user (handing over the operation to SecurityManager).
SecurityManager
Security Manager, Security Manager, manages all Subject, can cooperate with internal security components (associated Realm)
Realm
Domain object, used for authentication of permission information, shiro connection data bridge, such as our login verification, permission verification is defined in Realm.
3. Realm configuration
Define user entity User, which can be defined according to your own business
@ Data@Accessors (chain = true) public class User {/ * user id * / private Long userId; / * * username * / private String username; / * * password * / private String password; / * * user alias * / private String name;}
Rewrite the login verification doGetAuthenticationInfo and authorization doGetAuthorizationInfo methods in AuthorizingRealm, and write our custom verification logic.
/ * * Custom login authorization * * @ author ding * / public class UserRealm extends AuthorizingRealm {/ * authorization * here permissions are granted to * / @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {SimpleAuthorizationInfo info = new SimpleAuthorizationInfo (); / / add vip permission info.addStringPermission ("vip") for each user here; return info } / * * Authentication * our login logic is implemented here, such as account password verification * / @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {/ / get token UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; / / get the user name and password from token String username = token.getUsername (); String password = String.valueOf (token.getPassword ()) / / for convenience, here simulates getting user User user = this.getUser (); if (! user.getUsername (). Equals (username)) {throw new UnknownAccountException ("user does not exist");} else if (! user.getPassword () .equals (password)) {throw new IncorrectCredentialsException ("password error") } / / after the verification is completed, we return the user information here, so that we can obtain the user's login information return new SimpleAuthenticationInfo (user, password, getName ()) through Subject later. } / * * user data is simulated here * in actual development, it can be obtained by database query * / private User getUser () {return new User () .setName ("admin") .setUserId (1L) .setUsername ("admin") .setPassword ("123456");}} 4. Core configuration
ShiroConfig.java
/ * *
* Shiro built-in filter to implement interceptor-related interceptors
* frequently used filters:
* anon: access without authentication (login)
* authc: authentication is required to access
* user: if you use the rememberMe feature, you can access it directly.
* perms: this resource must obtain resource permission before it can be accessed. Format perms [permission 1, permission 2]
* role: this resource must have role permission before it can be accessed
* * /
/ * * shiro Core Manager * * @ author ding * / @ Configurationpublic class ShiroConfig {/ * can access * / private final static String ANON = "anon" without authentication; / * must be authenticated to access * / private final static String AUTHC = "authc" / * only have permission to access a resource * / private final static String PERMS = "perms"; / * create a realm, which returns the UserRealm * / @ Bean (name = "userRealm") public UserRealm userRealm () {return new UserRealm () we defined last time. } / * create Security Manager * / @ Bean (name = "securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager (@ Qualifier ("userRealm") UserRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); / / bind realm object securityManager.setRealm (userRealm); return securityManager } / * Authorization filter * / @ Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean (@ Qualifier ("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean (); / / set Security Manager bean.setSecurityManager (defaultWebSecurityManager); / / add shiro's built-in filter Map filterMap = new LinkedHashMap (); filterMap.put ("/ index", ANON) FilterMap.put ("/ userInfo", PERMS + "[vip]"); filterMap.put ("/ table2", AUTHC); filterMap.put ("/ table3", PERMS + "[vip2]"); bean.setFilterChainDefinitionMap (filterMap); / / set the jump landing page bean.setLoginUrl ("/ login"); / / unlimited jump bean.setUnauthorizedUrl ("/ unAuth"); return bean } / * Thymeleaf uses the Shiro tag * / @ Bean public ShiroDialect shiroDialect () {return new ShiroDialect ();}} 5. Interface programming
IndexController.java
/ * @ author ding * / @ Controllerpublic class IndexController {@ RequestMapping ({"/", "/ index"}) public String index (Model model) {model.addAttribute ("msg", "hello,shiro"); return "/ index";} @ RequestMapping ("/ userInfo") public String table1 (Model model) {return "userInfo" } @ RequestMapping ("/ table") public String table (Model model) {return "table";} @ GetMapping ("/ login") public String login () {return "login" } @ PostMapping (value = "/ doLogin") public String doLogin (@ RequestParam ("username") String username, @ RequestParam ("password") String password, Model model) {/ / get the current user Subject subject = SecurityUtils.getSubject (); / / to store the error message String msg = "" / / if if (! subject.isAuthenticated ()) {/ / encapsulates the username and password into shiro UsernamePasswordToken token = new UsernamePasswordToken (username, password); try {/ / executes the login method subject.login (token);} catch (Exception e) {e.printStackTrace () Msg = "wrong account or password";} / / if msg is empty and there is no exception, return to the home page if (msg.isEmpty ()) {return "redirect:/index";} else {model.addAttribute ("errorMsg", msg); return "login" } return "/ login";} @ GetMapping ("/ logout") public String logout () {SecurityUtils.getSubject () .logout (); return "index";} @ GetMapping ("/ unAuth") public String unAuth () {return "unAuth";}} 6. Web page resources
Create a templates folder in resources to store page resources
Index.html
Title Home Page
User logged in
Log out
The user is not logged in
User Information table
Login.html
Landing page
Login page account: admin, password: 123456 login
UserInfo.html
Table1 user information user name: user complete information:
Table.hetml
Tabletable7. Effect demonstration
Launch the Project browser and enter 127.0.0.1pur9999
When we click on user information and table, we automatically jump to the login page.
After logging in successfully
Get user information
What we get here is the user information returned by our previous doGetAuthenticationInfo method, which is all returned here for demonstration, and the password cannot be returned in actual production.
This is the end of the content about "how Springboot integrates Shiro to achieve login and permission verification". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.