SpringBoot2.0.3 + SpringSecurity5.0.6 + Vue front-end Separation authentication Authorization

Source: Internet
Author: User

New project introduces safety control

The new spring security component was recently added to the project, and was not used in the early days, with a few references to the latest version, and a four-day pit stop to complete the initial solution. It's really simple, Spring Security5 is much less configurable than previous versions, and it's lighter to operate

MARIADB Login Configure encryption Policy

SpringSecurity5 When performing login authentication, the encryption policy must be preset.

Pit One: Encryption policy configuration, verification will never pass, error 401

Pit Two: The local rewrite of the Userdetailsservice implementation class at the time of injection can not be found, the current diagram of the trouble directly with the @Qualifier to develop

Other, entity class user implementation Userdetails,role implementation grantedauthority and previous version and have too much change, can refer to a lot, do not repeat

The code is as follows:

/*** The implementation class of the Userdetailsservice interface that is overridden in the project, you need to specify*/@Qualifier ("UserService") @AutowiredPrivateUserdetailsservice Userdetailsservice; /*** Initial authentication login take password from memory *@paramAuth *@throwsException*/@Autowired Public voidConfigureglobal (Authenticationmanagerbuilder auth)throwsException {auth.userdetailsservice (userdetailsservice). Passwordencoder (NewBcryptpasswordencoder ()); }
Cross-domain issues

Springboot2.0.3 is especially easy when dealing with cross-domain, just

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity (prepostenabled = True)
@Order (-1)
Httpsecurity in the configuration class, plus cors (), do not need to write the filter wrapper httpservletresponse operation

  Login error 403, insufficient permissions
There are a lot of solutions here, because this article is not small, directly shut down the CSRF (cross-site request forgery) can
Ibid., csrf (). Disable ().
   
  Maximum pit--open across domains, each login returned as an anonymous user Anonymoususer
Problem Description:
Cross-domain is open, using swagger access is not a problem, when the front-end separation, springsecurity also works, and eventually logon is unsuccessful, return anonymous users
Close anonymous user anonymous (). disable (), direct error 401, user name or password wrong
Encountered this problem, has been tangled in the cross-domain, but did not go deep to see the front-end HTTP request on the information given, the reason is very simple, the problem of logon redirection
In Httpsecurity, when you choose Formlogin (), you will then choose a variety of successful URLs, then the code to implement the relevant interface, in fact, into the pit.
Note: When using AJAX logins on the front-end, springsecurity can only complete related processing logic by overriding processor handler related to success/failure/exit, etc.
Full Configuration Class Code:
@EnableWebSecurity @configuration@enableglobalmethodsecurity (prepostenabled=true) @Order (-1) Public classSecurityconfigextendswebsecurityconfigureradapter {@Autowired Customizeauthenticationsuccesshandler customizeauthenticationsuccess    Handler;    @Autowired Customizeauthenticationfailhandler Customizeauthenticationfailhandler;    @Autowired customizeauthenticationaccessdenied customizeauthenticationaccessdenied;    @Autowired Customizeauthenticationlogout customizeauthenticationlogout; @Overrideprotected voidConfigure (Httpsecurity http)throwsException {http. csrf (). Disable (). Anonymous (). Disable (). Cors () . and (). Httpbasic (). and ()//Login Success Page and Login failed page. Formlogin (). Successhandler (Customizeauthenticationsuccesshandler). Failurehandler (Cust Omizeauthenticationfailhandler). Permitall (). and ()//insufficient permissions, i.e. jump page at 403. ExceptionHandling (). Accessdeniedhandler (customizeauthenticationaccessdenied). Authenticationentrypoint (NewUnauthorizedentrypoint ()). and (). Logout (). Logoutsuccesshandler (customizeauthenticationlogout). permital L (). and (). Authorizerequests (). Antmatchers (httpmethod.options). Permitall ()//Access without permission. Antmatchers ("/logout"). Permitall ()//user role is required to access. Antmatchers ("/person/**"). Hasrole ("person"))                //Admin role required to access. Antmatchers ("/user/**"). Hasrole ("ADMIN")); }    /*** The implementation class of the Userdetailsservice interface that is overridden in the project, you need to specify*/@Qualifier ("UserService") @AutowiredPrivateUserdetailsservice Userdetailsservice; /*** Initial authentication login take password from memory *@paramAuth *@throwsException*/@Autowired Public voidConfigureglobal (Authenticationmanagerbuilder auth)throwsException {auth.userdetailsservice (userdetailsservice). Passwordencoder (NewBcryptpasswordencoder ()); }}

Rewrite the login success handler code as follows:

@Component Public classCustomizeauthenticationsuccesshandlerImplementsAuthenticationsuccesshandler {Private Static FinalLogger Logger = Loggerfactory.getlogger (Customizeauthenticationsuccesshandler.class); @Override Public voidonauthenticationsuccess (httpservletrequest request, HttpServletResponse Respon SE, authentication authentication)throwsIOException, servletexception {logger.info ("At Onauthenticationsuccess (...) function! "); Webauthenticationdetails Details=(webauthenticationdetails) Securitycontextholder.getcontext (). Getauthentication (). Getdetails (); Logger.info ("Login--ip:" +details.getremoteaddress ()); SecurityContext Context=Securitycontextholder.getcontext (); Authentication Authentication1=context.getauthentication (); Object principal=Authentication1.getprincipal (); Object Principal1=Authentication.getprincipal (); String name=Authentication.getname (); Logger.info ("Login--name:" +name+ "Principal:" +principal+ "Principal1:" +principal1); PrintWriter out=NULL; Try{ out=Response.getwriter (); Out.append (Jsonobject.tojsonstring (Responsedata.ok () Putdatavalue ("User", Principal). Putdatavalue ("Name", name))); } Catch(IOException e) {e.printstacktrace (); }finally {            if(Out! =NULL) {out.close (); }        }    }}

SpringBoot2.0.3 + SpringSecurity5.0.6 + Vue front-end Separation authentication Authorization

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.