权限框架Spring Security

  • Post author:
  • Post category:其他


权限框架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,是提前定义的一个方法,用于调出数据库中预定的数据。



版权声明:本文为weixin_44746721原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。