Springsecurity-HttpSecurity(三)

1、接着Springsecurity(二)书写配置文件,重写configure(HttpSecurity http)方法。配置自定义的登录页面,登录访问路径(等于前端表单的action地址),成功登录后的跳转地址。

@Configuration
public class SecurityConfig1 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        这边是我们原来自定义账号密码
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        String encode = bCryptPasswordEncoder.encode("zyf");
//        auth.inMemoryAuthentication().withUser("zyf").password(encode).roles("admin");

//      现在我们通过
        auth.userDetailsService(userDetailsService).passwordEncoder(get());
    }

    @Bean
    PasswordEncoder get(){
        return new BCryptPasswordEncoder();
    }
//

//  可以对请求的路径进行相对应的设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置认证
        http.formLogin() //自定义自己编写的登录页面
                .loginPage("/login.html") // 配置哪个 url 为登录页面
                .loginProcessingUrl("/user/login") // 登录访问路径。
                .defaultSuccessUrl("/success.html").permitAll()//登陆成功之后跳转地址
                .and().authorizeRequests();
                .and().csrf().disable();// 关闭 csrf保护功能
    }
}

2、自定义登录页面login.html;最主要的是首先是表单的action需要与**loginProcessingUrl("")**一致,表单的输入框的name=“username”;name=“password”;提交方式是post;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<section>
            <div class="form">
                <h1 align="center" >登录</h1>
                <form action="/user/login" method="post">
                    <div class="inputBox">
                        <input type="text" placeholder="username" name="username">
                    </div>
                    <div class="inputBox">
                        <input type="password" placeholder="password" name="password">
                    </div>
                    <div class="inputBox">
                        <input type="submit" value="登录">
                    </div>
                </form>
            </div>
    </div>
</section>
</body>
</html>

3、直接访问:http://localhost:8080/login.html,才会跳转到这个成功界面。
在这里插入图片描述
在这里插入图片描述
4、允许请求直接访问目标地址/test2/hello不需要经过验证

.antMatchers("/","/test2/hello").permitAll()

5、用户需要拥有这个权限才可以访问访问目标地址,如果没有权限会报错403
http.exceptionHandling().accessDeniedPage("/unauth.html");这条命令可以设置没有权限的跳转地址;

List authorities =AuthorityUtils.commaSeparatedStringToAuthorityList(“admin”);//设置权限后就可以访问
.antMatchers("/test2/index").hasAuthority(“admin”)

6、一系列关于请求地址请求方式的测试

//  可以对请求的路径进行相对应的设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.exceptionHandling().accessDeniedPage("/unauth.html");
        // 配置认证
        http.formLogin() //自定义自己编写的登录页面
                .loginPage("/login.html") // 配置哪个 url 为登录页面
                .loginProcessingUrl("/user/login") // 登录访问路径。
                .defaultSuccessUrl("/success.html").permitAll()//登陆成功之后跳转地址
                .and().authorizeRequests()
                .antMatchers("/","/test2/hello").permitAll()  //允许请求直接访问不需要经过验证
                .antMatchers("/test2/hello1").hasAuthority("admin")  //满足权限
                .antMatchers("/test/index").hasAnyAuthority("admin,manager")
                .antMatchers("/test/index").hasRole("sale1")
                .anyRequest().authenticated()
                .and().csrf().disable();// 关闭 csrf保护功能

    }

7、常用注解的使用

@RestController
@RequestMapping("/test2")
public class Controller {
    @GetMapping("/hello_word")
    public String test(){
        System.out.println("hello");
        return "hello world";
    }

//    .antMatchers("/","/test2/hello","/user/login").permitAll()  //允许请求直接访问?
    @GetMapping("/hello")
    public String hello() {
        return "hello springsecurity";
    }

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


    @GetMapping("/update")
    @Secured({"ROLE_sale", "ROLE_manager"})
    public String update() {
        return "hello update";
    }


    @GetMapping("/pre")
    @PreAuthorize("hasAnyAuthority('admin')")//方法之前,直接就报错
    public String pre() {
        return "hello pre";
    }

    @GetMapping("/post")
    @PostAuthorize("hasAuthority('admins11')") //没有权限先执行方法在显示出错,这个就是方法之后
    public String post() {
        System.out.println("hello world");
        return "hello post";
    }

    @RequestMapping("/testPostAuthorize")
    @PostAuthorize("hasAnyAuthority('menu:system')")
    public String preAuthorize() {
        System.out.println("test--PostAuthorize");
        return "PostAuthorize";
    }

    @RequestMapping("/getAll")
//    @PreAuthorize("hasRole('ROLE_管理员')")
    @PostFilter("filterObject.username == 'admin1'")
    public List<Users> getAllUser(){
        ArrayList<Users> list = new ArrayList<>();
        list.add(new Users(11,"admin1","6666"));
        list.add(new Users(22,"admin2","888"));
        return list;
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值