自学内容网 自学内容网

Spring Security无脑使用

步骤1:添加Spring Security依赖

在你的Spring Boot项目的pom.xml文件中,添加Spring Security的依赖:

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

步骤2:写一个简单地hello接口:

步骤3:浏览器访问接口

默认的用户名是 user ,默认的登录密码 在每次启动项目时随机生成 查看项目启动日志:

从项目启动日志中可以看到默认的登录密码,登录成功后,就可以访问hello 接口了。

步骤4:自己配置账户名或者密码

步骤2:创建Spring Security配置类

创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure()方法来配置Spring Security的行为。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()  //这开始了一个授权请求的配置链。.authorizeRequests() 方法允许你指定哪些 URL 需要认证和授权。
                .antMatchers("/", "/home").permitAll() // 方法指定了两个 URL 模式,/ 和 /home。.permitAll() 表示这些 URL 可以被任何用户无条件访问,即使他们没有登录。
                .anyRequest().authenticated() //.anyRequest() 表示所有未被前面规则明确指定的请求。.authenticated() 指定这些请求需要经过身份验证才能访问。
                
                .and() //.and() 方法用于继续下一个配置步骤。在这里,它用于从授权请求配置切换到其他配置,如表单登录配置。
            
            .formLogin() //.formLogin() 配置了表单登录功能
                //.loginPage("/login") 指定了登录页面的 URL 注意:配置了.loginPage("/login") ,你必须写这个页面,如果不配置,就用Spring Security 内置的Form登录页面
                .permitAll()   // 表示这个登录页面可以被任何人访问,不需要身份验证。
                
                .and()  //同样地,.and() 用于继续到下一个配置步骤,这里是登出配置。

            .logout()   //.logout() 开始配置登出功能。
                .logoutUrl("/logout")  //设置了处理登出请求的 URL
                .logoutSuccessUrl("/login") //指定了登出成功后用户会被重定向到的 URL
                .invalidateHttpSession(true) //表示在登出时会销毁 HttpSession。
                .deleteCookies("JSESSIONID");   //用于删除 JSESSIONID cookie,以完全清除用户的会话


    }
}


原文地址:https://blog.csdn.net/zhzjn/article/details/142878343

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!