【WEEK13】 【DAY5】Shiro Part 5【English Version】

2024.5.24 Friday
Continuation from 【WEEK13】 【DAY4】Shiro Part 4【English Version】

15.7. Implementation of Shiro Request Authorization

15.7.1. Modify ShiroConfig.java

15.7.1.1. Add a line of code for authorization verification

// Authorization. Normally, it should redirect to an unauthorized page, but at this time, due to only adding the following verification, it directly redirects to the 401 page
filterMap.put("/user/add","perms[user:add]");

15.7.1.2. Restart

Log in with any user and try to access the “add” page: because the user’s permissions are insufficient, access is denied.
Insert image description here

15.7.2. Modify MyController.java

package com.P40.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello, Shiro");
        return "index";
    }


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

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }


    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        // Get the current user
        Subject subject = SecurityUtils.getSubject();

        // Encapsulate user login data
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        // Execute the login method, if there is no exception, it is successful. Select the code and press Ctrl+Alt+T to add try-catch
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {   // Username does not exist
            model.addAttribute("msg","Incorrect username");
            return "login";
        } catch (IncorrectCredentialsException e) {   // Incorrect password
            model.addAttribute("msg","Incorrect password");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "Unauthorized, access to this page is prohibited";
    }
}

15.7.3. Modify ShiroConfig.java

Add redirection to an unauthorized page

package com.P40.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    // ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // Configuration: click to enter ShiroFilterFactoryBean source code for details
        // Set security manager
        bean.setSecurityManager(defaultWebSecurityManager);

        // Add Shiro's built-in filters
        /*
        anon: Accessible without authentication
        authc: Must be authenticated to access
        user: Must have remember me functionality to use
        perms: Must have permission for a specific resource to access
        role: Must have certain role permissions
         */
        // Login interception
        Map<String,String> filterMap = new LinkedHashMap<>();

        // Authorization. Normally, it should redirect to an unauthorized page, but at this time, due to only adding the following verification, it directly redirects to the 401 page
        filterMap.put("/user/add","perms[user:add]");

//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
        // After modifying the access permissions for the add and update pages only here, restart the project. Clicking on add or update will be intercepted, showing a 404 error, hoping to redirect to the login page
        filterMap.put("/user/*","authc");   // Wildcards can also be used here (replace the above two lines of /user/add and /user/update)
        bean.setFilterChainDefinitionMap(filterMap);

        // If no permissions, need to redirect to the login page
        bean.setLoginUrl("/toLogin");   // Set the login request

        // Unauthorized page
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

    // DefaultWebSecurityManager
    @Bean(name = "securityManager") // Alias this class to facilitate invocation by ShiroFilterFactoryBean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){    // Get UserRealm, but it seems that annotations are not needed here, it can be called directly
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // The default class name of DefaultWebSecurityManager is defaultWebSecurityManager, it is just changed to securityManager here

        // Associate UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    // Create realm object, need to customize class
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    // Creation order is reversed (from real->DefaultWebSecurityManager->ShiroFilterFactoryBean)
}

15.7.4. Restart

Similarly, when trying to access the add page without permission, the displayed URL and corresponding page are as follows:
Insert image description here

15.7.5. Modify UserRealm.java

15.7.5.1. Add permissions to all users

package com.P40.config;

import com.P40.pojo.User;
import com.P40.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// UserRealm is a bean
// Customized UserRealm, it must inherit the AuthorizingRealm method, and then implement methods (alt+insert)
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    // Authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("do doGetAuthorizationInfo Authorization");

        // Authorization
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();   // You can first write new SimpleAuthorizationInfo(); and then use Alt+Enter to quickly create the preceding framework
        info.addStringPermission("user:add");   // Add permission for all logged-in users to access User:add, at this time, any logged-in user can access the add page

        // Cannot return null
        return info;
    }

    // Authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("do doGetAuthenticationInfo Authentication");

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        // Change to connect to the real database
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null){   // User does not exist
            return null;    // UnknownAccountException
        }

        // Password authentication, shiro operation
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}

15.7.5.2. Restart Verification

Insert image description here

Implementation of Shiro Request Authorization This part is half done, see 【WEEK14】 【DAY1】Shiro Part 6【English Version】 for details.

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值