spring security的java功能演示

下面是一个使用Java和Spring Security的详细示例代码。该示例演示了如何设置身份验证和授权规则,并保护特定的URL路径。请注意,这只是一个基本示例,您可以根据自己的需求进行修改和扩展。

首先,确保您已经安装了Java开发环境(JDK)和Maven构建工具。

接下来,我们将创建一个Maven项目,并在项目的pom.xml文件中添加以下依赖项:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.5.0</version>
    </dependency>
    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>2.5.0</version>
    </dependency>
</dependencies>

接下来,创建一个Spring Boot应用程序,并创建以下文件。

DemoApplication.java - 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

HomeController.java - 控制器

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "Welcome to the home page!";
    }

    @GetMapping("/admin")
    public String admin() {
        return "Welcome to the admin page!";
    }
}

SecurityConfig.java - 安全配置

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN") // 保护/admin路径,要求具有ADMIN角色
                .anyRequest().authenticated() // 其他路径需要身份验证
                .and()
            .formLogin() // 使用表单登录
                .and()
            .httpBasic(); // 启用基本身份验证
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER") // 创建一个名为"user"的用户,密码是"password",具有USER角色
                .and()
                .withUser("admin").password("{noop}password").roles("ADMIN"); // 创建一个名为"admin"的用户,密码是"password",具有ADMIN角色
    }
}

SecurityConfig.java中,我们使用configure(HttpSecurity http)方法配置了URL的访问规则和安全策略。在configure(AuthenticationManagerBuilder auth)方法中,我们使用内存认证配置了两个用户。

最后,在`src/main/resources/application

.properties`文件中添加以下配置:

spring.security.user.password.encoder=none

这将禁用密码编码,以便我们可以使用明文密码进行演示。在实际应用中,您应该使用适当的密码编码器。

现在,您可以运行应用程序并访问以下URL:

  • http://localhost:8080/ - 欢迎页面,无需身份验证。
  • http://localhost:8080/admin - 管理员页面,需要具有ADMIN角色的身份验证。

在浏览器中访问这些URL时,您将被重定向到登录页面。使用以下用户进行身份验证:

  • 用户名:user,密码:password(具有USER角色)
  • 用户名:admin,密码:password(具有ADMIN角色)

根据用户的角色,您将被授权或拒绝访问相应的页面。

这是一个基本的Spring Security示例,您可以根据需要进行修改和扩展。


更多功能

当然!这里有更多的Spring Security示例代码,以展示不同的功能和用例。

  1. 使用数据库进行身份验证:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    // ...
}

在这个例子中,我们使用UserDetailsService从数据库中获取用户信息进行身份验证。

  1. 自定义登录页面:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }

    // ...
}

在这个例子中,我们指定了自定义的登录页面路径为/login,并允许所有用户访问该页面。

  1. 使用记住我功能:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .rememberMe();
    }

    // ...
}

在这个例子中,我们启用了记住我功能,允许用户在关闭浏览器后仍然保持登录状态。

  1. 限制登录尝试次数:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(authenticationProvider())
            .userDetailsService(userDetailsService());
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        provider.setLockoutPolicy(new ExcessiveAttemptsLockoutPolicy());
        provider.setPreAuthenticationChecks(new UserDetailsChecker() {
            @Override
            public void check(UserDetails user) {
                // 自定义的用户验证逻辑
            }
        });
        return provider;
    }

    // ...
}

在这个例子中,我们使用DaoAuthenticationProvider设置了一个锁定策略,当用户登录尝试次数过多时会被锁定。

这些示例代码展示了Spring Security的不同功能和用例,您可以根据需要进行修改和扩展。


更多功能

当然!这里有更多的Spring Security示例代码,以展示不同的功能和用例。

  1. 为不同角色设置访问权限:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }

    // ...
}

在这个例子中,我们根据用户的角色设置了不同的访问权限。具有ADMIN角色的用户可以访问/admin/**路径,具有USER角色的用户可以访问/user/**路径,其他路径需要身份验证。

  1. 使用CSRF保护:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }

    // ...
}

在这个例子中,我们启用了CSRF(Cross-Site Request Forgery)保护,使用CookieCsrfTokenRepository将CSRF令牌存储在Cookie中。

  1. 使用JWT进行身份验证:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/public").permitAll()
                .antMatchers("/api/private").authenticated()
                .and()
            .apply(new JwtConfigurer(jwtTokenProvider));
    }

    // ...
}

在这个例子中,我们使用JWT(JSON Web Token)进行身份验证。我们定义了公共和私有的API路径,并使用自定义的JwtConfigurer配置了JWT验证。

  1. 使用注解进行方法级别的授权:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin();

        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();

        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    }

    // ...
}

在这个例子中,我们使用@PreAuthorize注解和@EnableGlobalMethodSecurity配置了方法级别的授权,以允许在方法上定义访问规则。

这些示例代码展示了Spring Security的不同功能和用例,您可以根据需要进行修改和扩展。如果您有特定的需求或问题,请告诉我,我将

为您提供更多帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值