目录

springsecurity入门小案例.md

李羽秋
李羽秋 2022年01月26日  ·  阅读 1,249

springsecurity入门小案例

本案例将做权限控制,拥有admin角色才能访问/admin下的路径,其他角色不能访问。

1.导入依赖

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

2.新建contoller类

@Controller
public class HelloController {

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @ResponseBody
    @GetMapping("/admin/hello")
    public String admin(){
        return "admin";
    }
    @ResponseBody
    @GetMapping("/user/hello")
    public String user(){
        return "user";
    }

    @PostMapping("/doLogin")
    public String login(){
        return "redirect:main.html";
    }
}

3.自定义登录页面

<form action="/logina" method="post">
  <div class="input">
    <label for="name">用户名</label>
    <input type="text" name="username" id="name">
    <span class="spin"></span>
  </div>
  <div class="input">
    <label for="pass">密码</label>
    <input type="password" name="password" id="pass">
    <span class="spin"></span>
  </div>
  <div class="button login">
    <button type="submit">
      <span>登录</span>
      <i class="fa fa-check"></i>
    </button>
  </div>
</form>

4.security配置类

@Configuration
@EnableWebSecurity
public class SercuityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //将用户放在内存中
        auth.inMemoryAuthentication()
        		 //将用户信息加密
                .passwordEncoder(passwordEncoder())
                .withUser("li")
                .password(passwordEncoder().encode("123")).roles("admin")
                .and()
                .withUser("gong")
                .password(passwordEncoder().encode("456"))
                .roles("user");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        		//只有拥有admin角色才能进行访问/admin下所有资源
                .antMatchers("/admin/**").hasRole("admin")
                //只有拥有user角色才能进行访问/user下所有资源
                .antMatchers("/user/**").hasRole("user")
                //其他路径全部拦截,需先登录
                .anyRequest().authenticated();
                
                //自定义登录页面
        http.formLogin()
                 .loginPage("/login.html")
                 //登录处理接口,需和登录页面action地址一致
                .loginProcessingUrl("/logina")
                 //处理登录成功接口
                 .successForwardUrl("/doLogin")
                 .permitAll();
		//跨域保护关闭
        http.csrf().disable();
    }

    private PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

分类:
标签: