前后端分离项目通过注解+拦截器鉴权

前后端分离项目通过注解+拦截器鉴权,第1张

前后端分离项目通过注解+拦截器鉴权
  • 注解类(Authorized.java)
@documented
@Inherited
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorized {
}
  • 拦截器处理类(AuthInterceptor.java)
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Authorized authorized = handlerMethod.getMethodAnnotation(Authorized.class);
        if (authorized == null) {
            authorized = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authorized.class);
        }

        if (authorized != null) {
            return isAuthorized(request, response);
        }
        return true;
    }

    private boolean isAuthorized(HttpServletRequest request, HttpServletResponse response) {
    	//CURRENT_USER已经在登录完成的时候存到session中了
        JSONObject userJSON = (JSONObject) request.getSession().getAttribute("CURRENT_USER");

        if (userJSON != null) {
            return true;
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8;");

        try (PrintWriter writer = response.getWriter()) {
            String buffer = JSONObject.toJSONString(
                    BeeResponseEntity.failed(ErrorCode.UNAUTHORIZED),
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat
            );
            writer.print(buffer);
            return false;
        } catch (IOException e) {
            return false;
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5609664.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存