Security认证授权

类似于拦截器,过滤器,AOP。这个更为简洁

基于SpringBoot版本2.0.9以下

1.导入maven依赖

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

2.编写Security配置类

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity  //开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //1.授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问,其他页面只有有对应权限的人才可以访问
        // 认证请求:authorizeRequests()
        http
                .authorizeRequests()
                .antMatchers("/","/login","/home").permitAll()   //所有人可以访问的页面
                .antMatchers("/page1/**").hasAnyRole("admin1") //vip1才可以访问的页面
                .antMatchers("/page2/**").hasAnyRole("admin2") //vip2才可以访问页面
                .antMatchers("/page3/**").hasAnyRole("admin3"); //vip2才可以访问页面
//                .anyRequest().authenticated()
//                .and()
//                .formLogin()
//                .loginPage("/login").permitAll()
//                .and()
//                .logout()
//                .permitAll();

        //没有权限的话,会跳到login页面
        http.formLogin();

        //关闭csrf功能,跨站访问
        http.cors().disable();

        
        //注销,成功后跳到首页  logoutUrl = "/logout"  logoutSuccessUrl = "/login?logout"
        http.logout().logoutSuccessUrl("/");

    }

    //2.认证
    //需要 密码编码:PasswordEncoder
    // 早Spring Securty 5.0+ 新增了很多的加密方法 ,还有java原生的MD5 等等
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        
//从数据库认证:jdbcAuthentication()  ,没连数据库 从内存认证:inMemoryAuthentication(),这里实验就直接使用实验内存认证了
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())   //加密的方法
                .withUser("lan")    //用户名
                .password(new BCryptPasswordEncoder().encode("123"))    //密码
                .roles("admin1")   //拥有的权限 
                .and()  //加下一个用户
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("admin1","admin2","admin3")

    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值