API 安全机制 | 授权

2020-07-12  本文已影响0人  乌鲁木齐001号程序员

授权

401 vs 403

访问控制的实现方式

ACL | Access Control Lists
RBAC | Role Based Access Control

ACL 的简单实现

package com.lixinlei.security.api.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lixinlei.security.api.vo.UserInfo;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class AclInterceptor extends HandlerInterceptorAdapter {

    private String[] permitUrls = new String[] {"/users/login"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println(4);

        boolean result = true;
        if( !ArrayUtils.contains(permitUrls, request.getRequestURI()) ) {
            UserInfo user = (UserInfo) request.getSession().getAttribute("user");
            if(user == null) {
                // 没有通过认证
                response.setContentType("text/plain");
                response.getWriter().write("need authentication");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                result = false;
            } else {
                String method = request.getMethod();
                // 用户的 permission 字段中,是否有请求的方法
                if(!user.hasPermission(method)) {
                    response.setContentType("text/plain");
                    response.getWriter().write("forbidden");
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    result = false;
                }
            }
        }

        return result;
    }

}
上一篇下一篇

猜你喜欢

热点阅读