Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于在realm进行登入时抛出异常的问题 #6

Closed
whyalwaysmea opened this issue Feb 2, 2018 · 9 comments
Closed

关于在realm进行登入时抛出异常的问题 #6

whyalwaysmea opened this issue Feb 2, 2018 · 9 comments

Comments

@whyalwaysmea
Copy link

在JWTFilter中有如下方法

@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String authorization = httpServletRequest.getHeader("Authorization");
    authorization = authorization.replace("Bearer ", "");

    JWTToken token = new JWTToken(authorization);
    // 提交给realm进行登入,如果错误他会抛出异常并被捕获
    getSubject(request, response).login(token);
     // 如果没有抛出异常则代表登入成功,返回true
    return true;
 }

此时Header中带有Authorization,那么将会去MyRealm中进行用户验证。

如果Authorization传过来的token是错误的,就会抛出异常。但是再MyRealm.java 中的doGetAuthenticationInfo中抛出的异常,无法被ExceptionController所捕获,就导致返回的数据结构不统一了。
请问有解决办法吗?

@whyalwaysmea whyalwaysmea changed the title 关于在remlm进行登入时抛出异常的问题 关于在realm进行登入时抛出异常的问题 Feb 2, 2018
@Smith-Cruise
Copy link
Owner

可以参考我这个写法
https://github.com/Eagle-OJ/eagle-oj-api/blob/master/eagle-oj-web/src/main/java/com/eagleoj/web/controller/exception/GlobalExceptionController.java

使用@ExceptionHandler(ShiroException.class)进行捕捉

@whyalwaysmea
Copy link
Author

尝试还是无法被ExceptionController所捕获呢?
我就是直接使用的该项目中的代码,因为该项目中也是用了@ExceptionHandler(ShiroException.class)进行捕捉的。 不知道你所说的那个项目代码哪里和这个有不一样呢?

@Smith-Cruise
Copy link
Owner

你参考下我的吧
https://github.com/Smith-Cruise/Spring-Boot-Shiro/blob/master/src/main/java/org/inlighting/controller/ExceptionController.java
比如@RestControllerAdvice这些注解你加了吗

@whyalwaysmea
Copy link
Author

添加了的,我试了一下你的demo,即使我乱输入一个token,是提示Unauthorized。按理来说应该是在MyRealm中跑token invalid异常。
我觉得是MyRealm 中抛出的异常,在JWTFilter中被catch了,然后就会走response401该方法。 所以MyRealm中的自定义异常似乎没有多大的作用了。
不知道我这样理解对不对,希望可以讨论一下,谢谢。(^__^)

@whyalwaysmea
Copy link
Author

如果在JWTFilter中的isAccessAllowed方法里不catch, 还是不会走ExceptionController 。

@Smith-Cruise
Copy link
Owner

我明天看看,最近比较忙。实在不行可以先像我一样catch下。

@Smith-Cruise
Copy link
Owner

看了下,的确没有什么好的办法,因为JWTFilter执行的时候SpringBoot的Controller都还没启动,所以无法捕捉异常,感觉还是URL redirect才是最好的办法了。

@Smith-Cruise Smith-Cruise reopened this Apr 10, 2018
@whyalwaysmea
Copy link
Author

是的,所以我现在将异常捕捉之后,把异常信息一起带到了401里面,然后通过401接口返回去

@Smith-Cruise
Copy link
Owner

好吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants