SpringBoot SpringSecurity怎么使用

springboot已经为用户采用默认配置,只需要引入pom依赖就能快速启动spring security。
目的:验证请求用户的身份,提供安全访问
优势:基于spring,配置方便,减少大量代码

SpringBoot SpringSecurity怎么使用

内置访问控制方法

permitAll() 表示所匹配的 URL 任何人都允许访问。

authenticated() 表示所匹配的 URL 都需要被认证才能访问。

anonymous() 表示可以匿名访问匹配的 URL 。和 permitAll() 效果类似,只是设置为 anonymous() 的 url 会执行 filter 链中

denyAll() 表示所匹配的 URL 都不允许被访问。

rememberMe() 被“remember me”的用户允许访问 这个有点类似于很多网站的十天内免登录,登陆一次即可记住你,然后未来一段时间不用登录。

fullyAuthenticated() 如果用户不是被 remember me 的,才可以访问。也就是必须一步一步按部就班的登录才行。

角色权限判断

hasAuthority(String) 判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑

hasAnyAuthority(String …) 如果用户具备给定权限中某一个,就允许访问

hasRole(String) 如果用户具备给定角色就允许访问。否则出现 403

hasAnyRole(String …) 如果用户具备给定角色的任意一个,就允许被访问

hasIpAddress(String) 如果请求是指定的 IP 就运行访问。可以通过 request.getRemoteAddr() 获取 ip 地址

引用 Spring Security

Pom 文件中添加

  1.    org.springframework.boot   spring-boot-starter-security

登录后复制

  1.             vipsoft-parent        com.vipsoft.boot        1.0-SNAPSHOT        4.0.0    vipsoft-security    1.0-SNAPSHOT                        cn.hutool            hutool-all            5.3.7                            org.springframework.boot            spring-boot-starter-security                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-test            test                                                org.junit.vintage                    junit-vintage-engine                                                                                org.springframework.boot                spring-boot-maven-plugin                        

登录后复制

运行后会自动生成 password 默认用户名为: user

SpringBoot SpringSecurity怎么使用

默认配置每次都启动项目都会重新生成密码,同时用户名和拦截请求也不能自定义,在实际应用中往往需要自定义配置,因此接下来对Spring Security进行自定义配置。

配置 Spring Security (入门)

在内存中(简化环节,了解逻辑)配置两个用户角色(admin和user),设置不同密码;
同时设置角色访问权限,其中admin可以访问所有路径(即/*),user只能访问/user下的所有路径。

自定义配置类,实现WebSecurityConfigurerAdapter接口,WebSecurityConfigurerAdapter接口中有两个用到的 configure()方法,其中一个配置用户身份,另一个配置用户权限:

配置用户身份的configure()方法:

SecurityConfig

  1. package com.vipsoft.web.config;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;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;import org.springframework.security.crypto.password.PasswordEncoder;@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {    /**     * 配置用户身份的configure()方法     *     * @param auth     * @throws Exception     */    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();        //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中        auth.inMemoryAuthentication()                .passwordEncoder(passwordEncoder)                .withUser("admin")                .password(passwordEncoder.encode("888"))                .roles("ADMIN")                .and()                .withUser("user")                .password(passwordEncoder.encode("666"))                .roles("USER");    }    /**     * 配置用户权限的configure()方法     * @param http     * @throws Exception     */    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()                //配置拦截的路径、配置哪类角色可以访问该路径                .antMatchers("/user").hasAnyRole("USER")                .antMatchers("/*").hasAnyRole("ADMIN")                //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面                .and().formLogin();    }}

登录后复制

添加接口测试用

  1. package com.vipsoft.web.controller;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class DefaultController {    @GetMapping("/")    @PreAuthorize("hasRole('ADMIN')")    public String demo() {        return "Welcome";    }    @GetMapping("/user/list")    @PreAuthorize("hasAnyRole('ADMIN','USER')")    public String getUserList() {        return "User List";    }    @GetMapping("/article/list")    @PreAuthorize("hasRole('ADMIN')")    public String getArticleList() {        return "Article List";    }}

登录后复制

SpringBoot SpringSecurity怎么使用

以上就是SpringBoot SpringSecurity怎么使用的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
编程技术

怎么在SpringBoot中使用Spring AOP实现接口鉴权

2025-3-7 0:49:31

编程技术

怎么构建springboot web应用镜像并使用容器部署

2025-3-7 0:49:37

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
私信列表
搜索