shiro articles] III. login authentication and authorization under shiro Case

Articles] [shiro III. Shiro login authentication and authorization on a case

Lengthy article directories can be viewed through the right side of Contents

shiro login authentication and authorization Cases

Project Preparation

  1. This project is based . Shiro login authentication and authorization on a case two articles] [shiro

4 Authorization - Role

4.1 page add two hyperlink ok

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>登录成功</h1>
    <a href="/logout">注销</a><br />
    <a href="/add">add</a>
    <a href="/delete">delete</a>

</body>
</html>

2 add 4.2 UserController corresponding method

@RequestMapping("/add")
public String add(){
    return "ok";
}
@RequestMapping("/delete")
public String delete(){
    return "ok";
}

4.3 authorization methods UserRealm of AuthorizationInfo add functionality

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo();

        Object username = principalCollection.getPrimaryPrincipal();
        if ("admin".equals(username.toString())){
            HashSet<String> roles = new HashSet<String>();
            roles.add("admin");
            sazi.addRoles(roles);
        }
        return sazi;
    }

4.3 Configuration roles in the spring filter vessel

Multiple roles separated by commas
Here Insert Picture Description

4.4 does not have permission to create a new page unauthorized.jsp

Here login.jsp, ok.jsp, unauthorized.jsp shiroFilter spring is disposed in the container

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>你没有权限</h1>
</body>
</html>

4.5 Test

Use admin2 for the user login name, click on the add will jump to a page does not have permission
to use the admin successful call

5. Authorization - Permission

5.1 configure permissions spring filter vessel

Here Insert Picture Description

5.2 doGetAuthorizationInfo add functionality to the authorization method UserRealm

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
	SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo();

    Object username = principalCollection.getPrimaryPrincipal();
    if ("admin".equals(username.toString())){
        HashSet<String> roles = new HashSet<String>();
        roles.add("admin");
        sazi.addRoles(roles);
    } else if ("admin2".equals(username.toString())){
        HashSet<String> permissions = new HashSet<String>();
        permissions.add("user:delete");
        sazi.addStringPermissions(permissions);
    }
    return sazi;
}

5.3 Test

Use admin as login user name, then you can call add, delete calls will jump to the page does not have permission.
Admin2 for the use of the words the user name that is registered can call the delete, add calls will jump to the page does not have permission.

6. License

6.1 Notes

6.1.1 annotated on the controller method

@RequiresPermissions(“user:add”)
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR):表示当前 Subject 需要权限 user:a 或 user:b

@RequiresRoles ( "admin")
@RequiresRoles (value = { "admin", "user"}, = Logical Logical.AND): indicates the current Subject needs and user role admin

6.1.2 placed springmvc.xml

如果要使用注解使用,首先要在配置文件中开启注解(SpringMVC配置文件中)
<!-- 启动shiro注解 -->   
<aop:config proxy-target-class="true"></aop:config>

<bean 	class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
	<property name="securityManager" ref="securityManager" />
</bean>

6.1.3 springmvc.xml configure global exception handler

If you do not have permission does not automatically jump to the page with their own, they will complain with comments.

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!-- 默认的错误视图页面 -->
    <property name="defaultErrorView" value="error" />
    <!-- 错误视图页面可以通过${ex}获取异常信息 -->
    <property name="exceptionAttribute" value="ex" />
    <property name="exceptionMappings">
        <props>
            <prop key="org.apache.shiro.authz.AuthorizationException">
                unauthorized
            </prop>
        </props>
    </property>
</bean>

6.2 jsp tag

6.2.1 guide tag library

<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>

label

  1. Visitors: guest
    <shiro:guest>  
    欢迎游客访问,<a href="/login.jsp">登录</a>  
    </shiro:guest>
    
  2. The user has been authenticated and selected the Remember Me: user
    <shiro:user>  
    欢迎[<shiro:principal/>]登录,<a href="/logout">注销</a>  
    </shiro:user>
    
  3. User authentication is not already selected Remember me: authenticated
    <shiro:authenticated>  
        用户[<shiro:principal/>]已身份验证通过  
    </shiro:authenticated>   
    
  4. Display user information: principal
    <shiro: principal/>
    
  5. There are currently Subject role will be displayed body body content: hasRole
    <shiro:hasRole name="admin">  
        用户[<shiro:principal/>]拥有角色admin<br/>  
    </shiro:hasRole> 
    
  6. Hsanyrioles
    <shiro:hasAnyRoles name="admin,user">  
        用户[<shiro:principal/>]拥有角色admin或user<br/>  
    </shiro:hasAnyRoles>   
    
  7. Subject currently has no role to display body body content: lacksRole
    <shiro:lacksRole name="abc">  
        用户[<shiro:principal/>]没有角色abc<br/>  
    </shiro:lacksRole>  
    
  8. hasPermission: If the current Subject has permission to display the contents of the body member
    <shiro:hasPermission name="user:create">  
        用户[<shiro:principal/>]拥有权限user:create<br/>  
    </shiro:hasPermission>   
    
  9. If the current Subject not have permission to display the body body content: lacksPermission tag
    <shiro:lacksPermission name="org:create">  
        用户[<shiro:principal/>]没有权限org:create<br/>  
    </shiro:lacksPermission>   
    

7 Remember me

7.1 modify the login page

Remember me New Options

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录页面</h1>

<form action="/login">
    username:<input type="text" name="username"><br />
    password:<input type="text" name="password"><br />
    rememberMe:<input type="checkbox" name="rememberMe"><br />
    <input type="submit" value="登录">
</form>

</body>
</html>

7.2 modify the controller login method

@RequestMapping("/login")
    public String login(String username, String password, String rememberMe){
        // 1. 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // *2. 判断是否登录,没有登陆返回false
        if (!currentUser.isAuthenticated()) {
            // 3。 封装用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 判断是否记住我
                if("on".equals(rememberMe)){
                    token.setRememberMe(true);
                }

                // 4. 登录
                currentUser.login(token);
            } catch (AuthenticationException ae) { // 6.3.4 其他的认证异常
                System.out.println("认证失败。。。。");
                return "login";
            }
        }
        return "ok";
    }

7.3 modify configuration files applicationContext

I remember that there is data encryption cookies in

<!-- 会话Cookie模板 -->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    <constructor-arg value="sid" />
    <!--设置js是否可以访问cookie,true不能访问 -->
    <property name="httpOnly" value="true" />
    <!-- 保存时长30天,以秒为单位 -->
    <property name="maxAge" value="2592000" />
</bean>

<!-- rememberMe管理器 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
    <!-- ipherKey是加密rememberMe Cookie的密钥;默认AES算法 -->
    <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />
    <!-- 引入上面定义的cookie模板 -->
    <property name="cookie" ref="rememberMeCookie" />
</bean>

Here Insert Picture Description

7.4 Edit Filter

Here Insert Picture Description

7.5 Test

8 summary

8.1 login authentication

  1. realm
  2. filter

8.2 control authority

  1. Filters: will jump to the page does not have permission to configure their own
  2. Annotations and labels: no permissions will throw an exception

8.3 Encryption

  1. Salt value encryption after the encrypted password to solve the same problem
Published 56 original articles · won praise 11 · views 4079

Guess you like

Origin blog.csdn.net/TheNew_One/article/details/104111710