ITPub博客

首页 > 架构设计 > 软件结构 > 电子商务Java微服务 SpringBoot整合SpringSecurity

电子商务Java微服务 SpringBoot整合SpringSecurity

原创 软件结构 作者:gung123 时间:2020-03-11 14:25:49 0 删除 编辑

一 初体验有spring cloud b2b2c电子商务需求的朋友可以加企鹅求求:一零三八七七四六二六 

1.导包

<dependency>

   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.测试

@RestController

public class HelloController
{
   @GetMapping("/hello")
   public String hello() {
       return "Hello";
   }
}

访问http://localhost:8080/hello 会自动跳到login页面
默认用户名 user
默认密码在控制台显示

二 在配置文件或代码中配置security需要的用户名和密码

第一种: 在配置文件中配置

spring.security.user.name=user

spring.security.user.password=123
spring.security.user.roles=admin

第二种:在代码中配置

新建一个SecurityConfig .java类

@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter
{
   //去掉spring5一定要密码加密的限制
   @Bean
   PasswordEncoder passwordEncoder(){
       return NoOpPasswordEncoder.getInstance();
   }
   //第二种: 在代码中配置用户名和密码
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception
   {
       auth.inMemoryAuthentication()
               .withUser("terry").password("123").roles("admin")
               .and()
               .withUser("tt").password("456").roles("user");
   }
}

三 配置HttpSecurity

1.接着上面的配置文件写

@Configuration

public class SecurityConfig extends WebSecurityConfigurerAdapter
{
   //去掉spring5一定要密码加密的限制
   @Bean
   PasswordEncoder passwordEncoder(){
       return NoOpPasswordEncoder.getInstance();
   }
   //第二种: 在代码中配置用户名和密码
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception
   {
       auth.inMemoryAuthentication()
               .withUser("terry").password("123").roles("admin")
               .and()
               .withUser("tt").password("456").roles("user");
   }

   //HttpSecurity配置
   @Override
   protected void configure(HttpSecurity http) throws Exception
   {
       http.authorizeRequests()
               .antMatchers("/admin/**").hasRole("admin")
               .antMatchers("/user/**").hasAnyRole("admin","user")
               //.antMatchers("/user/**").access("hasAnyRole('user','admin')")
               .anyRequest().authenticated()
               .and()
               .formLogin()
               .loginProcessingUrl("/doLogin")
               .permitAll()
               .and()
               .csrf().disable();//要使用postman,防止被认为是csrf攻击
   }
}

2.测试

@RequestMapping("/admin/hello")

public String admin(){
   return "Hello admin";
}

@RequestMapping("/user/hello")
public String user(){
   return "hello user";
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69952307/viewspace-2679614/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-11-01

  • 博文量
    200
  • 访问量
    79619