Spring boot front and rear detach project How to handle exceptions thrown by spring security

Source: Internet
Author: User
Tags getmessage

Recently in the development of a project before and after the separation of the use of spring boot + spring Security + JWT implementation of user login rights control and other operations. But how do you handle the exception that spring security throws when the user logs in? Using @restcontrolleradvice and @exceptionhandler cannot handle exceptions thrown by spring security, such as usernamenotfoundexception and so on, I want to be friendly to the front end to return prompt information such as , the user name does not exist or the like. Stick to My Code:

JWT validation class: overriding Spring Security Usernamapasswordauthenticationfilter

PublicClassJwtauthenticationfilterExtendsUsernamepasswordauthenticationfilter {PrivateAuthenticationManager AuthenticationManager;PrivateRedisserviceimpl Redisservice;PrivateAppConfig AppConfig; PublicJwtauthenticationfilter (AuthenticationManager AuthenticationManager,Redisserviceimpl Redisservice,AppConfig AppConfig) {This.authenticationmanager = AuthenticationManager;This.redisservice = Redisservice;This.appconfig = AppConfig; }/** * @param req * @param res * @return * @throws authenticationexception * @//TODO:2018/4/12 Accept and resolve user credentials */@Override PublicAuthentication Attemptauthentication (HttpServletRequest req,HttpServletResponse Res)Throwsauthenticationexception {try {Authentity creds =NewObjectmapper (). ReadValue (Req.getinputstream (),Authentity.Class);Verification Code Checkif (appconfig.getcaptchaenabled ()) {If the Verification code login check function is turned onif (Stringutils.isblank (Creds.getcaptcha ())) {Logger.error ("Verification code is empty");ThrowNewWelendexception (StatusCode.Captcha_empty); }if (!redisservice.exists (Appconfig.getcaptchakey ())) {Logger.error ("Verification Code is invalid");ThrowNewWelendexception (StatusCode.Captcha_overdue); }String Captcha = (String) Redisservice.get (Appconfig.getcaptchakey ());if (!creds.getcaptcha (). Equals (Captcha)) {Logger.error ("Verification Code is incorrect");throw New welendexception (StatusCode.  CAPTCHA_ERROR); }} return Authenticationmanager.authenticate ( new Usernamepasswordauthenticationtoken ( Creds.getusername (), Creds.getpassword (), new arraylist<> ()); } catch (IOException e) {logger.error ("Client ' s variables can ' t be parsed by COM.FASTERXML.JACKSON.CORE.J Sonparse "); throw New welendexception (StatusCode.  SERVER_ERROR); } }}

Verify User name Password:

PublicClassCustomauthenticationproviderImplementsAuthenticationprovider {Private Userdetailsserviceimpl Userdetailsservice;Private Bcryptpasswordencoder Bcryptpasswordencoder;PublicCustomauthenticationprovider(Userdetailsserviceimpl Userdetailsservice, Bcryptpasswordencoder bcryptpasswordencoder) {This.userdetailsservice = Userdetailsservice;This.bcryptpasswordencoder = Bcryptpasswordencoder; }@OverridePublic authenticationAuthenticate(Authentication authentication)Throws Authenticationexception {Get authenticated username & password String name = Authentication.getname (); String password = authentication.getcredentials (). toString ();Authentication logic Jwtuserdetails userdetails = userdetailsservice.loaduserbyusername (name);if (Null! = userdetails) {Boolean verifypwd = bcryptpasswordencoder.matches (Password,userdetails.getloginpwd ());if (verifypwd) {Generate tokens here the tokens are deposited: userdetails,password,authorities (permission list) Authentication auth =New Usernamepasswordauthenticationtoken (userdetails, Password, userdetails.getauthorities ());return auth; }else { throw new Badcredentialsexception ("username or password wrong!");}} else { throw new Usernamenotfoundexception ("Can not find this account");}} /** * can provide authentication service for input type * @param authentication * @return */ @Override public   boolean Suppo RTS(class<?> authentication) { return authentication.equals ( Usernamepasswordauthenticationtoken.class); }}

Global exception Handling

@RestControllerAdvicepublic class Globalexceptionhandler {private Logger Logger = Loggerfactory. GetLogger (GetClass ());/** * @param Request * @param exception * @return * @throws Exception * @//TODO:2018/4/25 parameter failed validation exception */@ExceptionHandler (value = methodargumentnotvalidexception.class) public Object Methodargumentnotvalidhandler ( HttpServletRequest request, Methodargumentnotvalidexception exception) throws exception {Re-encapsulate on-demand error messages that need to be returnedlist<statuscode> invalidarguments = new arraylist<> ();Parse the original error message, return it after encapsulation, return the illegal field name, original value, error message Resultobject resultmsg = Resultobject. Datamsg (Exception.getbindingresult (). Getfielderror (). Getdefaultmessage (), statuscode.variable_error); return resultmsg; }/** * @param Request * @param exception * @return * @throws Exception * @//TODO:2018/4/25 cannot parse parameter exception */@ExceptionHandler (value = httpmessagenotreadableexception.class) public Object Httpmessagenotreadablehandler ( HttpServletRequest request, Httpmessagenotreadableexception exception) throws exception {Logger. info (Exception.getmessage ()); Resultobject resultmsg = Resultobject. DATAMSG ("parameter cannot be parsed properly", statuscode.variable_error); return resultmsg; }/** * @param exception * @return * @throws Exception * @//TODO:2018/4/25 Handling Token Expiration Exception */@ExceptionHandler (value = expiredjwtexception.class) public Object Expiredjwtexceptionhandler (expiredjwtexception Exception) throws Exception {Logger. info (Exception.getmessage ()); Resultobject resultmsg = Resultobject. DATAMSG ("Login has expired!" ", Statuscode.forbidden); return resultmsg; }/** * @param Request * @param exception * @return * @throws Exception * @//Todo:2018/4/25 method Insufficient Access exception */@ExceptionHandler (value = accessdeniedexception.class) public Object Accessdeniedexceptionhandler ( Accessdeniedexception exception) throws exception {Logger. info (Exception.getmessage ()); Resultobject resultmsg = Resultobject. DATAMSG ("Insufficient Permissions!" ", Statuscode.forbidden); return resultmsg; }@ExceptionHandler (value = nohandlerfoundexception.class) public Object Nohandlerfoundexceptionhandler ( Nohandlerfoundexception exception) throws exception {Logger. info (Exception.getmessage ()); Return Resultobject. DATAMSG ("Link does not exist", statuscode.not_found); }/** * Handling of custom exceptions */@ExceptionHandler (value = welendexception.class) public Object Welendexceptionhandler (welendexception e) { Resultobject r = new Resultobject (); R. SetStatus (String.valueof (E.getcode ())); R. Setmessage (E.getmessage ()); return R; }@ExceptionHandler (value = authenticationexception.class) public Object Authenticationexceptionhandler ( Authenticationexception e) {return resultobject. Datamsg (E.getlocalizedmessage (), Statuscode.forbidden); }@ExceptionHandler (value = duplicatekeyexception.class) public Object Duplicatekeyexceptionhandler ( Duplicatekeyexception e) throws Exception {Logger. Error (E.getmessage (), e); return resultobject. codemsg (statuscode.existed);} @ExceptionHandler (value = badcredentialsexception.class) public Object Badcredentialsexceptionhandler ( Badcredentialsexception e) throws Exception {logger. Error (E.getmessage (), e); return resultobject. Codemsg ( STATUSCODE.AUTH_ERROR); } @ExceptionHandler (value = exception.class) public Object Exceptionhandler (Exception e) throws Exception {Logger
                                               
                                                .error (E.getmessage (), E); Return Resultobject
                                                . codemsg (statuscode.failed);}} 
                                                    

Enter the wrong user name at logon

The console directly prints the information and does not undergo exceptionhandler processing.

As shown above, I want to handle spring security throwing exceptions in the global exception class in order to return friendly hints. Is there any way out?

Spring boot front and rear detach project How to handle exceptions thrown by spring security

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.