Spring MVC rapidly integrates Shiro, mvcshiro
I think there will be a lot of programmers who are reluctant to Implement User Management Code.
One of the reasons is that different JavaEE systems and user management in different projects are implemented in a personalized manner, and the logic is cumbersome.
It is also the front of the system, and the chance of backcooking is very high in the future, which can be said to be a low-income and high-risk.
Shiro has recently been integrated into the system, and I feel this little guy is quite flexible.
Complete user authentication and authorization, clean API, let people feel like a spring equinox.
This article focuses on the integration process, allowing you to quickly integrate Shiro into the JavaEE project. After all, the project is quite tight.
For the implementation of the source code, you can find a leisurely night to savor it.
1. Foreplay
Shiro core jar:
Where the Java EE application starts, web. xml configuration:
<filter> <filter-name>shiroFilter</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The Shiro Spring annotation file and application startup will help you do many things:
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id = "lifecycleBeanPostProcessor" class = "org. apache. shiro. spring. lifecycleBeanPostProcessor "/> <! -- The password stored in the database is encrypted using the MD5 algorithm. Therefore, you must configure a password matching object --> <bean id = "credentialsMatcher" class = "org. apache. shiro. authc. credential. md5CredentialsMatcher "/> <! -- Cache Management --> <! -- <Bean id = "cacheManager" class = "org. apache. shiro. cache. MemoryConstrainedCacheManager"/> --> <! -- Use the JdbcRealm class that comes with Shiro to specify the encryption object used for password matching to specify the data source that stores the user, role, and permission and related query statements --> <bean id = "jdbcRealm" class = "org. apache. shiro. realm. jdbc. jdbcRealm "> <property name =" credentialsMatcher "ref =" credentialsMatcher "/> <property name =" permissionsLookupEnabled "value =" true "/> <property name =" dataSource "ref = "basedb"/> <property name = "authenticationQuery" value = "SELECT nsmc from user where userid =? "/> <! -- <Property name = "userRolesQuery" value = "SELECT role_name from sec_user_role left join sec_role using (role_id) left join sec_user using (user_id) WHERE user_name =? "/> --> <! -- <Property name = "permissionsQuery" value = "SELECT permission_name FROM sec_role_permission left join sec_role using (role_id) left join sec_permission using (permission_id) WHERE role_name =? "/> --> </Bean> <! -- Custom authentication --> <bean id = "myRealm" class = "cn. orson. common. MyRealm"/> <! -- Shiro security manager --> <bean id = "securityManager" class = "org. apache. shiro. web. mgt. DefaultWebSecurityManager"> <! -- Configure multiple realms --> <property name = "realms"> <list> <ref bean = "myRealm"/> <ref bean = "jdbcRealm"/> </list> </property> <! -- <Property name = "realm" ref = "jdbcRealm"/> --> <! -- <Property name = "cacheManager" ref = "cacheManager"/> --> </bean> <! -- The Shiro primary filter has powerful functions. Its powerful feature lies in its support for executing Web applications with custom filters based on URL path expressions, shiro's controllable Web requests must be intercepted by the Shiro main filter. Shiro provides perfect support for Spring-based Web applications --> <bean id = "shiroFilter" class = "org. apache. shiro. spring. web. shiroFilterFactoryBean "> <! -- Shiro's core security interface, which is mandatory --> <property name = "securityManager" ref = "securityManager"/> <! -- Requires the logon Link (logon page address), which is not a required attribute. By default, the "/login" under the root directory of the Web project is automatically searched. jsp "page --> <property name =" loginUrl "value ="/login. jsp "/> <! -- Connection to be redirected after Successful Logon (this attribute is not used in this example, because the processing logic after successful logon is hard-coded in LoginController) --> <! -- <Property name = "successUrl" value = "/"> </property> --> <! -- When a user accesses resources that are not authorized to the user, connection displayed --> <property name = "unauthorizedUrl" value = "/"/> <property name = "filterChainDefinitions"> <value>/security/* = anon/tag = authc </value> </property> </bean> <bean id = "shiroLogin" class = "cn. orson. common. shiroLogin "/> <! -- Enable Shiro annotations (for example, @ RequiresRoles and @ RequiresPermissions). You need to use SpringAOP to scan classes that use Shiro annotations and perform security logic verification if necessary --> <! -- <Bean class = "org. springframework. aop. framework. autoproxy. defaultAdvisorAutoProxyCreator "> </bean> <bean class =" org. apache. shiro. spring. security. interceptor. authorizationAttributeSourceAdvisor "> <property name =" securityManager "ref =" securityManager "> </property> </bean> --> </beans>
2. personalization
The request is generally initiated by the front-end. Whether you are A. jsp/. php/. net ...... the method is similar.
<Html> <body>
The project must have a custom project verification domain.
Public class MyRealm extends AuthorizingRealm {Log log = LogFactory. getLog (MyRealm. class);/*** grant roles and permissions to the Subject currently logged on * tested: In this example, the call time of this method is when resources need to be authorized to be accessed * tested: the logic in this method is executed every time you access the resource to be authorized. This indicates that AuthorizationCache is not enabled by default in this example. * I personally feel that if the ConcurrentMapCache support starting with Spring3.1 is used, you can choose whether to enable AuthorizationCache. * For example, when you obtain permission information from the database, you can first access the cache provided by Spring3.1, instead of using the AuthorizationCache */@ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {log.info ("your access doGetAuthorizationInfo succeeded") provided by Shior; // get the username of the current logon, equivalent to (String) principals. fromRealm (this. getName ()). iterator (). next () String currentUsername = (String) super. getAvailablePrincipal (principals );
// Implement your own business logic here // set roles and permissions based on the business logic
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo (); // actually, if (null! = CurrentUsername & "mike ". equals (currentUsername) {// Add a role, not in the configuration sense, but prove that the user has the admin role simpleAuthorInfo. addRole ("admin"); simpleAuthorInfo. addStringPermission ("admin: manage"); // Add the permission return simpleAuthorInfo;} // if this method does not directly return null, this will cause any user to access/admin/listUser. jsp automatically jumps to the address specified by unauthorizedUrl. // For details, see applicationContext. return null for the configuration of <bean id = "shiroFilter"> in xml;}/*** verify the Subject currently logged on * tested: In this example, the method is called at the time LoginController. run Subject in the login () method. when login () */@ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authcToken) throws AuthenticationException {// get the token based on the user name and password // In fact this authcToken is from the LoginController currentUser. login (token) uploads the same UsernamePasswordToken token = (UsernamePasswordToken) authcToken; log.info ("Get the token as" + ReflectionToStringBuilder when verifying the current Subject. ToString (token, ToStringStyle. MULTI_LINE_STYLE); // No comparison is required here. The comparison logic Shiro will do, we only need to return a correct token-related authentication information. // to put it bluntly, the first parameter is used to enter the logon username, set the second parameter to a valid logon password (which can be obtained from the database, which is hardcoded for demonstration in this example, on the subsequent login page, only the user and password specified here can pass the verification/* if ("mike ". equals (token. getUsername () {AuthenticationInfo authcInfo = new SimpleAuthenticationInfo ("mike", "mike", this. getName (); authcInfo. getCredentials (); this. setSession ("currentUser", "mike"); return AuthcInfo;} * // when the SimpleAuthenticationInfo object corresponding to the logon user name is not returned, the UnknownAccountException exception return null will be thrown in LoginController;}/*** put some data into ShiroSession, for other places to use * such as Controller, HttpSession is used directly. getAttribute (key) can get */private void setSession (Object key, Object value) {Subject currentUser = SecurityUtils. getSubject (); if (null! = CurrentUser) {Session session = currentUser. getSession (); if (null! = Session) {session. setAttribute (key, value );}}}}
The requested background service. Here you can perform some business logic
@ Controller @ RequestMapping (value = "/") public class ShiroLogin {/*** actual logon Code * If logon is successful, go to the homepage; logon failed, the Failure Information is fed back to the user ** @ param request * @ param model * @ return */@ RequestMapping (value = "dologin", method = RequestMethod. POST) @ ResponseBody public String doLogin (HttpServletRequest request, Model model) {String msg = ""; String userName = request. getParameter ("userName"); String password = request. getParameter ("password ");
/* UsernamePasswordToken token = new UsernamePasswordToken (userName, password); token. setRememberMe (true); Subject subject = SecurityUtils. getSubject (); try {subject. login (token); if (subject. isAuthenticated () {return "redirect:/";} else {return "login" ;}} catch (IncorrectCredentialsException e) {msg = "Logon Password error. password for account "+ token. getPrincipal () + "was incorrect. "; model. addAttri Messages ("message", msg); System. out. println (msg);} catch (ExcessiveAttemptsException e) {msg = "too many logon failures"; model. addAttribute ("message", msg); System. out. println (msg);} catch (LockedAccountException e) {msg = "the account has been locked. the account for username "+ token. getPrincipal () + "was locked. "; model. addAttribute ("message", msg); System. out. println (msg);} catch (DisabledAccountException e) {msg = "the account has been disabled. The account for username "+ token. getPrincipal () + "was disabled. "; model. addAttribute ("message", msg); System. out. println (msg);} catch (ExpiredCredentialsException e) {msg = "the account has expired. the account for username "+ token. getPrincipal () + "was expired. "; model. addAttribute ("message", msg); System. out. println (msg);} catch (UnknownAccountException e) {msg = "the account does not exist. there is no user with usernam E of "+ token. getPrincipal (); model. addAttribute ("message", msg); System. out. println (msg);} catch (UnauthorizedException e) {msg = "You are not authorized! "+ E. getMessage (); model. addAttribute (" message ", msg); System. out. println (msg );}*/}}
The entire integration process is over. Isn't it simple.
The next time the Project Manager assigns you user management, you only need to spend half a day designing.
Use Shiro to implement code in half a day.
Then, take the rest of the time to do other research work that you like.