权限框架Spring Security

SpringSecurity权限框架实战
本文详细介绍了如何在项目中引入并配置SpringSecurity权限框架,包括添加依赖、配置类编写、接口方法实现、内存账号测试及自定义密码编解码器等步骤。

权限框架Spring Security

 第一步:在pom.xml文件中添加依赖


<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-security</artifactId>

</dependency>


第二步:简单模式测试,直接访问http://localhost:8080/

注:此处不可登录,未设置密码、用户名


第三步:添加配置测试

(1)创建配置类:

@Configuration

@EnableWebSecurity

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()

                .antMatchers("/").permitAll()

                .anyRequest().authenticated()

                .and()

                .logout().permitAll()

                .and()

                .formLogin();

        http.csrf().disable();

    }

    @Override

    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");

    }

}

(2)添加接口方法:

@GetMapping("/")

public String index(Long id){

    return "欢迎使用!";

}

直接访问http://localhost:8080/

 


第四步、添加内存账号测试

(1)增加内存账号配置到配置类:

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("ADMIN");

}

(2)添加端口配置

server:
  port: 80
  servlet:
    context-path: /user

(3)访问http://localhost:80/getList ,输入账号admin,密码123456:

第五步、添加自定义密码编解码测试;

(1)创建自定义密码编解码类:

public class MyPasswordEncoder implements PasswordEncoder {

    final static String ENCODER_PWD = "123456";

    @Override

    public String encode(CharSequence rawPassword) {

        return rawPassword + ENCODER_PWD;

    }

    @Override

    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        return encodedPassword.equals(rawPassword+ENCODER_PWD);

    }

}

(2)修改配置用户密码编解码方式:

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password(new MyPasswordEncoder().encode("123456")).roles("ADMIN");

}

(3)访问http://localhost:80/queryById?id=1 ,输入账号admin,密码123456:

注:因为上面的端口改成了80,所有后面的测试需要在80端口;queryById,是提前定义的一个方法,用于调出数据库中预定的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值