Spring Security is used for rights management.

Source: Internet
Author: User

1: Add Dependency:

        <Dependency>        <groupId>Org.thymeleaf.extras</groupId>        <Artifactid>Thymeleaf-extras-springsecurity4</Artifactid>    </Dependency>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-security</Artifactid>        </Dependency>

2: Create validation Service integration Userdetailservice

 Packagecom.qingwenwei.security;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.apache.logging.log4j.LogManager;ImportOrg.apache.logging.log4j.Logger;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.security.core.authority.SimpleGrantedAuthority;Importorg.springframework.security.core.userdetails.UserDetails;ImportOrg.springframework.security.core.userdetails.UserDetailsService;Importorg.springframework.security.core.userdetails.UsernameNotFoundException;ImportCom.qingwenwei.persistence.model.User;ImportCom.qingwenwei.service.UserService;ImportOrg.springframework.stereotype.Service; @Service Public classMyuserdetailsserviceImplementsuserdetailsservice{Logger Logger= Logmanager.getlogger (Myuserdetailsservice.class); @AutowiredPrivateUserService UserService; @Override PublicUserdetails Loaduserbyusername (String username)throwsusernamenotfoundexception {logger.debug ("Get User"); User User= This. Userservice.findbyusername (username); The password after encryption.        To perform the following authorization certification. Logger.debug (User.getusername ()+ "Password" +User.getpassword ());        The password after encryption. if(NULL==user) {            Throw NewUsernamenotfoundexception ("Can ' t find user by Username:" +username); } List<SimpleGrantedAuthority> grantedauthorities =NewArraylist<>(); //grant roles to user         for(String role:user.getRolesSet ()) {logger.debug (role); Grantedauthorities.add (Newsimplegrantedauthority (role)); }//user.setgrantedauthorities (authorities);//@AuthenticationPrincipal Tag value for login        return NewOrg.springframework.security.core.userdetails.User (User.getusername (), User.getpassword (),    Grantedauthorities); }}

3: Configure

 Packagecom.qingwenwei.security;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.security.authentication.AuthenticationProvider;ImportOrg.springframework.security.authentication.dao.DaoAuthenticationProvider;ImportOrg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;Importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;Importorg.springframework.security.config.annotation.web.builders.HttpSecurity;Importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;ImportOrg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;ImportOrg.springframework.security.core.userdetails.UserDetailsService;Importorg.springframework.security.crypto.bcrypt.bcryptpasswordencoder;@ Configuration@enablewebsecurity@enableglobalmethodsecurity (prepostenabled=true) Public classWebsecurityconfigextendsWebsecurityconfigureradapter {@Bean PublicBcryptpasswordencoder Bcryptpasswordencoder () {return NewBcryptpasswordencoder (); } @Autowired myuserdetailsservice Myuserdetailsservice;//@Bean//Userdetailsservice Myuserdetailsservice () {//Register Userdetailsservice//return new Myuserdetailsservice ();//    }@Bean PublicAuthenticationprovider Authenticationprovider () {Daoauthenticationprovider Authenticationprovider=NewDaoauthenticationprovider ();//Authenticationprovider.setuserdetailsservice (This.myuserdetailsservice ());Authenticationprovider.setuserdetailsservice (Myuserdetailsservice); Authenticationprovider.setpasswordencoder ( This. Bcryptpasswordencoder ()); returnAuthenticationprovider; } @Autowired Public voidConfigureglobal (Authenticationmanagerbuilder auth)throwsException {//auth.inmemoryauthentication ()//validation that exists in the memory//. Withuser ("T"). Password ("T"). Roles ("USER" )//. and ()//. Withuser ("admin"). Password ("admin") . Roles (" admin");Auth.userdetailsservice (Myuserdetailsservice). Passwordencoder ( This. Bcryptpasswordencoder ());//Auth.userdetailsservice (Myuserdetailsservice). Passwordencoder (New Bcryptpasswordencoder ());//Auth.authenticationprovider (This.authenticationprovider ());//different approach} @Overrideprotected voidConfigure (Httpsecurity http)throwsException {http.csrf (). Disable (). Authorizerequests (). Antmatchers ("/user/settings"). Authenticated ()//Order Matters. Antmatchers ("/", "/js/**", "/css/**", "/avatar/**", "/images/**", "/fonts/**", "/bootstrap-select/**", "/ bootstrap-datetimepicker/** ","/custom/** ","/daterangepicker/** ","/chartjs/** "). Permitall ()//These paths is configure not to require any authentication. Antmatchers ("/post/**"). Permitall ()//All posts is allowed to be viewed without authentication. Antmatchers ("/user/**"). Permitall ()//All user profiles is allowed to be viewed without authentication. Antmatchers ("/category/**"). Permitall ()//All categories is allowed to be viewed without authentication. Antmatchers ("/user/registration"). Permitall (). Antmatchers ("/avatar/**"). Permitall ()//Temp. Antmatchers ("/avatar1/**"). Permitall ()//Temp. Anyrequest (). Authenticated ()//every request requires the user to be authenticated. and (). Formlogin (). LoginPage ("/user/login"). Permitall ()//login URL can be accessed by anyone. and (). Logout (). Invalidatehttpsession (true). Clearauthentication (true). Logoutsuccessurl ("/?logout"). Permitall (); }}

4: Configuration succeeded.

Spring Security is used for rights management.

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.