shiro 实现多种方式登录_前后端分离架构使用shiro框架进行登录的两种实现

本文介绍了两种使用Shiro框架在前后端分离架构下实现登录的方法。第一种是重写FormAuthenticationFilter,当未登录用户访问受限页面时,返回JSON提示。第二种是使用PassThruAuthenticationFilter,允许自定义登录行为,通过Subject.login()进行认证。详细步骤包括配置shiro.xml,覆盖关键方法以及在Controller中调用subject.login()。
摘要由CSDN通过智能技术生成

方法一:重写FormAuthenticationFilter

原理:

假设在shiro.xml中配置了 /** = authc

而默认authc对应org.apache.shiro.web.filter.authc.FormAuthenticationFilter过滤器

则表示所有路径都被此过滤器拦截

当未登录请求被拦截,会调用FormAuthenticationFilter.onAccessDeny():

如果请求的是loginUrl,则调用AuthenticatingFilter.executeLogin()

如果不是,则使request重定向到loginUrl,并return false;

AuthenticatingFilter.executeLogin():

调用subject.login(token)

如果登录成功,则调用onLoginSuccess()

失败则调用onLoginFailure()

AuthenticatingFilter.onLoginSuccess(): return true;

AuthenticatingFilter.onLoginFailure(): return false;

subject.login(token):

最终会调用realm的doGetAuthenticationInfo

思路

重写默认的FormAuthenticationFilter,

在onAccessDeny()方法中:

如果请求的是loginUrl,则调用AuthenticatingFilter.executeLogin()

如果不是,则返回json,提示“未登录,无法访问该地址”

@Override

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

if (this.isLoginRequest(request, response)) {

if (this.isLoginSubmission(request, response)) {

if (log.isTraceEnabled()) {

log.trace("Login submission detected.  Attempting to execute login.");

}

return this.executeLogin(request, response);

} else {

if (log.isTraceEnabled()) {

log.trace("Login page view.");

}

return true;

}

} else {

if (log.isTraceEnabled()) {

log.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication url [" + this.getLoginUrl() + "]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值