详解Springboot2.3集成Spring security 框架(原生集成)
0、pom
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.0.RELEASE com.jack demo 0.0.1-SNAPSHOT war demo DemoprojectforSpringSecurity 1.8 org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat provided org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.security spring-security-test test org.springframework.boot spring-boot-maven-plugin
1、SpringSecurityConfig(security配置)
//手动定义用户认证和//关联用户Service认证二者取一
这里测试用的是手动定义用户认证!!!
packagecom.jack.demo; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.context.annotation.Configuration; importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; importorg.springframework.security.config.annotation.web.builders.HttpSecurity; importorg.springframework.security.config.annotation.web.builders.WebSecurity; importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity; importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; /** *@program:demo *@description:Security配置 *@author:Jack.Fang *@date:2020-06-011541 **/ @Configuration @EnableWebSecurity publicclassSpringSecurityConfigextendsWebSecurityConfigurerAdapter{ @Autowired privateMyUserServicemyUserService; @Override protectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{ //手动定义用户认证 auth.inMemoryAuthentication().passwordEncoder(newBCryptPasswordEncoder()).withUser("admin").password(newBCryptPasswordEncoder().encode("123456")).roles("ADMIN"); auth.inMemoryAuthentication().passwordEncoder(newBCryptPasswordEncoder()).withUser("jack").password(newBCryptPasswordEncoder().encode("fang")).roles("USER"); //关联用户Service认证 //auth.userDetailsService(myUserService).passwordEncoder(newMyPasswordEncoder()); //默认jdbc认证 //auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(newMyPasswordEncoder()); } @Override protectedvoidconfigure(HttpSecurityhttp)throwsException{ http.authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .logout().permitAll() .and() .formLogin(); http.csrf().disable(); } @Override publicvoidconfigure(WebSecurityweb)throwsException{ web.ignoring().antMatchers("/js/**","/css/**","/image/**"); } }
2、MyPasswordEncoder(自定义密码比较)
packagecom.jack.demo; importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; importorg.springframework.security.crypto.password.PasswordEncoder; /** *@program:demo *@description:密码加密 *@author:Jack.Fang *@date:2020-06-011619 **/ publicclassMyPasswordEncoderimplementsPasswordEncoder{ @Override publicStringencode(CharSequencecharSequence){ returnnewBCryptPasswordEncoder().encode(charSequence.toString()); } @Override publicbooleanmatches(CharSequencecharSequence,Strings){ returnnewBCryptPasswordEncoder().matches(charSequence,s); } }
3、MyUserService(自行实现的用户登录接口)
具体内容省略。这里测试用的是SpringSecurityConfig手动添加用户名与密码。
packagecom.jack.demo; importorg.springframework.security.core.userdetails.UserDetails; importorg.springframework.security.core.userdetails.UserDetailsService; importorg.springframework.security.core.userdetails.UsernameNotFoundException; importorg.springframework.stereotype.Component; /** *@program:demo *@description:用户 *@author:Jack.Fang *@date:2020-06-011617 **/ @Component publicclassMyUserServiceimplementsUserDetailsService{ @Override publicUserDetailsloadUserByUsername(Strings)throwsUsernameNotFoundException{ returnnull; } }
4、启动类(测试)
DemoApplication.java
packagecom.jack.demo; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.security.access.prepost.PostAuthorize; importorg.springframework.security.access.prepost.PostFilter; importorg.springframework.security.access.prepost.PreAuthorize; importorg.springframework.security.access.prepost.PreFilter; importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; importorg.springframework.security.core.userdetails.User; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RestController; importjava.util.List; @EnableGlobalMethodSecurity(prePostEnabled=true) @RestController @SpringBootApplication publicclassDemoApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(DemoApplication.class,args); } @RequestMapping("/") publicStringindex(){ return"helloSpringSecurity!"; } @RequestMapping("/hello") publicStringhello(){ return"hello!"; } @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping("/roleAdmin") publicStringrole(){ return"adminauth"; } @PreAuthorize("#id<10andprincipal.username.equals(#username)and#user.username.equals('abc')") @PostAuthorize("returnObject%2==0") @RequestMapping("/test") publicIntegertest(Integerid,Stringusername,Useruser){ //... returnid; } @PreFilter("filterObject%2==0") @PostFilter("filterObject%4==0") @RequestMapping("/test2") publicListtest2(List idList){ //... returnidList; } }
测试hello接口(http://localhost:8080/hello)
未登录跳转登录页
登录SpringSecurityConfig配置的admin账号与密码123456
成功调用hello
测试roleAdmin(登录admin123456成功,登录jackfang访问则失败)
登出logout
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。