Shiro and integrated SpringMVC

 

Source: https: //gitee.com/jiaodacailei/shiro-springmvc-demo.git

Key concept

Shiro is a framework for Java permissions, as opposed to a frame of a spring: Spring Security

 

 

Create Maven-web project

Configuration pom.xml

reference:

\ Shiro-web \ pom.xml

Configuring web.xml

Configuring spring / springmvc / shiro, focus on:

Configuring spring

src/main/resources/applicationContext.xml

src/main/resources/spring-shiro-web.xml

Configuration springmvc

Reference: springmvc-servlet.xml

 

Log in Home page and load

Creating main.jsp and login.jsp

 

MainController map

 

Authenticate

shiro internal certification process is as follows, if you do not understand, you can skip the first, after the completion of the examples that follow look.

Now, we have to complete the login form to submit post / login, let shiro help us to complete the certification. Of course, we still need to write the logic of certification, completed in the Realm.

In shiro spring configuration, the definition Realm

src/main/resources/spring-shiro-web.xml

We need to inject custom realm in securityManager in here userRealm

Creating UserRealm class

Methods inherited AuthorizingRealm, and obtain authentication information can rewrite

Handles authentication fails, the need to increase in the Controller / login map of Post:

Authorize

Next, we need to complete the authorization, to achieve admin user login system can see the users, roles, menu three modules; and cai user login system, you can only see the user module.

Modify UserRealm

 

Modify UserRealm, rewrite method to obtain authorization information

Verify permissions

Need to modify main.jsp, using shiro tag library to verify the permissions, no more authority authentication, permission to see the back of verification that section.

Shiro also need to tag library

 

filter

filter effect
anon Anonymous Filters: corresponding url, without any certification to access, that is, anonymous access.
authc 表单认证过滤器:对应的url的get请求,验证用户是否登录,如果没有登录,则跳转登录页面;对应的url的post请求,会获取表单中的用户名和密码,调用用户提供的Realm的doGetAuthenticationInfo(AuthenticationToken token)进行认证,认证通过则返回首页。
user 用户过滤器:对应的url请求,验证用户是否登录,如果没有登录则跳转登录页面,用户输入登录信息,登录成功后,回跳转回初次访问的url。
logout 注销过滤器:将shiro中的用户注销,并返回首页

 

User过滤器测试:

当系统启动时,首先访问url: /2

会跳转登录页,认证成功后,会跳回 /2

 

 

获取用户

在我们实际代码中,如何获取用户信息呢?

例如,我们经常会在登录成功后将用户信息放在HttpSession中,在后续的请求中,就获取该用户信息,从而使用它。

在Shiro中,我们可以通过SecurityUtils.getSubject().getPrincipal()获取当前用户信息:

该用户信息是我们在UserRealm中设置的(红框中的内容):

 

权限验证

下面时shiro权限验证的内部流程,如果看不懂,可以先略过,后面完成例子之后再回过头来看。

权限验证主要是指,当我们已经登录成功后,怎么判断当前用户有哪些权限,是什么角色?

主要包含下面三种验证方式:

Java编码方式验证权限

SecurityUtils.getSubject().hasRole(“admin”)

SecurityUtils.getSubject().isPermitted(“menu:view”)

 

注解方式验证权限

配置

代码

@RequireRoles

@RequirePermissions

 

测试

 

分别使用admin和cai用户登录系统,然后分别访问/msg

admin用户会看到true,cai用户没有权限:

采用shiro的jsp标签库

<shiro:hasPermission/>

<shiro:hasRole/>

 

Guess you like

Origin www.cnblogs.com/qfchen/p/11201718.html