springboot Spring Security

初入门
核心依赖文件

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

当我们的web项目引入这个依赖之后 我们在访问请求 会弹出一个登录框
登录的默认名是user 密码则是随机生成打印在控制台上

如果不想随机生成 那么可以在application的配置文件中配置

#spring.security.user.name=wx
#spring.security.user.password=123
#spring.security.user.roles=admin

除了上面的配置外
还可以继承别的类 重写方法


/**
 * @author w
 */
@Configuration  //配置
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();//表示不对密码加密 
    }
    @Override
    protected void  configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123").roles("ADMIN","USER")//配置用户和用户角色
                .and()
                .withUser("jack").password("123").roles("USER")
                .and()
        .withUser("root").password("123").roles("ADMIN","DBA");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()//开启HttpSecurity的配置
        .antMatchers("/admin/**")//这行以及下面表示 访问这个路径 必须有下面的角色
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .access("hasAnyRole('ADMIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('ADMIN') and hasRole('DBA')")
                .anyRequest()//这行和下面一行表示表示除了前面定义的URL模式之外,用户访问其他的URL都必须认证后访问                .authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")//这行以及上两行表示开启表单登录
                .permitAll()//表示和登录相关的不需要认证即可访问
                .and()
                .csrf()
                .disable();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值