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

Shiro tutorial (4)-shiro and Project Integrated Development

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

1 shiro and project integration development 1.1 shiro and spring web project integration

The integration of shiro and springweb projects is based on the "project based on url interception implementation". The technical architecture of the project based on url interception implementation is springmvc+mybatis. Two points should be paid attention to:

1. Integration of shiro and spring

2. Join shiro to support web applications

1.1.1 cancel the original springmvc authentication and authorization interceptor

Remove the LoginInterceptor and PermissionInterceptor interceptors configured in springmvc.xml.

1.1.2 jar package added to shiro

1.1.3 web.xml add shiro Filter

[html] view plain copy print?

ShiroFilter

Org.springframework.web.filter.DelegatingFilterProxy

TargetFilterLifecycle

True

ShiroFilter

/ *

1.1.4 applicationContext-shiro.xml

[html] view plain copy print?

/ loginsubmit.action = authc

/ logout.action = logout

/ refuse.jsp = anon

/ item/list.action = roles [item], authc

/ js/** anon

/ paired wayward picpathsCompact anon

/ styles/** anon

/ * * = user

SecurityManager: this attribute is required.

LoginUrl: requests from users without login authentication will jump to this address, which is not a required attribute. If you do not enter the address, you will automatically find the "/ login.jsp" page in the root directory of the project web project.

UnauthorizedUrl: a page that does not have permission to jump to by default.

1.1.5 Authorization using shiro comments

Configure shiro annotation support in springmvc.xml, and configure permissions using shiro annotations in the controller method:

[html] view plain copy print?

Modify the Controller code to add authorization comments to the method, as follows:

[java] view plain copy print?

/ / query the list of products

@ RequestMapping ("/ queryItem")

@ RequiresPermissions ("item:query")

Public ModelAndView queryItem () throws Exception {

The above code @ RequiresPermissions ("item:query") indicates that you must have "item:query" permission to execute.

Other methods refer to examples to add comments

1.1.6 Custom realm

This realm does not query permission data from the database. Currently, you need to integrate the shiro and modify it based on the realm defined in the previous section.

[java] view plain copy print?

Public class CustomRealm1 extends AuthorizingRealm {

@ Autowired

Private SysService sysService

@ Override

Public String getName () {

Return "customRealm"

}

/ / what type of token is supported

@ Override

Public boolean supports (AuthenticationToken token) {

Return token instanceof UsernamePasswordToken

}

/ / Authentication

@ Override

Protected AuthenticationInfo doGetAuthenticationInfo (

AuthenticationToken token) throws AuthenticationException {

/ / obtain user identity information from token

String username = (String) token.getPrincipal ()

/ / query from the database with username

/ /....

/ / return null if the query cannot be found

If (! username.equals ("zhang")) {/ / the simulated query cannot be found here

Return null

}

/ / obtain the user password queried from the database

String password = "123"; / / static data simulation is used here.

/ / retrieve the menu from the database according to the user's id

/ /... Use static data first

List menus = new ArrayList ()

SysPermission sysPermission_1 = new SysPermission ()

SysPermission_1.setName (Commodity Management)

SysPermission_1.setUrl ("/ item/queryItem.action")

SysPermission sysPermission_2 = new SysPermission ()

SysPermission_2.setName ("user Management")

SysPermission_2.setUrl ("/ user/query.action")

Menus.add (sysPermission_1)

Menus.add (sysPermission_2)

/ / build the user's body information

ActiveUser activeUser = new ActiveUser ()

ActiveUser.setUserid (username)

ActiveUser.setUsername (username)

ActiveUser.setUsercode (username)

ActiveUser.setMenus (menus)

/ / the returned authentication information is authenticated by the parent class AuthenticatingRealm

SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo (

ActiveUser, password, getName ()

Return simpleAuthenticationInfo

}

/ / authorization

@ Override

Protected AuthorizationInfo doGetAuthorizationInfo (

PrincipalCollection principals) {

/ / obtain identity information

ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal ()

/ / user id

String userid = activeUser.getUserid ()

/ / query permission data from the database according to the user id

/ /.... Static data simulation is used here

List permissions = new ArrayList ()

Permissions.add ("item:query")

Permissions.add ("item:update")

/ / close the permission information to AuthorizationInfo

SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo ()

For (String permission: permissions) {

SimpleAuthorizationInfo.addStringPermission (permission)

}

Return simpleAuthorizationInfo

}

}

1.1.7 Login

[java] view plain copy print?

/ / user login page

@ RequestMapping ("/ login")

Public String login () throws Exception {

Return "login"

}

/ / users log in and submit

@ RequestMapping ("/ loginsubmit")

Public String loginsubmit (Model model, HttpServletRequest request)

Throws Exception {

/ / shiro returns the exception classpath through request after an error occurs during the authentication process

String exceptionClassName = (String) request

.getAttribute ("shiroLoginFailure")

If (UnknownAccountException.class.getName () .equals (exceptionClassName)) {

Throw new CustomException ("account does not exist")

} else if (IncorrectCredentialsException.class.getName (). Equals (

ExceptionClassName)) {

Throw new CustomException ("user name / password error")

} else {

Throw new Exception (); / / finally generates an unknown error in the exception handler

}

}

1.1.8 Home Page

Because session is managed by shiro, you need to modify the controller method on the home page:

[java] view plain copy print?

/ / system home page

@ RequestMapping ("/ first")

Public String first (Model model) throws Exception {

/ / subject

Subject subject = SecurityUtils.getSubject ()

/ / identity

ActiveUser activeUser = (ActiveUser) subject.getPrincipal ()

Model.addAttribute ("activeUser", activeUser)

Return "/ first"

}

1.1.9 exit

Because you use shiro's sessionManager, you don't need to develop the exit function, just use shiro's logout interceptor.

[html] view plain copy print?

/ logout.action = logout

1.1.10 Unlimited refuse.jsp

When the user does not have permission to operate, shiro will jump to the refuse.jsp page.

Reference: applicationContext-shiro.xml

1.2 realm connection database 1.2.1 add credential matcher

Add a credential matcher to achieve md5 encryption verification.

Modify applicationContext-shiro.xml:

[html] view plain copy print?

1.2.2 realm Code

Modify the realm code to query the user identity information and permission information from the database, and inject sysService into realm.

[java] view plain copy print?

Public class CustomRealm1 extends AuthorizingRealm {

@ Autowired

Private SysService sysService

@ Override

Public String getName () {

Return "customRealm"

}

/ / what type of token is supported

@ Override

Public boolean supports (AuthenticationToken token) {

Return token instanceof UsernamePasswordToken

}

@ Override

Protected AuthenticationInfo doGetAuthenticationInfo (

AuthenticationToken token) throws AuthenticationException {

/ / obtain user identity from token

String usercode = (String) token.getPrincipal ()

SysUser sysUser = null

Try {

SysUser = sysService.findSysuserByUsercode (usercode)

} catch (Exception e) {

/ / TODO Auto-generated catch block

E.printStackTrace ()

}

/ / if the account does not exist

If (sysUser = = null) {

Throw new UnknownAccountException ("account not found")

}

/ / pull out the menu according to the user's id

List menus = null

Try {

Menus = sysService.findMenuList (sysUser.getId ())

} catch (Exception e) {

/ / TODO Auto-generated catch block

E.printStackTrace ()

}

/ / user password

String password = sysUser.getPassword ()

/ / Salt

String salt = sysUser.getSalt ()

/ / build the user's body information

ActiveUser activeUser = new ActiveUser ()

ActiveUser.setUserid (sysUser.getId ())

ActiveUser.setUsername (sysUser.getUsername ())

ActiveUser.setUsercode (sysUser.getUsercode ())

ActiveUser.setMenus (menus)

SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo (

ActiveUser, password, ByteSource.Util.bytes (salt), getName ()

Return simpleAuthenticationInfo

}

@ Override

Protected AuthorizationInfo doGetAuthorizationInfo (

PrincipalCollection principals) {

/ / identity information

ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal ()

/ / user id

String userid = activeUser.getUserid ()

/ / obtain user permissions

List permissions = null

Try {

Permissions = sysService.findSysPermissionList (userid)

} catch (Exception e) {

/ / TODO Auto-generated catch block

E.printStackTrace ()

}

/ / build shiro authorization information

SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo ()

For (SysPermission sysPermission:permissions) {

SimpleAuthorizationInfo.addStringPermission (sysPermission.getPercode ())

}

Return simpleAuthorizationInfo

}

}

1.3 caching

Each authorization of shiro obtains permission information through realm. In order to improve access speed, you need to add cache. Read permission data from realm for the first time, and then no longer read it. Here Shiro and Ehcache are integrated.

1.3.1 add jar package 1.3.2 configuration for Ehcache

Configure the cache manager in applicationContext-shiro.xml.

[html] view plain copy print?

1.4 session Management

Configure sessionManager in applicationContext-shiro.xml:

[html] view plain copy print?

1.5 CAPTCHA 1.5.1 Custom FormAuthenticationFilter

You need to verify the CAPTCHA before verifying the account number and name.

[java] view plain copy print?

Public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

Protected boolean onAccessDenied (ServletRequest request

ServletResponse response, Object mappedValue) throws Exception {

/ / Verification code

/ / get the correct CAPTCHA from session

HttpSession session = (HttpServletRequest) request) .getSession ()

/ / the verification code entered on the page

String randomcode = request.getParameter ("randomcode")

/ / remove the CAPTCHA from the session

String validateCode = (String) session.getAttribute ("validateCode")

If (! randomcode.equals (validateCode)) {

/ / randomCodeError indicates an error in the verification code

Request.setAttribute ("shiroLoginFailure", "randomCodeError")

/ / access denied, account and password no longer verified

Return true

}

Return super.onAccessDenied (request, response, mappedValue)

}

}

1.5.2 modify FormAuthenticationFilter configuration

Modify the configuration of FormAuthenticationFilter in applicationContext-shiro.xml.

[html] view plain copy print?

Change to

1.5.3 Landing Page

Add a CAPTCHA:

[html] view plain copy print?

CAPTCHA:

Refresh

1.5.4 configure validatecode.jsp anonymous access

Modify applicationContext-shiro.xml:

1.6 remember me

User login chooses "automatic login" this login will write identity information to cookie, the next login will take out identity information from cookie to achieve automatic login.

1.6.1 user identity implements java.io.Serializable interface

Recording identity information to cookie requires that the user identity information object implement the serialization interface, as follows:

1.6.2 configuration

[html] view plain copy print?

Modify the input name of "remember me checkbox" on the formAuthenticationFitler add page:

[html] view plain copy print?

1.6.3 Landing Page

Add "remember me" checkbox to login.jsp.

[html] view plain copy print?

Automatic landing

2 attached: 2.1shiro filter

Filter abbreviation

Corresponding Java class

Anon

Org.apache.shiro.web.filter.authc.AnonymousFilter

Authc

Org.apache.shiro.web.filter.authc.FormAuthenticationFilter

AuthcBasic

Org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

Perms

Org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

Port

Org.apache.shiro.web.filter.authz.PortFilter

Rest

Org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

Roles

Org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

Ssl

Org.apache.shiro.web.filter.authz.SslFilter

User

Org.apache.shiro.web.filter.authc.UserFilter

Logout

Org.apache.shiro.web.filter.authc.LogoutFilter

Anon: example / admins/**=anon has no parameters, which means it can be used anonymously.

Authc: for example, / admins/user/**=authc means authentication (login) is required to use it. There are no parameters.

Roles: example / admins/user/**=roles [admin], parameters can be written in quotation marks, and parameters are separated by commas. When there are multiple parameters, such as admins/user/**=roles ["admin,guest"], each parameter is passed, which is equivalent to the hasAllRoles () method.

Perms: example / admins/user/**=perms [user:add:*], parameters can be written in quotation marks, and parameters are separated by commas, such as / admins/user/**=perms ["user:add:*,user:modify:*"]. When there are multiple parameters, each parameter must be passed before it is passed, which is considered as the isPermitedAll () method.

Rest: example / admins/user/**=rest [user], which is equivalent to / admins/user/**=perms [user:method] according to the requested method, where method is post,get,delete and so on.

Port: example / admins/user/**=port [8081]. When the port of the requested url is not 8081, it jumps to schemal://serverName:8081?queryString, where schmal is the protocol http or https, etc., and serverName is the port of port in the url configuration that you access, queryString.

Is it from the url you visited? The following parameters.

AuthcBasic: for example, / admins/user/**=authcBasic has no parameter to indicate httpBasic authentication

Ssl: example / admins/user/**=ssl has no parameters and indicates a secure url request. The protocol is https.

User: for example, there is no parameter for / admins/user/**=user to indicate that a user must exist, and no check is made when logging in.

Note:

Anon,authcBasic,auchc,user is the authentication filter

Perms,roles,ssl,rest,port is the authorization filter

2.2 jsp tags for shiro

The Jsp page adds:

Label name

Label conditions (all display label contents)

After logging in

When not in the login state

When users do not have RememberMe,

When the user is in RememberMe

When there are abc or 123roles

Have a role abc

No role abc

Have permission resource abc

No abc permission resource

Show user identity name

Display attribute values in the user's identity

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

Database

Wechat

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

12
Report