SpringBoot-HttpSecurity

使用HttpSecutiry 同样要使用WebSecurityConfigurerAdapter类的重载,他重载的方法是configure(HttpSecurity http)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("uuc").password("123").roles("admin")
                .and()
                .withUser("akk").password("123").roles("user");
    }    


    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //开启配置
        http.authorizeRequests()
        //ant风格的路径匹配符,当符合/admin/**,将具有admin权限
                .antMatchers("/admin/**").hasRole("admin")
//只要符合路径,就可以具备admin或者user任意一个权限
                .antMatchers("user/**").hasAnyRole("admin","user")
                //其他的请求authenticated登录之后就能访问
                .anyRequest().authenticated()
                .and()
                //表单登录
                .formLogin()
                //处理登陆的url
                .loginProcessingUrl("/doLogin")
                //跟登录相关的访问可以直接过
                .permitAll()
                .and()
                //postman测试需要关闭防止csrf攻击
                .csrf().disable();
    }
}

使用普通用户登录admin权限地址
在这里插入图片描述
没有权限
Type = Forbiden,status = 403
在这里插入图片描述
user可以正常登录
在这里插入图片描述

相关代码使用postman测试的时候所需要

                //表单登录
                .formLogin()
                //处理登陆的url
                .loginProcessingUrl("/doLogin")
                //跟登录相关的访问可以直接过
                .permitAll()
                .and()
                //postman测试需要关闭防止csrf攻击
                .csrf().disable();

get获取登录请求
在这里插入图片描述

post进行登录.请求路径就是/doLogin
在这里插入图片描述

其他的configure设置

  .antMatchers("/user/**").access("hasAnyRole('user','admin')")
//即拥有管理员有拥有普通用户
  .antMatchers("/user/**").access("hasRole('user' and 'admin')")
发布了35 篇原创文章 · 获赞 1 · 访问量 613

猜你喜欢

转载自blog.csdn.net/weixin_39232166/article/details/105306466