【springboot+security】2、HttpSecurity 的配置不同的拦截规则

1、配置不同的拦截规则

前一节我们没有对sping security做任何配置,现在我们要对不通的访问路径进行配置不同的拦截规则,那就需要我们配置HttpSecurity。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   


    @Bean
    PasswordEncoder passwordEncoder() {
   
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        auth.inMemoryAuthentication()
                .withUser("an").
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的基于 SpringBoot 和 Spring Security 的登录拦截 Demo: 1. 首先,需要添加 SpringBoot 和 Spring Security 的依赖,例如在 Maven 中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 在 SpringBoot 主类中,添加 `@EnableWebSecurity` 注解和继承 `WebSecurityConfigurerAdapter` 类,并实现其中的 `configure(HttpSecurity http)` 方法,例如: ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/secure/**").authenticated() .anyRequest().permitAll() .and() .formLogin().loginPage("/login").defaultSuccessURL("/secure/home").permitAll() .and() .logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}123456").roles("USER"); } } ``` 上面的代码中,`@EnableWebSecurity` 注解开启了 Spring Security 的 Web 安全功能。`configure(HttpSecurity http)` 方法定义了 HTTP 请求的安全配置,`.antMatchers("/secure/**").authenticated()` 定义了需要认证的 URL,`.formLogin().loginPage("/login").defaultSuccessURL("/secure/home").permitAll()` 定义了登录页面的 URL 和登录成功后的默认页面,`.logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()` 定义了退出登录后的跳转页面。`configure(AuthenticationManagerBuilder auth)` 方法定义了用户认证方式,这里使用了内存中的用户信息。 3. 添加登录页面和安全页面: 在 `login.html` 中,添加登录表单: ```html <form method="post" action="/login"> <input type="text" name="username" placeholder="Username" /> <input type="password" name="password" placeholder="Password" /> <button type="submit">Login</button> </form> ``` 在 `home.html` 中,添加安全页面的内容。 4. 在 application.properties 中添加用户名和密码加密方式: ```properties spring.security.user.password.encoder=noop ``` 这样就完成了一个简单的基于 SpringBoot 和 Spring Security 的登录拦截 Demo。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值