SpringBoot整合Security静态权限案例

一、相关pom依赖

 <dependencies>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
       
        <!-- springBoot整合freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!--springBoot整合security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

二、案例环境准备代码

1)、application.yml

server:
  port: 9001
# 配置freemarker
spring:
  freemarker:
    # 设置模板后缀名
    suffix: .ftl
    # 设置文档类型
    content-type: text/html
    # 设置页面编码格式
    charset: UTF-8
    # 设置页面缓存
    cache: false
    # 设置ftl文件路径
    template-loader-path:
      - classpath:/templates
  # 设置静态文件路径,js,css等
  mvc:
    static-path-pattern: /static/**

2)、controller案例代码

@Controller
public class OrderController {
	// 首页
	@RequestMapping("/")
	public String index() {
		return "index";
	}

	// 查询订单
	@RequestMapping("/showOrder")
	public String showOrder() {
		return "showOrder";
	}

	// 添加订单
	@RequestMapping("/addOrder")
	public String addOrder() {
		return "addOrder";
	}

	// 修改订单
	@RequestMapping("/updateOrder")
	public String updateOrder() {
		return "updateOrder";
	}

	// 删除订单
	@RequestMapping("/deleteOrder")
	public String deleteOrder() {
		return "deleteOrder";
	}

	// 自定义登陆页面
	@GetMapping("/login")
	public String login() {
		return "login";
	}

}

3)、默认配置时测试访问主页,默认是fromLogin模式

三、修改默认配置

1)、httpBasicm模式案例(浏览器与服务器做认证授权)

配置安全认证:

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置认证用户信息和权限
     * @param auth 认证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置账户权限
        auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("addOrder");

    }

    /**
     * 配置拦截请求资源
     * @param http 请求
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //拦截所有请求,设置认证模式为httpBasic
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
    }

    /**
     * 配置密码不加密
     * @return NoOpPasswordEncoder
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}

访问主页:

2)、formLogin模式案例

配置安全认证:

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置认证用户信息和权限
     * @param auth 认证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置管理员有showOrder updateOrder addOrder deleteOrder 权限
        auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("showOrder","updateOrder","addOrder","deleteOrder");
        //设置普通用户有showOrder updateOrder  权限
        auth.inMemoryAuthentication().withUser("user").password("123456").authorities("showOrder","updateOrder");

    }

    /**
     * 配置拦截请求资源
     * @param http 请求
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //拦截所有请求,设置认证模式为formLogin
        http.authorizeRequests()
                //配置查询订单权限
                .antMatchers("/showOrder").hasAnyAuthority("showOrder")
                //配置新增订单权限
                .antMatchers("/addOrder").hasAnyAuthority("addOrder")
                //配置修改订单权限
                .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
                //配置删除订单权限
                .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
                .antMatchers("/**").fullyAuthenticated().and().formLogin();
    }

    /**
     * 配置密码不加密
     * @return NoOpPasswordEncoder
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}

验证结果管理员有所有权限,普通用户只有查询和修改权限:

四、配置自定义错误页和登入页

1)、错误页

@Configuration
public class WebServerAutoConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}
@Controller
public class ErrorController {

	// 403权限不足页面
	@RequestMapping("/error/403")
	public String error() {
		return "/error/403";
	}
	...
}

2)、登入页

http.authorizeRequests()
                //配置查询订单权限
                .antMatchers("/showOrder").hasAnyAuthority("showOrder")
                //配置新增订单权限
                .antMatchers("/addOrder").hasAnyAuthority("addOrder")
                //配置修改订单权限
                .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
                //配置删除订单权限
                .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
                //配置自定义登入页,禁用csrf(方便演示)
                .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();

3)、自定义认证成功或者失败处理

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

	public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
			throws IOException, ServletException {
		System.out.println("用户认证失败");
		res.sendRedirect("https://www.zhqwfj.xyz");
	}

}
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	// 用户认证成功
	public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
			throws IOException, ServletException {
		System.out.println("用户登陆成功");
		res.sendRedirect("/");
	}
}
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
    private MyAuthenticationSuccessHandler successHandler;
	@Autowired
    private MyAuthenticationFailureHandler failHandler;
	// 用户认证信息
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 设置用户账号信息和权限
		 auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("showOrder","addOrder","updateOrder","deleteOrder");
		 // 添加 useradd账号 只有添加查询和添加订单权限
		 auth.inMemoryAuthentication().withUser("userAdd").password("123456")
			.authorities("showOrder","addOrder");
	}

	// 配置HttpSecurity 拦截资源
	protected void configure(HttpSecurity http) throws Exception {
// 拦截请求, 权限名称
		http.authorizeRequests()
		.antMatchers("/showOrder").hasAnyAuthority("showOrder")
		.antMatchers("/addOrder").hasAnyAuthority("addOrder")
		.antMatchers("/login").permitAll()
		.antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
		.antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
		//并且关闭csrf
		.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").successHandler(successHandler).failureHandler(failHandler).and().csrf().disable();
		
	
	}

	// SpringBoot2.0抛弃了原来的NoOpPasswordEncoder,要求用户保存的密码必须要使用加密算法后存储,在登录验证的时候Security会将获得的密码在进行编码后再和数据库中加密后的密码进行对比
	@Bean
	public static NoOpPasswordEncoder passwordEncoder() {
		return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot是一个快速开发应用程序的框架,Spring Security是一个安全框架,可以对应用程序进行身份验证和授权。在Spring Boot中,可以将Spring Security与应用程序集成,实现对用户身份验证和授权的支持。 以下是在Spring Boot整合Spring Security进行权限校验的步骤: 1. 添加Spring Security依赖 在build.gradle或pom.xml中添加Spring Security依赖: ``` implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. 创建Spring Security配置类 创建一个继承自WebSecurityConfigurerAdapter的配置类: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and().formLogin() .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login") .permitAll(); } } ``` 在configure方法中配置Spring Security: - 配置用户认证,使用UserDetailsService实现类和BCryptPasswordEncoder进行密码加密 - 配置请求授权,指定请求路径需要哪些角色才能访问 - 配置登录页面和登出路径 3. 创建用户实体类和用户认证实现类 创建一个用户实体类和一个实现UserDetailsService接口的用户认证实现类: ``` @Entity @Table(name = "users") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "enabled") private boolean enabled; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<>(); // getters and setters @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList()); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } } ``` ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return user; } } ``` 4. 创建角色实体类和角色认证实现类 创建一个角色实体类和一个实现GrantedAuthority接口的角色认证实现类: ``` @Entity @Table(name = "roles") public class Role implements GrantedAuthority { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; // getters and setters @Override public String getAuthority() { return name; } } ``` ``` @Service public class RoleServiceImpl implements RoleService { @Autowired private RoleRepository roleRepository; @Override public Role findByName(String name) { return roleRepository.findByName(name); } } ``` 5. 创建控制器 创建一个控制器,用于测试权限校验: ``` @RestController public class TestController { @GetMapping("/admin") public String admin() { return "Hello Admin"; } @GetMapping("/user") public String user() { return "Hello User"; } } ``` 6. 启动应用程序 现在可以启动应用程序并访问控制器中的/admin和/user路径。只有具有相应角色的用户才能访问。 以上是在Spring Boot整合Spring Security进行权限校验的步骤,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值