1.创建项目集成依赖
-
org.springframework.boot -
spring-boot-starter-security
- @RestController
- public class Test {
- @GetMapping("/test")
- public String test(){
- return "test";
- }
- }
下面用到的测试方法
- @RestController
- public class Test {
- @GetMapping("/test")
- public String test(){
- return "test";
- }
- @GetMapping("/admin/hello")
- public String testadmin(){
- return "admin";
- }
- @GetMapping("/user/hello")
- public String testuser(){
- return "user";
- }
- }
用户名user 密码为项目日志打印
2.配置访问用户名和密码
- spring.security.user.name=liuboss
- spring.security.user.password=123456
- spring.security.user.roles=admin
3.添加配置类---配置用户名和密码。
- @Configuration
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
-
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- return NoOpPasswordEncoder.getInstance();
- }
-
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("boss").password("123").roles("admin")
- .and()
- .withUser("liuboss").password("123").roles("admin");
- }
- }
4.配置访问角色和登录页面
- @Configuration
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
-
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- return NoOpPasswordEncoder.getInstance();
- }
-
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("admin").password("123").roles("admin")
- .and()
- .withUser("user").password("123").roles("user");
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .antMatchers("/admin/**").hasRole("admin")
- .antMatchers("user/**").hasAnyRole("admin","user")
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/doLogin")
- .permitAll()
- .and()
- /*关闭攻击使用postman测试*/
- .csrf().disable();
- }
- }
5.登陆表单的配置,增加登陆成功,登陆失败处理。
- @Configuration
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
-
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- return NoOpPasswordEncoder.getInstance();
- }
-
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("admin").password("123").roles("admin")
- .and()
- .withUser("user").password("123").roles("user");
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .antMatchers("/admin/**").hasRole("admin")
- .antMatchers("user/**").hasAnyRole("admin","user")
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/doLogin")
- /*跳转到登录页面*/
- .loginPage("/login")
- /*登陆成功的处理*/
- .successHandler(new AuthenticationSuccessHandler() {
- @Override
- public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
- resp.setContentType("application/json;charset=utf-8");
- PrintWriter out = resp.getWriter();
- HashMap
- map.put("status",200);
- map.put("msg",authentication.getPrincipal());
- out.write(new ObjectMapper().writeValueAsString(map));
- out.flush();
- out.close();
- }
- })
- /*登陆失败的处理*/
- .failureHandler(new AuthenticationFailureHandler() {
- @Override
- public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
- resp.setContentType("application/json;charset=utf-8");
- PrintWriter out = resp.getWriter();
- HashMap
- map.put("status",401);
- if (e instanceof LockedException){
- map.put("msg","账户被锁定,登录失败");
- } else if (e instanceof BadCredentialsException){
- map.put("msg","账户名或密码错误,登录失败");
- } else if (e instanceof DisabledException){
- map.put("msg","账户被禁用,登录失败");
- } else if (e instanceof AccountExpiredException){
- map.put("msg","账户过期登录失败");
- } else {
- map.put("msg","登录失败");
- }
- out.write(new ObjectMapper().writeValueAsString(map));
- out.flush();
- out.close();
- }
- })
- .permitAll()
- .and()
- /*关闭攻击使用postman测试*/
- .csrf().disable();
- }
- }
6.多个http security 的配置。
- @Configuration
- public class MultHttpSecurityConfig {
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- return NoOpPasswordEncoder.getInstance();
- }
- @Autowired
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("admin").password("1234").roles("admin")
- .and()
- .withUser("user").password("1234").roles("user");
- }
- /*多个http配置*/
- @Configuration
- /*@Order(1) 为访问优先级,数字越低,优先级越高*/
- @Order(1)
- public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
- }
- }
-
- @Configuration
- public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/doLogin")
- .permitAll()
- .and()
- .csrf().disable();
- }
- }
-
- }
7.密码加密 使用此方式
- @org.junit.jupiter.api.Test
- public void contentLoads(){
- for (int i = 0; i < 10; i++) {
- BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
- System.out.println(encoder.encode("123456"));
- }
- }
8.配置密码加密方式
- @Configuration
- public class MultHttpSecurityConfig {
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- /*return NoOpPasswordEncoder.getInstance();*/
- /*使用BCryptPasswordEncoder加密方式*/
- return new BCryptPasswordEncoder();
- }
- @Autowired
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("admin").password("$2a$10$/NB.L1nOJnBPsi3KTfvJfuoZCbOf.choREFrVZQXqCldfa0a3KNtq").roles("admin")
- .and()
- .withUser("user").password("$2a$10$4zwF70VbjE67IgiVmpLGVeuvg59DyJh/BN60drYw96XkHshXnln7K").roles("user");
- }
- /*多个http配置*/
- @Configuration
- /*@Order(1) 为访问优先级,数字越低,优先级越高*/
- @Order(1)
- public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
- }
- }
-
- @Configuration
- public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/doLogin")
- .permitAll()
- .and()
- .csrf().disable();
- }
- }
-
- }
9.方法的安全
配置类
-
- @Configuration
- /*开启方法安全*/
- @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
- public class MultHttpSecurityConfig {
- /*提供实例--不需要加密*/
- @Bean
- PasswordEncoder passwordEncoder(){
- /*return NoOpPasswordEncoder.getInstance();*/
- /*使用BCryptPasswordEncoder加密方式*/
- return new BCryptPasswordEncoder();
- }
- @Autowired
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication()
- .withUser("admin").password("$2a$10$/NB.L1nOJnBPsi3KTfvJfuoZCbOf.choREFrVZQXqCldfa0a3KNtq").roles("admin")
- .and()
- .withUser("user").password("$2a$10$4zwF70VbjE67IgiVmpLGVeuvg59DyJh/BN60drYw96XkHshXnln7K").roles("user");
- }
- /*多个http配置*/
- @Configuration
- /*@Order(1) 为访问优先级,数字越低,优先级越高*/
- @Order(1)
- public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
- }
- }
-
- @Configuration
- public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/doLogin")
- .permitAll()
- .and()
- .csrf().disable();
- }
- }
-
- }
service层配置
- @Service
- public class MethodService {
- @PreAuthorize("hasAnyRole('admin')")
- public String admin(){
- return "hello admin";
- }
- @Secured("ROLB_user")
- public String user(){
- return "hello user";
- }
- @PreAuthorize("hasAnyRole('admin','user')")
- public String hello (){
- return "hello hello";
- }
- }
controller运用
- @Autowired
- MethodService methodService;
-
- @GetMapping("/hello1")
- public String hello1(){
- return methodService.admin();
- }
- @GetMapping("/hello2")
- public String hello2(){
- return methodService.user();
- }
- @GetMapping("/hello3")
- public String hello3(){
- return methodService.hello();
- }